AutoWeightLogger1 / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
5665756 verified
raw
history blame
1.19 kB
import easyocr
import numpy as np
import cv2
import re
# Initialize OCR reader once
reader = easyocr.Reader(['en'], gpu=False)
def extract_weight_from_image(pil_img):
try:
img = np.array(pil_img)
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Resize for better accuracy
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
# Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
# Invert colors: useful for LCD display images
inverted = cv2.bitwise_not(blurred)
# Normalize brightness
norm_img = cv2.normalize(inverted, None, 0, 255, cv2.NORM_MINMAX)
# Perform OCR
result = reader.readtext(norm_img, detail=0)
combined_text = " ".join(result)
print("OCR Text:", combined_text)
# Regex to detect numbers (e.g. 25, 75.45, 100.00)
match = re.search(r"\b\d{1,4}(\.\d{1,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