Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch
|
| 4 |
+
import pytesseract
|
| 5 |
+
import easyocr
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from yolov5 import YOLOv5
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
# Load YOLOv5 model (pre-trained)
|
| 11 |
+
model = YOLOv5('yolov5s.pt', device='cpu')
|
| 12 |
+
|
| 13 |
+
# Load EasyOCR
|
| 14 |
+
ocr_reader = easyocr.Reader(['en'])
|
| 15 |
+
|
| 16 |
+
# Image Preprocessing (Sharpen & Deblur)
|
| 17 |
+
def enhance_image(image):
|
| 18 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
| 19 |
+
kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
|
| 20 |
+
sharpened = cv2.filter2D(image, -1, kernel)
|
| 21 |
+
return sharpened
|
| 22 |
+
|
| 23 |
+
# Detect Digits Using YOLOv5
|
| 24 |
+
def detect_digits(image):
|
| 25 |
+
results = model(image)
|
| 26 |
+
digits = [det.xyxy.tolist()[0] for det in results.pred[0] if det.conf > 0.5]
|
| 27 |
+
return digits
|
| 28 |
+
|
| 29 |
+
# Extract Text Using OCR
|
| 30 |
+
def extract_text(image):
|
| 31 |
+
text = pytesseract.image_to_string(image, config='--psm 6')
|
| 32 |
+
return text
|
| 33 |
+
|
| 34 |
+
# Extract Weight Using Regex
|
| 35 |
+
def extract_weight(text):
|
| 36 |
+
matches = re.findall(r'\d+\.\d+', text) # Extract decimal numbers
|
| 37 |
+
return matches[0] if matches else "Weight not detected"
|
| 38 |
+
|
| 39 |
+
# Full Processing Pipeline
|
| 40 |
+
def process_image(image):
|
| 41 |
+
enhanced = enhance_image(image)
|
| 42 |
+
digits = detect_digits(image)
|
| 43 |
+
text = extract_text(enhanced)
|
| 44 |
+
weight = extract_weight(text)
|
| 45 |
+
return weight or "No weight detected"
|
| 46 |
+
|
| 47 |
+
# Gradio Interface
|
| 48 |
+
iface = gr.Interface(fn=process_image, inputs="image", outputs="text")
|
| 49 |
+
iface.launch()
|