AutoWeightLogger1 / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
7dd3534 verified
raw
history blame
1.12 kB
import easyocr
import numpy as np
import re
import cv2
reader = easyocr.Reader(['en'], gpu=False)
def extract_weight_from_image(pil_img):
try:
img = np.array(pil_img)
# Step 1: Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Step 2: Apply adaptive threshold to handle lighting
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
# Step 3: Dilate to make digits thicker
kernel = np.ones((2, 2), np.uint8)
dilated = cv2.dilate(thresh, kernel, iterations=1)
# Step 4: OCR on the preprocessed image
result = reader.readtext(dilated, detail=0)
text = " ".join(result).strip()
print("OCR Text:", text)
# Step 5: Match numeric values like 52.30 or 003.25
match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", 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