import numpy as np import re import cv2 from PIL import Image import easyocr # ✅ Initialize EasyOCR Reader once reader = easyocr.Reader(['en'], gpu=False) def preprocess_image(image): """ Convert to grayscale and apply adaptive thresholding to enhance contrast for digital scale OCR. """ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) thresh = cv2.adaptiveThreshold( gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, 10 ) return thresh def extract_weight_from_image(pil_image): try: # ✅ Convert PIL image to OpenCV format image = np.array(pil_image.convert("RGB")) # ✅ Preprocess image processed = preprocess_image(image) # ✅ Optional: Save debug image for troubleshooting debug_path = "debug_processed_image.png" Image.fromarray(processed).save(debug_path) print(f"[DEBUG] Preprocessed image saved to: {debug_path}") # ✅ Perform OCR using EasyOCR result = reader.readtext(processed) print("🔍 OCR Results:") for detection in result: print(f" • Text: '{detection[1]}' | Confidence: {detection[2]*100:.2f}%") # ✅ Extract first matching numeric value for detection in result: text = detection[1].replace(",", ".") # normalize decimal conf = detection[2] match = re.search(r"\b\d{1,4}(\.\d{1,2})?\b", text) if match: return match.group(), round(conf * 100, 2) # ❌ No weight found return "No weight detected", 0.0 except Exception as e: print(f"❌ OCR Error: {e}") return f"Error: {str(e)}", 0.0