Spaces:
Runtime error
Runtime error
Update ocr_engine.py
Browse files- ocr_engine.py +8 -10
ocr_engine.py
CHANGED
@@ -3,26 +3,23 @@ import numpy as np
|
|
3 |
import cv2
|
4 |
import re
|
5 |
|
|
|
6 |
reader = easyocr.Reader(['en'], gpu=False)
|
7 |
|
8 |
def enhance_image(img):
|
9 |
-
#
|
10 |
img = cv2.resize(img, None, fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
|
11 |
-
|
12 |
-
# Convert to gray
|
13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
14 |
|
15 |
# Denoise
|
16 |
gray = cv2.fastNlMeansDenoising(gray, h=15)
|
17 |
|
18 |
# Sharpen
|
19 |
-
kernel = np.array([[0, -1, 0],
|
20 |
-
[-1, 5,-1],
|
21 |
-
[0, -1, 0]])
|
22 |
sharp = cv2.filter2D(gray, -1, kernel)
|
23 |
|
24 |
-
# Contrast
|
25 |
-
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
26 |
contrast = clahe.apply(sharp)
|
27 |
|
28 |
return contrast
|
@@ -33,12 +30,13 @@ def extract_weight_from_image(pil_img):
|
|
33 |
enhanced = enhance_image(img)
|
34 |
|
35 |
results = reader.readtext(enhanced)
|
|
|
|
|
36 |
ocr_texts = [text for _, text, _ in results]
|
37 |
weight_candidates = []
|
38 |
|
39 |
for _, text, conf in results:
|
40 |
-
cleaned = text.lower()
|
41 |
-
cleaned = cleaned.replace("kg", "").replace("kgs", "")
|
42 |
cleaned = cleaned.replace("o", "0").replace("s", "5").replace("g", "9")
|
43 |
cleaned = re.sub(r"[^\d\.]", "", cleaned)
|
44 |
|
|
|
3 |
import cv2
|
4 |
import re
|
5 |
|
6 |
+
# Load OCR model once
|
7 |
reader = easyocr.Reader(['en'], gpu=False)
|
8 |
|
9 |
def enhance_image(img):
|
10 |
+
# Enlarge and convert to grayscale
|
11 |
img = cv2.resize(img, None, fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
|
|
|
|
|
12 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
13 |
|
14 |
# Denoise
|
15 |
gray = cv2.fastNlMeansDenoising(gray, h=15)
|
16 |
|
17 |
# Sharpen
|
18 |
+
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
|
|
|
|
|
19 |
sharp = cv2.filter2D(gray, -1, kernel)
|
20 |
|
21 |
+
# Contrast enhance
|
22 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
23 |
contrast = clahe.apply(sharp)
|
24 |
|
25 |
return contrast
|
|
|
30 |
enhanced = enhance_image(img)
|
31 |
|
32 |
results = reader.readtext(enhanced)
|
33 |
+
print("DEBUG OCR RESULTS:", results)
|
34 |
+
|
35 |
ocr_texts = [text for _, text, _ in results]
|
36 |
weight_candidates = []
|
37 |
|
38 |
for _, text, conf in results:
|
39 |
+
cleaned = text.lower().replace("kg", "").replace("kgs", "")
|
|
|
40 |
cleaned = cleaned.replace("o", "0").replace("s", "5").replace("g", "9")
|
41 |
cleaned = re.sub(r"[^\d\.]", "", cleaned)
|
42 |
|