import easyocr import numpy as np import re import cv2 reader = easyocr.Reader(['en'], gpu=False) def extract_weight_from_image(pil_img): try: img = np.array(pil_img) # Preprocessing gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) resized = cv2.resize(gray, None, fx=2.5, fy=2.5, interpolation=cv2.INTER_CUBIC) blurred = cv2.GaussianBlur(resized, (3, 3), 0) _, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # OCR result = reader.readtext(thresh, detail=0) combined_text = " ".join(result) print("OCR Result:", combined_text) # Improve regex to only match numbers with optional decimal match = re.search(r"\b(?:\d{1,3}\.?\d{1,2}|\d{1,4})\b", combined_text) if match: return match.group(), 95.0 else: return "No weight detected", 0.0 except Exception as e: return f"Error: {str(e)}", 0.0