Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +20 -29
ocr_engine.py
CHANGED
@@ -1,50 +1,41 @@
|
|
1 |
-
import easyocr
|
2 |
-
import numpy as np
|
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 |
-
# Resize image for consistency
|
13 |
-
if img.shape[1] > 1000:
|
14 |
-
img = cv2.resize(img, (1000, int(img.shape[0] * 1000 / img.shape[1])))
|
15 |
-
|
16 |
# Convert to grayscale
|
17 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
18 |
|
19 |
-
#
|
20 |
-
|
21 |
-
|
22 |
-
# Histogram Equalization and slight blur
|
23 |
-
gray = cv2.equalizeHist(gray)
|
24 |
-
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
|
25 |
-
|
26 |
-
# Adaptive threshold
|
27 |
-
thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
28 |
-
cv2.THRESH_BINARY, 11, 2)
|
29 |
|
30 |
# Invert if needed
|
31 |
-
|
32 |
-
if white_ratio < 0.5:
|
33 |
thresh = cv2.bitwise_not(thresh)
|
34 |
|
35 |
-
#
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
-
|
41 |
-
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", combined_text)
|
42 |
if match:
|
43 |
-
|
44 |
-
return f"{weight} kg", 100.0
|
45 |
else:
|
46 |
return "No weight detected kg", 0.0
|
47 |
|
48 |
except Exception as e:
|
49 |
-
print("❌ OCR Error:", e)
|
50 |
return f"Error: {str(e)}", 0.0
|
|
|
|
|
|
|
1 |
import cv2
|
2 |
+
import numpy as np
|
3 |
import re
|
4 |
+
from PIL import Image
|
|
|
5 |
|
6 |
def extract_weight_from_image(pil_img):
|
7 |
try:
|
8 |
img = np.array(pil_img)
|
9 |
|
|
|
|
|
|
|
|
|
10 |
# Convert to grayscale
|
11 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
12 |
|
13 |
+
# Threshold image
|
14 |
+
_, thresh = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
# Invert if needed
|
17 |
+
if np.mean(thresh > 127) < 0.5:
|
|
|
18 |
thresh = cv2.bitwise_not(thresh)
|
19 |
|
20 |
+
# Resize to make digits bigger
|
21 |
+
scale_factor = 4
|
22 |
+
resized = cv2.resize(thresh, None, fx=scale_factor, fy=scale_factor, interpolation=cv2.INTER_LINEAR)
|
23 |
+
|
24 |
+
# OCR-style region crop: focus on left part of display
|
25 |
+
height, width = resized.shape
|
26 |
+
digit_region = resized[0:height, 0:int(width * 0.7)] # ignore 'kg'
|
27 |
+
|
28 |
+
# Use pytesseract as fallback OCR for just digits
|
29 |
+
import pytesseract
|
30 |
+
config = "--psm 7 -c tessedit_char_whitelist=0123456789."
|
31 |
+
result = pytesseract.image_to_string(digit_region, config=config)
|
32 |
+
print("Raw OCR:", result)
|
33 |
|
34 |
+
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", result)
|
|
|
35 |
if match:
|
36 |
+
return f"{match.group()} kg", 100.0
|
|
|
37 |
else:
|
38 |
return "No weight detected kg", 0.0
|
39 |
|
40 |
except Exception as e:
|
|
|
41 |
return f"Error: {str(e)}", 0.0
|