Spaces:
Running
Running
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) | |
# Preprocessing for OCR | |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) | |
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR) | |
gray = cv2.equalizeHist(gray) | |
gray = cv2.GaussianBlur(gray, (3, 3), 0) | |
inverted = cv2.bitwise_not(gray) | |
# OCR read | |
result = reader.readtext(inverted, detail=0) | |
combined_text = " ".join(result) | |
print("OCR Raw Text:", combined_text) | |
# First try matching with "kg" | |
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)\s*(kg|KG|Kg)", combined_text) | |
if match: | |
return f"{match.group(1)} kg", 95.0 | |
# Then try fallback match: only numbers | |
fallback = re.search(r"\d{1,4}(?:\.\d{1,2})?", combined_text) | |
if fallback: | |
return f"{fallback.group(0)} kg", 75.0 | |
return "No weight detected kg", 0.0 | |
except Exception as e: | |
return f"Error: {str(e)}", 0.0 | |