Spaces:
Runtime error
Runtime error
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) | |
# Resize and convert to grayscale | |
img = cv2.resize(img, None, fx=2.5, fy=2.5, interpolation=cv2.INTER_LINEAR) | |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) | |
# Apply Gaussian blur to remove noise | |
blurred = cv2.GaussianBlur(gray, (5, 5), 0) | |
# Apply adaptive threshold | |
thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, | |
cv2.THRESH_BINARY_INV, 15, 6) | |
# OCR | |
results = reader.readtext(thresh) | |
# Debug: Print all detected text | |
print("OCR Results:", results) | |
weight_candidates = [] | |
for _, text, conf in results: | |
text = text.lower().replace('kg', '').replace('kgs', '').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 | |
# Return the one with 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 | |