Spaces:
Runtime error
Runtime error
File size: 1,155 Bytes
6b14fa5 65ed4c1 8fe1b94 a71f519 6b14fa5 65ed4c1 363a646 65ed4c1 363a646 65ed4c1 a71f519 363a646 a71f519 701d11a a71f519 33069a9 a71f519 33069a9 a71f519 33069a9 a71f519 33069a9 a71f519 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 |
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)
# Grayscale + resize
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
# Histogram equalization
gray = cv2.equalizeHist(gray)
# Adaptive threshold
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
# Invert colors (LCD digits are usually dark on light)
thresh = cv2.bitwise_not(thresh)
# OCR
result = reader.readtext(thresh, detail=0)
combined_text = " ".join(result)
print("OCR Text:", combined_text)
# Match weight pattern (e.g. 52.30, 003.2, 250)
match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", combined_text)
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
|