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) | |
# Resize for consistency | |
if img.shape[1] > 1000: | |
img = cv2.resize(img, (1000, int(img.shape[0] * 1000 / img.shape[1]))) | |
# Preprocessing for 7-segment digital font | |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) | |
gray = cv2.resize(gray, None, fx=3, fy=3, interpolation=cv2.INTER_LINEAR) | |
blur = cv2.GaussianBlur(gray, (3, 3), 0) | |
_, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) | |
# Optional inversion for black background with white digits | |
white_pct = np.mean(thresh > 127) | |
if white_pct < 0.5: | |
thresh = cv2.bitwise_not(thresh) | |
# OCR | |
result = reader.readtext(thresh, detail=0) | |
combined_text = " ".join(result).strip() | |
print("OCR Text:", combined_text) | |
# Match number like 25, 65.2, 18.89 etc. | |
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", combined_text) | |
if match: | |
weight = match.group(1) | |
return f"{weight} kg", 100.0 | |
else: | |
return "No weight detected kg", 0.0 | |
except Exception as e: | |
return f"Error: {str(e)}", 0.0 | |