Rammohan0504 commited on
Commit
72d3be0
·
verified ·
1 Parent(s): ae63d6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -33
app.py CHANGED
@@ -1,44 +1,65 @@
1
  import gradio as gr
2
- from datetime import datetime
3
- from PIL import ImageFilter, ImageEnhance
4
- import pytz
5
- from ocr_engine import extract_weight_from_image
6
- from PIL import Image
7
 
8
- def enhance_image(pil_img):
9
- pil_img = pil_img.filter(ImageFilter.SHARPEN)
10
- enhancer = ImageEnhance.Contrast(pil_img)
11
- return enhancer.enhance(2.0)
12
 
13
- def process_image(img):
14
- if img is None:
15
- return "No image uploaded", None, None, "No OCR output"
16
 
17
- enhanced = enhance_image(img)
18
- weight, confidence, raw_text, processed_img_cv = extract_weight_from_image(enhanced)
19
- processed_img = Image.fromarray(processed_img_cv)
 
 
20
 
21
- ist_time = datetime.now(pytz.timezone("Asia/Kolkata")).strftime("%d-%m-%Y %I:%M:%S %p")
22
- return f"{weight} kg (Confidence: {confidence}%)", ist_time, processed_img, raw_text
 
 
23
 
24
- with gr.Blocks(title="⚖️ Auto Weight Logger") as demo:
25
- gr.Markdown("## ⚖️ Auto Weight Logger")
26
- gr.Markdown("📷 **Upload or capture an image of a digital weight scale.** This app sharpens images and extracts weights using EasyOCR.")
27
 
28
- with gr.Row():
29
- image_input = gr.Image(type="pil", label="Upload / Capture Image")
30
- output_weight = gr.Textbox(label="⚖️ Detected Weight (in kg)")
31
 
32
- with gr.Row():
33
- timestamp = gr.Textbox(label="🕒 Captured At (IST)")
34
- snapshot = gr.Image(label="🧪 Processed Snapshot")
 
 
 
 
35
 
36
- with gr.Row():
37
- debug_output = gr.Textbox(label="🪵 Raw OCR Output")
 
 
38
 
39
- submit = gr.Button("🔍 Detect Weight")
40
- submit.click(process_image,
41
- inputs=image_input,
42
- outputs=[output_weight, timestamp, snapshot, debug_output])
43
 
44
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import easyocr
3
+ import cv2
4
+ import numpy as np
5
+ import re
 
6
 
7
+ # Initialize OCR reader
8
+ reader = easyocr.Reader(['en'], gpu=False)
 
 
9
 
10
+ # Preprocessing function to enhance OCR accuracy
11
+ def preprocess(img):
12
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
13
 
14
+ # Sharpening kernel (helps deblur weak edges)
15
+ sharpen_kernel = np.array([[-1, -1, -1],
16
+ [-1, 9, -1],
17
+ [-1, -1, -1]])
18
+ sharp = cv2.filter2D(gray, -1, sharpen_kernel)
19
 
20
+ # Adaptive thresholding for binarization
21
+ thresh = cv2.adaptiveThreshold(sharp, 255,
22
+ cv2.ADAPTIVE_THRESH_MEAN_C,
23
+ cv2.THRESH_BINARY_INV, 11, 4)
24
 
25
+ # Dilation to strengthen character boundaries
26
+ kernel = np.ones((2, 2), np.uint8)
27
+ dilated = cv2.dilate(thresh, kernel, iterations=1)
28
 
29
+ return dilated
 
 
30
 
31
+ # Extract weight using regex
32
+ def extract_weight(results):
33
+ for text, _, _ in results:
34
+ match = re.search(r'\b\d{2,4}(\.\d{1,2})?\b', text)
35
+ if match:
36
+ return match.group()
37
+ return None
38
 
39
+ # Complete OCR pipeline
40
+ def get_weight(img):
41
+ # Convert RGB to BGR
42
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
43
 
44
+ # Resize small or distant images (heuristic)
45
+ if img.shape[0] < 500:
46
+ img = cv2.resize(img, None, fx=2.0, fy=2.0,
47
+ interpolation=cv2.INTER_CUBIC)
48
 
49
+ preprocessed = preprocess(img)
50
+ results = reader.readtext(preprocessed)
51
+ weight = extract_weight(results)
52
+
53
+ return f"Detected Weight: {weight if weight else 'Not found'}"
54
+
55
+ # Gradio UI
56
+ demo = gr.Interface(
57
+ fn=get_weight,
58
+ inputs=gr.Image(type="numpy", label="Upload Image"),
59
+ outputs=gr.Textbox(label="Detected Weight"),
60
+ title="Auto Weight Logger (Blur & Distance Aware)",
61
+ description="Extracts weight from digital display images using OCR & preprocessing."
62
+ )
63
+
64
+ if __name__ == "__main__":
65
+ demo.launch()