Spaces:
Build error
Build error
File size: 1,731 Bytes
c28abeb c11fb3a 8f557ef c28abeb 8f557ef 8c624d2 c11fb3a adab0b4 8c624d2 adab0b4 c11fb3a adab0b4 cfcd3d5 c11fb3a 8c624d2 c11fb3a c28abeb 8c624d2 c11fb3a 1362c73 8c624d2 c28abeb adab0b4 8c624d2 c28abeb 8c624d2 c11fb3a adab0b4 8c624d2 cfcd3d5 8c624d2 c11fb3a 8c624d2 c11fb3a 8c624d2 c11fb3a 8c624d2 c11fb3a 8c624d2 42b463a 393f381 adab0b4 c11fb3a |
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 51 52 53 54 55 56 57 58 |
import numpy as np
import re
import cv2
from PIL import Image
import easyocr
# β
Initialize EasyOCR Reader once
reader = easyocr.Reader(['en'], gpu=False)
def preprocess_image(image):
"""
Convert to grayscale and apply adaptive thresholding
to enhance contrast for digital scale OCR.
"""
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
thresh = cv2.adaptiveThreshold(
gray, 255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY_INV,
11, 10
)
return thresh
def extract_weight_from_image(pil_image):
try:
# β
Convert PIL image to OpenCV format
image = np.array(pil_image.convert("RGB"))
# β
Preprocess image
processed = preprocess_image(image)
# β
Optional: Save debug image for troubleshooting
debug_path = "debug_processed_image.png"
Image.fromarray(processed).save(debug_path)
print(f"[DEBUG] Preprocessed image saved to: {debug_path}")
# β
Perform OCR using EasyOCR
result = reader.readtext(processed)
print("π OCR Results:")
for detection in result:
print(f" β’ Text: '{detection[1]}' | Confidence: {detection[2]*100:.2f}%")
# β
Extract first matching numeric value
for detection in result:
text = detection[1].replace(",", ".") # normalize decimal
conf = detection[2]
match = re.search(r"\b\d{1,4}(\.\d{1,2})?\b", text)
if match:
return match.group(), round(conf * 100, 2)
# β No weight found
return "No weight detected", 0.0
except Exception as e:
print(f"β OCR Error: {e}")
return f"Error: {str(e)}", 0.0
|