Sarvamangalak commited on
Commit
3d3299c
·
verified ·
1 Parent(s): 7d3d8d2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import numpy as np
4
+ import cv2
5
+ from PIL import Image, ImageDraw
6
+ from transformers import YolosImageProcessor, YolosForObjectDetection
7
+
8
+ # Load model
9
+ processor = YolosImageProcessor.from_pretrained(
10
+ "nickmuchi/yolos-small-finetuned-license-plate-detection"
11
+ )
12
+ model = YolosForObjectDetection.from_pretrained(
13
+ "nickmuchi/yolos-small-finetuned-license-plate-detection"
14
+ )
15
+ model.eval()
16
+
17
+ # -------- Plate Color Classifier -------- #
18
+ def classify_plate_color(plate_img):
19
+ img = np.array(plate_img)
20
+ hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
21
+
22
+ green = cv2.inRange(hsv, (35, 40, 40), (85, 255, 255))
23
+ yellow = cv2.inRange(hsv, (15, 50, 50), (35, 255, 255))
24
+ white = cv2.inRange(hsv, (0, 0, 200), (180, 30, 255))
25
+
26
+ g = np.sum(green)
27
+ y = np.sum(yellow)
28
+ w = np.sum(white)
29
+
30
+ if g > y and g > w:
31
+ return "Electric Vehicle (Green Plate)"
32
+ elif y > g and y > w:
33
+ return "Commercial Vehicle (Yellow Plate)"
34
+ else:
35
+ return "Private Vehicle (White Plate)"
36
+
37
+ # -------- Main Pipeline -------- #
38
+ def process_image(img):
39
+ image = Image.fromarray(img)
40
+
41
+ inputs = processor(images=image, return_tensors="pt")
42
+ with torch.no_grad():
43
+ outputs = model(**inputs)
44
+
45
+ target_sizes = torch.tensor([[image.size[1], image.size[0]]])
46
+ results = processor.post_process_object_detection(
47
+ outputs, threshold=0.3, target_sizes=target_sizes
48
+ )[0]
49
+
50
+ draw = ImageDraw.Draw(image)
51
+
52
+ if len(results["boxes"]) == 0:
53
+ return image, "No license plate detected"
54
+
55
+ box = results["boxes"][0].tolist()
56
+ x1, y1, x2, y2 = map(int, box)
57
+
58
+ plate = image.crop((x1, y1, x2, y2))
59
+ vehicle_type = classify_plate_color(plate)
60
+
61
+ draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
62
+ draw.text((x1, y1 - 10), vehicle_type, fill="red")
63
+
64
+ return image, vehicle_type
65
+
66
+ # -------- Gradio UI -------- #
67
+ with gr.Blocks() as demo:
68
+ gr.Markdown("# 🚗 Vehicle Classification using License Plate")
69
+ gr.Markdown("Upload or take a photo of a car. The AI detects the license plate and classifies the vehicle.")
70
+
71
+ with gr.Row():
72
+ input_img = gr.Image(type="numpy", sources=["upload", "webcam"])
73
+ output_img = gr.Image()
74
+
75
+ result = gr.Textbox(label="Vehicle Type")
76
+
77
+ btn = gr.Button("Detect Vehicle")
78
+ btn.click(process_image, input_img, [output_img, result])
79
+
80
+ demo.launch()