Spaces:
Runtime error
Runtime error
Create ocr_engine.py
Browse files- ocr_engine.py +38 -0
ocr_engine.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import easyocr
|
2 |
+
import numpy as np
|
3 |
+
import re
|
4 |
+
import cv2
|
5 |
+
|
6 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
7 |
+
|
8 |
+
def extract_weight_from_image(pil_image):
|
9 |
+
try:
|
10 |
+
image = np.array(pil_image)
|
11 |
+
|
12 |
+
# Grayscale conversion
|
13 |
+
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
14 |
+
|
15 |
+
# Resize to make digits clearer
|
16 |
+
resized = cv2.resize(gray, None, fx=3, fy=3, interpolation=cv2.INTER_CUBIC)
|
17 |
+
|
18 |
+
# Bilateral Filter to reduce noise
|
19 |
+
filtered = cv2.bilateralFilter(resized, 11, 17, 17)
|
20 |
+
|
21 |
+
# Adaptive Thresholding
|
22 |
+
thresh = cv2.adaptiveThreshold(filtered, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
23 |
+
cv2.THRESH_BINARY, 11, 2)
|
24 |
+
|
25 |
+
# OCR
|
26 |
+
result = reader.readtext(thresh, detail=0)
|
27 |
+
text = " ".join(result)
|
28 |
+
print("OCR Output:", text)
|
29 |
+
|
30 |
+
# Extract weight like 25.52 or 123
|
31 |
+
match = re.search(r'\d{1,4}(\.\d{1,2})?', text)
|
32 |
+
if match:
|
33 |
+
return match.group(), 95.0
|
34 |
+
else:
|
35 |
+
return "No weight detected", 0.0
|
36 |
+
|
37 |
+
except Exception as e:
|
38 |
+
return f"Error: {str(e)}", 0.0
|