Spaces:
Build error
Build error
File size: 1,602 Bytes
c11fb3a 8f557ef b902588 8f557ef b902588 8f557ef b902588 c11fb3a adab0b4 b902588 adab0b4 c11fb3a b902588 adab0b4 b902588 adab0b4 b902588 adab0b4 b902588 c11fb3a b902588 c11fb3a c28abeb 8c624d2 c11fb3a 1362c73 b902588 c28abeb adab0b4 b902588 c28abeb b902588 c11fb3a b902588 cfcd3d5 b902588 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 |
import re
import cv2
import numpy as np
from PIL import Image
from paddleocr import PaddleOCR
# β
Initialize PaddleOCR once
ocr = PaddleOCR(use_angle_cls=False, lang='en', show_log=False)
def preprocess_image(image):
"""
Convert to grayscale and enhance contrast to help OCR.
"""
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
processed = cv2.adaptiveThreshold(
gray, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,
11, 2
)
return processed
def extract_weight_from_image(pil_image):
try:
# β
Convert to OpenCV format
image = np.array(pil_image.convert("RGB"))
# β
Preprocess image
processed = preprocess_image(image)
# Optional: Save debug image
debug_path = "debug_processed_image.png"
Image.fromarray(processed).save(debug_path)
print(f"[DEBUG] Saved preprocessed image to {debug_path}")
# β
Run OCR on original (RGB) image (not preprocessed)
result = ocr.ocr(image, cls=False)
print("π PaddleOCR Results:")
for line in result[0]:
text = line[1][0]
conf = line[1][1]
print(f" β’ Text: '{text}' | Confidence: {conf*100:.2f}%")
# Try to extract number like 53.25 or 100
match = re.search(r"\b\d{1,4}(\.\d{1,2})?\b", text)
if match:
return match.group(), round(conf * 100, 2)
return "No weight detected", 0.0
except Exception as e:
print(f"β OCR Error: {e}")
return f"Error: {str(e)}", 0.0
|