Spaces:
Runtime error
Runtime error
Update ocr_engine.py
Browse files- ocr_engine.py +28 -14
ocr_engine.py
CHANGED
@@ -1,29 +1,43 @@
|
|
1 |
-
import
|
2 |
import numpy as np
|
3 |
import cv2
|
4 |
import re
|
5 |
|
|
|
|
|
|
|
6 |
def extract_weight_from_image(pil_img):
|
7 |
try:
|
8 |
-
# Convert
|
9 |
img = np.array(pil_img)
|
10 |
|
11 |
-
# Resize and
|
12 |
-
img = cv2.resize(img, None, fx=
|
13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
|
16 |
-
|
|
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
print("OCR TEXT:", text)
|
21 |
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
return match.group(), 99.0
|
26 |
-
return "Not detected", 0.0
|
27 |
|
28 |
except Exception as e:
|
29 |
return f"Error: {str(e)}", 0.0
|
|
|
1 |
+
import easyocr
|
2 |
import numpy as np
|
3 |
import cv2
|
4 |
import re
|
5 |
|
6 |
+
# Initialize OCR reader once
|
7 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
8 |
+
|
9 |
def extract_weight_from_image(pil_img):
|
10 |
try:
|
11 |
+
# Convert image to NumPy format
|
12 |
img = np.array(pil_img)
|
13 |
|
14 |
+
# Resize and preprocess
|
15 |
+
img = cv2.resize(img, None, fx=3.5, fy=3.5, interpolation=cv2.INTER_LINEAR)
|
16 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
17 |
+
gray = cv2.bilateralFilter(gray, 11, 17, 17)
|
18 |
+
_, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
19 |
+
|
20 |
+
# OCR
|
21 |
+
results = reader.readtext(thresh)
|
22 |
+
|
23 |
+
# Debug
|
24 |
+
print("OCR Results:", results)
|
25 |
+
|
26 |
+
weight_candidates = []
|
27 |
+
for _, text, conf in results:
|
28 |
+
clean = text.lower().replace("kg", "").strip()
|
29 |
+
clean = clean.replace("o", "0").replace("O", "0") # fix OCR misreads
|
30 |
|
31 |
+
# Match weights like 86, 85.5, 102.3
|
32 |
+
if re.fullmatch(r"\d{2,4}(\.\d{1,2})?", clean):
|
33 |
+
weight_candidates.append((clean, conf))
|
34 |
|
35 |
+
if not weight_candidates:
|
36 |
+
return "Not detected", 0.0
|
|
|
37 |
|
38 |
+
# Return best candidate
|
39 |
+
best_weight, best_conf = sorted(weight_candidates, key=lambda x: -x[1])[0]
|
40 |
+
return best_weight, round(best_conf * 100, 2)
|
|
|
|
|
41 |
|
42 |
except Exception as e:
|
43 |
return f"Error: {str(e)}", 0.0
|