AutoWeightLogger / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
e91f073 verified
raw
history blame
1.38 kB
import easyocr
import numpy as np
import cv2
import re
reader = easyocr.Reader(['en'], gpu=False)
def extract_weight_from_image(pil_img):
try:
img = np.array(pil_img)
# STEP 1: Resize and convert to grayscale
img = cv2.resize(img, None, fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# STEP 2: Denoise + Threshold
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Invert to get black text on white background
inverted = cv2.bitwise_not(thresh)
# STEP 3: OCR
results = reader.readtext(inverted)
# Debug print
print("OCR Results:", results)
# STEP 4: Extract weight values using regex
weight_candidates = []
for _, text, conf in results:
text = text.replace("kg", "").replace("KG", "").strip()
if re.match(r"^\d{2,4}(\.\d{1,2})?$", text):
weight_candidates.append((text, conf))
if not weight_candidates:
return "Not detected", 0.0
# STEP 5: Highest confidence
weight, confidence = sorted(weight_candidates, key=lambda x: -x[1])[0]
return weight, round(confidence * 100, 2)
except Exception as e:
return f"Error: {str(e)}", 0.0