Spaces:
Runtime error
Runtime error
import pytesseract | |
import numpy as np | |
import cv2 | |
import re | |
def extract_weight_from_image(pil_img): | |
try: | |
# Convert PIL to OpenCV format | |
img = np.array(pil_img) | |
# Resize and convert to grayscale | |
img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) | |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) | |
# Thresholding for clarity | |
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV) | |
# Run OCR | |
text = pytesseract.image_to_string(thresh) | |
print("OCR TEXT:", text) | |
# Search for weight pattern | |
match = re.search(r"\b\d{2,4}(\.\d{1,2})?\b", text) | |
if match: | |
return match.group(), 99.0 | |
return "Not detected", 0.0 | |
except Exception as e: | |
return f"Error: {str(e)}", 0.0 | |