Spaces:
Runtime error
Runtime error
Update ocr_engine.py
Browse files- ocr_engine.py +14 -28
ocr_engine.py
CHANGED
@@ -1,43 +1,29 @@
|
|
1 |
-
import
|
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 |
-
# Convert PIL to
|
11 |
img = np.array(pil_img)
|
12 |
|
13 |
-
#
|
14 |
-
img = cv2.resize(img, None, fx=
|
15 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
20 |
-
binary = cv2.bitwise_not(binary)
|
21 |
-
|
22 |
-
# Step 2: OCR with bounding boxes
|
23 |
-
results = reader.readtext(binary, detail=1)
|
24 |
-
|
25 |
-
# Step 3: Filter for weight-like values
|
26 |
-
weight_candidates = []
|
27 |
-
for bbox, text, conf in results:
|
28 |
-
clean = text.lower().replace("kg", "").replace("kgs", "").strip()
|
29 |
-
clean = clean.replace("o", "0").replace("O", "0") # common OCR mistake
|
30 |
-
|
31 |
-
# Match like 2 digits or 3 digits or decimal numbers
|
32 |
-
if re.fullmatch(r"\d{2,4}(\.\d{1,2})?", clean):
|
33 |
-
weight_candidates.append((clean, conf))
|
34 |
|
35 |
-
|
36 |
-
|
|
|
37 |
|
38 |
-
#
|
39 |
-
|
40 |
-
|
|
|
|
|
41 |
|
42 |
except Exception as e:
|
43 |
return f"Error: {str(e)}", 0.0
|
|
|
1 |
+
import pytesseract
|
2 |
import numpy as np
|
3 |
import cv2
|
4 |
import re
|
5 |
|
|
|
|
|
6 |
def extract_weight_from_image(pil_img):
|
7 |
try:
|
8 |
+
# Convert PIL to OpenCV format
|
9 |
img = np.array(pil_img)
|
10 |
|
11 |
+
# Resize and convert to grayscale
|
12 |
+
img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
|
13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
14 |
|
15 |
+
# Thresholding for clarity
|
16 |
+
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
+
# Run OCR
|
19 |
+
text = pytesseract.image_to_string(thresh)
|
20 |
+
print("OCR TEXT:", text)
|
21 |
|
22 |
+
# Search for weight pattern
|
23 |
+
match = re.search(r"\b\d{2,4}(\.\d{1,2})?\b", text)
|
24 |
+
if match:
|
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
|