Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +22 -21
ocr_engine.py
CHANGED
|
@@ -1,40 +1,41 @@
|
|
| 1 |
import cv2
|
| 2 |
import easyocr
|
| 3 |
-
import re
|
| 4 |
-
from dblur import Deblurrer
|
| 5 |
import numpy as np
|
| 6 |
-
|
| 7 |
|
| 8 |
-
# Initialize EasyOCR reader
|
| 9 |
reader = easyocr.Reader(['en'], gpu=False)
|
| 10 |
-
restormer = Deblurrer(model_name="restormer")
|
| 11 |
|
| 12 |
-
def
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
| 16 |
|
| 17 |
def extract_weight_from_image(pil_img):
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
|
| 25 |
-
cv2.THRESH_BINARY, 11, 3)
|
| 26 |
|
|
|
|
|
|
|
|
|
|
| 27 |
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
|
| 28 |
-
|
| 29 |
|
| 30 |
# OCR
|
| 31 |
-
results = reader.readtext(
|
| 32 |
-
|
| 33 |
filtered = [text for _, text, conf in results if len(text.strip()) <= 5 and conf > 0.4]
|
| 34 |
raw_text = " ".join(filtered)
|
| 35 |
-
matches = re.findall(r"\d+\.\d+|\d+", raw_text)
|
| 36 |
|
|
|
|
| 37 |
weight = matches[0] if matches else "0.0"
|
| 38 |
confidence = int(results[0][2] * 100) if results else 0
|
| 39 |
|
| 40 |
-
return weight, confidence, raw_text,
|
|
|
|
| 1 |
import cv2
|
| 2 |
import easyocr
|
|
|
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
+
import re
|
| 5 |
|
| 6 |
+
# Initialize EasyOCR reader
|
| 7 |
reader = easyocr.Reader(['en'], gpu=False)
|
|
|
|
| 8 |
|
| 9 |
+
def sharpen_image(img_cv):
|
| 10 |
+
kernel = np.array([[0, -1, 0],
|
| 11 |
+
[-1, 5,-1],
|
| 12 |
+
[0, -1, 0]])
|
| 13 |
+
return cv2.filter2D(img_cv, -1, kernel)
|
| 14 |
|
| 15 |
def extract_weight_from_image(pil_img):
|
| 16 |
+
# Convert PIL to OpenCV
|
| 17 |
+
img_cv = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
|
| 18 |
+
|
| 19 |
+
# Resize and sharpen
|
| 20 |
+
img_cv = cv2.resize(img_cv, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC)
|
| 21 |
+
img_cv = sharpen_image(img_cv)
|
| 22 |
|
| 23 |
+
# Convert to grayscale
|
| 24 |
+
img_gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
# Apply adaptive threshold and morphology
|
| 27 |
+
img_thresh = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
|
| 28 |
+
cv2.THRESH_BINARY, 11, 3)
|
| 29 |
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
|
| 30 |
+
img_clean = cv2.morphologyEx(img_thresh, cv2.MORPH_CLOSE, kernel)
|
| 31 |
|
| 32 |
# OCR
|
| 33 |
+
results = reader.readtext(img_clean)
|
|
|
|
| 34 |
filtered = [text for _, text, conf in results if len(text.strip()) <= 5 and conf > 0.4]
|
| 35 |
raw_text = " ".join(filtered)
|
|
|
|
| 36 |
|
| 37 |
+
matches = re.findall(r"\d+\.\d+|\d+", raw_text)
|
| 38 |
weight = matches[0] if matches else "0.0"
|
| 39 |
confidence = int(results[0][2] * 100) if results else 0
|
| 40 |
|
| 41 |
+
return weight, confidence, raw_text, img_cv # Return processed image
|