Autoweight / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
8c624d2 verified
raw
history blame
1.73 kB
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