Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +14 -12
ocr_engine.py
CHANGED
@@ -9,27 +9,29 @@ def extract_weight_from_image(pil_img):
|
|
9 |
try:
|
10 |
img = np.array(pil_img)
|
11 |
|
12 |
-
# Resize
|
13 |
if img.shape[1] > 1000:
|
14 |
img = cv2.resize(img, (1000, int(img.shape[0] * 1000 / img.shape[1])))
|
15 |
|
16 |
-
#
|
17 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
18 |
-
gray = cv2.resize(gray, None, fx=
|
19 |
-
|
20 |
-
|
21 |
|
22 |
-
#
|
23 |
-
|
24 |
-
|
|
|
|
|
25 |
thresh = cv2.bitwise_not(thresh)
|
26 |
|
27 |
# OCR
|
28 |
result = reader.readtext(thresh, detail=0)
|
29 |
-
|
30 |
-
|
31 |
|
32 |
-
#
|
33 |
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", combined_text)
|
34 |
if match:
|
35 |
weight = match.group(1)
|
@@ -38,5 +40,5 @@ def extract_weight_from_image(pil_img):
|
|
38 |
return "No weight detected kg", 0.0
|
39 |
|
40 |
except Exception as e:
|
|
|
41 |
return f"Error: {str(e)}", 0.0
|
42 |
-
|
|
|
9 |
try:
|
10 |
img = np.array(pil_img)
|
11 |
|
12 |
+
# Resize if image is large
|
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 and upscale
|
17 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
18 |
+
gray = cv2.resize(gray, None, fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
|
19 |
+
gray = cv2.GaussianBlur(gray, (5, 5), 0)
|
20 |
+
gray = cv2.equalizeHist(gray)
|
21 |
|
22 |
+
# Thresholding
|
23 |
+
_, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
24 |
+
|
25 |
+
# Invert if needed
|
26 |
+
if np.mean(thresh > 127) < 0.5:
|
27 |
thresh = cv2.bitwise_not(thresh)
|
28 |
|
29 |
# OCR
|
30 |
result = reader.readtext(thresh, detail=0)
|
31 |
+
print("🔍 OCR Text:", result)
|
32 |
+
combined_text = " ".join(result)
|
33 |
|
34 |
+
# Extract weight
|
35 |
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", combined_text)
|
36 |
if match:
|
37 |
weight = match.group(1)
|
|
|
40 |
return "No weight detected kg", 0.0
|
41 |
|
42 |
except Exception as e:
|
43 |
+
print("❌ OCR Error:", e)
|
44 |
return f"Error: {str(e)}", 0.0
|
|