AutoWeightLogger / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
1379dcc verified
raw
history blame
1.19 kB
import easyocr
import numpy as np
import cv2
import re
reader = easyocr.Reader(['en'], gpu=False)
def extract_weight_from_image(pil_img):
try:
img = np.array(pil_img)
# Convert to grayscale and resize for better clarity
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
# Histogram equalization
gray = cv2.equalizeHist(gray)
# Adaptive threshold to enhance text
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
# Invert for LCD-like contrast
thresh = cv2.bitwise_not(thresh)
# OCR read
result = reader.readtext(thresh, detail=0)
combined_text = " ".join(result)
print("OCR Text:", combined_text)
# Regex to match weight like 25, 46.5, 75.45 etc.
match = re.search(r"\b\d{2,4}\.?\d{0,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