AutoWeightLogger1 / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
f617821 verified
raw
history blame
1.23 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)
# Resize if image is too large
if img.shape[1] > 1000:
img = cv2.resize(img, (1000, int(img.shape[0] * 1000 / img.shape[1])))
# Preprocessing
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
gray = cv2.equalizeHist(gray)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.adaptiveThreshold(
blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2
)
# OCR
result = reader.readtext(thresh, detail=0)
combined_text = " ".join(result)
print("OCR Text:", combined_text)
# Regex to match numbers with optional 'kg'
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)\s*(kg|KG|Kg)?", combined_text)
if match:
weight = match.group(1)
return f"{weight} kg", 95.0
else:
return "No weight detected kg", 0.0
except Exception as e:
return f"Error: {str(e)}", 0.0