Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +14 -16
ocr_engine.py
CHANGED
@@ -3,39 +3,37 @@ 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 |
img = np.array(pil_img)
|
12 |
|
13 |
-
#
|
14 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
15 |
-
|
16 |
-
# Resize for better accuracy
|
17 |
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
|
18 |
|
19 |
-
#
|
|
|
20 |
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
|
21 |
-
|
22 |
-
# Invert colors: useful for LCD display images
|
23 |
inverted = cv2.bitwise_not(blurred)
|
24 |
|
25 |
-
#
|
26 |
-
|
27 |
-
|
28 |
-
# Perform OCR
|
29 |
-
result = reader.readtext(norm_img, detail=0)
|
30 |
combined_text = " ".join(result)
|
31 |
print("OCR Text:", combined_text)
|
32 |
|
33 |
-
#
|
34 |
-
match = re.search(r
|
35 |
if match:
|
36 |
-
return match.group(), 95.0
|
37 |
else:
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
except Exception as e:
|
41 |
return f"Error: {str(e)}", 0.0
|
|
|
3 |
import cv2
|
4 |
import re
|
5 |
|
|
|
6 |
reader = easyocr.Reader(['en'], gpu=False)
|
7 |
|
8 |
def extract_weight_from_image(pil_img):
|
9 |
try:
|
10 |
img = np.array(pil_img)
|
11 |
|
12 |
+
# Grayscale and resize
|
13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
|
|
|
|
14 |
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
|
15 |
|
16 |
+
# Enhance contrast
|
17 |
+
gray = cv2.equalizeHist(gray)
|
18 |
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
|
|
|
|
|
19 |
inverted = cv2.bitwise_not(blurred)
|
20 |
|
21 |
+
# OCR
|
22 |
+
result = reader.readtext(inverted, detail=0)
|
|
|
|
|
|
|
23 |
combined_text = " ".join(result)
|
24 |
print("OCR Text:", combined_text)
|
25 |
|
26 |
+
# Match weight in KG (like 25kg or 25.00 kg)
|
27 |
+
match = re.search(r'(\d{1,4}(?:\.\d{1,2})?)\s?(kg)', combined_text, re.IGNORECASE)
|
28 |
if match:
|
29 |
+
return f"{match.group(1)} kg", 95.0
|
30 |
else:
|
31 |
+
# Fallback to just number
|
32 |
+
fallback = re.search(r'\d{1,4}(?:\.\d{1,2})?', combined_text)
|
33 |
+
if fallback:
|
34 |
+
return f"{fallback.group(0)} kg", 90.0
|
35 |
+
|
36 |
+
return "No weight detected kg", 0.0
|
37 |
|
38 |
except Exception as e:
|
39 |
return f"Error: {str(e)}", 0.0
|