Spaces:
Build error
Build error
File size: 1,245 Bytes
8f557ef 42b463a 393f381 7605648 1362c73 7605648 ba02b0d 7605648 2c62dab 7605648 ba02b0d 7605648 e4046d9 7605648 42b463a 1362c73 7605648 1362c73 393f381 7605648 |
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 cv2
import pytesseract
import numpy as np
from PIL import Image
def extract_weight_from_image(pil_img):
try:
# Step 1: Convert PIL to OpenCV
img = pil_img.convert("L") # grayscale
img = np.array(img)
# Step 2: Resize image for better OCR accuracy
img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
# Step 3: Apply Gaussian Blur to remove noise
blur = cv2.GaussianBlur(img, (5, 5), 0)
# Step 4: Apply Adaptive Thresholding
thresh = cv2.adaptiveThreshold(
blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2
)
# Step 5: OCR Config - digits only
config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.'
# Step 6: Run OCR
text = pytesseract.image_to_string(thresh, config=config)
print("🔍 OCR RAW OUTPUT:", repr(text)) # view this in Hugging Face logs
# Step 7: Extract numbers
weight = ''.join(filter(lambda c: c in '0123456789.', text))
confidence = 95 if weight else 0
return weight.strip(), confidence
except Exception as e:
print("❌ OCR Exception:", str(e))
return "", 0
|