Spaces:
Build error
Build error
import easyocr | |
import re | |
import cv2 | |
import numpy as np | |
from PIL import Image | |
# Initialize EasyOCR reader | |
reader = easyocr.Reader(['en'], gpu=False) | |
def preprocess_image(image): | |
# Convert to grayscale | |
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
# Blur + Otsu thresholding | |
blur = cv2.GaussianBlur(gray, (3, 3), 0) | |
_, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) | |
return thresh | |
def extract_weight_from_image(pil_image): | |
try: | |
# Convert PIL image to OpenCV image | |
image = np.array(pil_image.convert("RGB")) | |
processed = preprocess_image(image) | |
# OCR | |
result = reader.readtext(processed) | |
print("OCR Results:", result) # for debugging | |
weight = None | |
confidence = 0.0 | |
for detection in result: | |
text = detection[1] | |
conf = detection[2] | |
match = re.search(r"\b\d+(\.\d+)?\b", text) # more flexible matching | |
if match: | |
weight = match.group() | |
confidence = conf | |
break | |
if weight: | |
return weight, round(confidence * 100, 2) | |
else: | |
return "No weight detected", 0.0 | |
except Exception as e: | |
return f"Error: {str(e)}", 0.0 | |