Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +13 -5
ocr_engine.py
CHANGED
|
@@ -9,15 +9,23 @@ def extract_weight_from_image(pil_img):
|
|
| 9 |
try:
|
| 10 |
img = np.array(pil_img)
|
| 11 |
|
|
|
|
| 12 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
| 13 |
-
resized = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
|
| 14 |
-
blurred = cv2.GaussianBlur(resized, (5, 5), 0)
|
| 15 |
-
_, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
print("OCR Text:", text)
|
| 20 |
|
|
|
|
| 21 |
match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", text)
|
| 22 |
if match:
|
| 23 |
return match.group(), 95.0
|
|
|
|
| 9 |
try:
|
| 10 |
img = np.array(pil_img)
|
| 11 |
|
| 12 |
+
# Step 1: Convert to grayscale
|
| 13 |
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Step 2: Apply adaptive threshold to handle lighting
|
| 16 |
+
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
| 17 |
+
cv2.THRESH_BINARY_INV, 11, 2)
|
| 18 |
+
|
| 19 |
+
# Step 3: Dilate to make digits thicker
|
| 20 |
+
kernel = np.ones((2, 2), np.uint8)
|
| 21 |
+
dilated = cv2.dilate(thresh, kernel, iterations=1)
|
| 22 |
+
|
| 23 |
+
# Step 4: OCR on the preprocessed image
|
| 24 |
+
result = reader.readtext(dilated, detail=0)
|
| 25 |
+
text = " ".join(result).strip()
|
| 26 |
print("OCR Text:", text)
|
| 27 |
|
| 28 |
+
# Step 5: Match numeric values like 52.30 or 003.25
|
| 29 |
match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", text)
|
| 30 |
if match:
|
| 31 |
return match.group(), 95.0
|