Spaces:
Runtime error
Runtime error
File size: 1,466 Bytes
6b14fa5 65ed4c1 5b73d24 8fe1b94 6b14fa5 65ed4c1 363a646 65ed4c1 363a646 65ed4c1 33069a9 363a646 701d11a 33069a9 7dd3534 33069a9 7dd3534 33069a9 8fe1b94 33069a9 65ed4c1 8fe1b94 65ed4c1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import easyocr
import numpy as np
import re
import cv2
reader = easyocr.Reader(['en'], gpu=False)
def extract_weight_from_image(pil_img):
try:
img = np.array(pil_img)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Apply bilateral filter to reduce noise while keeping edges
filtered = cv2.bilateralFilter(gray, 11, 17, 17)
# Apply binary threshold
_, thresh = cv2.threshold(filtered, 150, 255, cv2.THRESH_BINARY_INV)
# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
return "No weight detected", 0.0
# Get the largest contour assuming it's the display area
largest_contour = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(largest_contour)
# Add padding
pad = 10
x, y = max(x - pad, 0), max(y - pad, 0)
cropped = gray[y:y+h+pad, x:x+w+pad]
# OCR on cropped area
result = reader.readtext(cropped, detail=0)
combined = " ".join(result)
print("Detected Text:", combined)
# Match weight patterns like 52.30 or 003.25
match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", combined)
if match:
return match.group(), 95.0
else:
return "No weight detected", 0.0
except Exception as e:
return f"Error: {str(e)}", 0.0
|