Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +6 -10
ocr_engine.py
CHANGED
|
@@ -9,28 +9,24 @@ def extract_weight_from_image(pil_img):
|
|
| 9 |
try:
|
| 10 |
img = np.array(pil_img)
|
| 11 |
|
| 12 |
-
#
|
| 13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
| 14 |
-
|
| 15 |
-
# Resize and enhance contrast
|
| 16 |
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
|
| 17 |
gray = cv2.equalizeHist(gray)
|
| 18 |
-
|
| 19 |
-
# Reduce noise and invert for LCD displays
|
| 20 |
gray = cv2.GaussianBlur(gray, (3, 3), 0)
|
| 21 |
inverted = cv2.bitwise_not(gray)
|
| 22 |
|
| 23 |
-
# OCR
|
| 24 |
result = reader.readtext(inverted, detail=0)
|
| 25 |
combined_text = " ".join(result)
|
| 26 |
-
print("OCR
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
match = re.search(r"(\d{1,
|
| 30 |
if match:
|
| 31 |
return f"{match.group(1)} kg", 95.0
|
| 32 |
|
| 33 |
-
#
|
| 34 |
fallback = re.search(r"\d{1,4}(?:\.\d{1,2})?", combined_text)
|
| 35 |
if fallback:
|
| 36 |
return f"{fallback.group(0)} kg", 75.0
|
|
|
|
| 9 |
try:
|
| 10 |
img = np.array(pil_img)
|
| 11 |
|
| 12 |
+
# Preprocessing for OCR
|
| 13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
|
|
|
|
|
|
| 14 |
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
|
| 15 |
gray = cv2.equalizeHist(gray)
|
|
|
|
|
|
|
| 16 |
gray = cv2.GaussianBlur(gray, (3, 3), 0)
|
| 17 |
inverted = cv2.bitwise_not(gray)
|
| 18 |
|
| 19 |
+
# OCR read
|
| 20 |
result = reader.readtext(inverted, detail=0)
|
| 21 |
combined_text = " ".join(result)
|
| 22 |
+
print("OCR Raw Text:", combined_text)
|
| 23 |
|
| 24 |
+
# First try matching with "kg"
|
| 25 |
+
match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)\s*(kg|KG|Kg)", combined_text)
|
| 26 |
if match:
|
| 27 |
return f"{match.group(1)} kg", 95.0
|
| 28 |
|
| 29 |
+
# Then try fallback match: only numbers
|
| 30 |
fallback = re.search(r"\d{1,4}(?:\.\d{1,2})?", combined_text)
|
| 31 |
if fallback:
|
| 32 |
return f"{fallback.group(0)} kg", 75.0
|