Spaces:
Running
Running
File size: 1,577 Bytes
a481416 12d76b5 523b1ec 12d76b5 523b1ec a481416 523b1ec eff70bd 523b1ec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import gradio as gr
import numpy as np
from PIL import Image
import cv2
import re
from paddleocr import PaddleOCR
from datetime import datetime
# Initialize OCR model once
ocr = PaddleOCR(use_angle_cls=True, lang='en')
# Preprocessing: Convert to grayscale and threshold
def preprocess_image(image):
img = np.array(image.convert("RGB"))
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
return Image.fromarray(thresh)
# OCR detection + regex filtering
def extract_weight_text(image):
results = ocr.ocr(np.array(image), cls=True)
for line in results[0]:
text = line[1][0]
match = re.search(r"\d+\.\d+", text)
if match:
return match.group()
return None
# Main function
def detect_weight(image):
if image is None:
return "No image uploaded.", "", None
pre_img = preprocess_image(image)
weight = extract_weight_text(pre_img)
if weight:
return f"Detected Weight: {weight} kg", datetime.now().strftime("Captured At: %Y-%m-%d %H:%M:%S"), pre_img
else:
return "Weight Not Detected", "", pre_img
# Gradio UI
interface = gr.Interface(
fn=detect_weight,
inputs=gr.Image(type="pil", label="Upload or Capture Image"),
outputs=[
gr.Textbox(label="Weight"),
gr.Textbox(label="Timestamp"),
gr.Image(label="Preprocessed Image")
],
title="Auto Weight Logger",
description="Upload or click image of digital scale. It will detect and show the weight (kg).",
)
interface.launch()
|