HiralShah62 commited on
Commit
056ff88
Β·
verified Β·
1 Parent(s): 2251026

Update detect.py

Browse files
Files changed (1) hide show
  1. detect.py +129 -123
detect.py CHANGED
@@ -1,124 +1,130 @@
1
- import streamlit as st
2
- from ultralytics import YOLO
3
- import cv2
4
- import easyocr
5
- import numpy as np
6
- import pandas as pd
7
- from PIL import Image
8
- import tempfile
9
-
10
- @st.cache_resource
11
- def load_model():
12
- model = YOLO('yolo11n-custom.pt')
13
- model.fuse()
14
- return model
15
-
16
- model = load_model()
17
-
18
- reader = easyocr.Reader(['en'])
19
-
20
- def detect_license_plate(image):
21
- results = model.predict(image, conf=0.15, iou=0.3, classes=[0])
22
- plate_texts = []
23
- img_array = np.array(image)
24
- # img = cv2.imread(image_path)
25
- img = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
26
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
27
-
28
- img_height, img_width, _ = img.shape
29
-
30
- for result in results:
31
- for bbox in result.boxes.xyxy:
32
- x1, y1, x2, y2 = map(int, bbox.tolist())
33
- plate = img[int(y1):int(y2), int(x1):int(x2)]
34
- scale=2
35
- height, width = plate.shape[:2]
36
- plate = cv2.resize(plate, (width * scale, height * scale), interpolation=cv2.INTER_CUBIC)
37
-
38
- text = reader.readtext(plate, detail=0, allowlist="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-")
39
- text = " ".join(text).upper()
40
-
41
- text_scale = max(1, width / 250)
42
- thickness = max(2, width // 200)
43
- cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), thickness)
44
- (text_width, text_height), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, text_scale, thickness)
45
- text_x = x1 + (width - text_width) // 2 # Centered horizontally
46
- text_y = y1 - 10 if y1 > 50 else y2 + text_height + 20 # Above unless too high
47
- text_box_y1 = text_y - text_height - 5
48
- text_box_y2 = text_y + 5
49
- cv2.rectangle(img, (text_x - 8, text_box_y1 - 3), (text_x + text_width + 8, text_box_y2 + 3), (0, 0, 0), -1)
50
- cv2.rectangle(img, (text_x - 5, text_box_y1), (text_x + text_width + 5, text_box_y2), (255, 255, 255), -1)
51
- cv2.putText(img, text, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, text_scale, (0, 0, 0), thickness)
52
-
53
- plate_texts.append(text)
54
- image = img
55
- return image, plate_texts
56
-
57
- st.title("🚘 Real-Time License Plate Detection", anchor=False)
58
-
59
- st.write("For better license plate detection, ensure you use high-quality images. If detection is unclear, try enhancing the image first. Use the Refine Image for Detection tool.")
60
-
61
- st.write("Upload an image, upload a video, or use your webcam for real-time license plate detection.")
62
-
63
- option = st.radio("Choose Input Source:", ("Upload Image", "Upload Video", "Webcam"), horizontal=True )
64
-
65
-
66
- if option == "Upload Image":
67
- uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
68
- if uploaded_file:
69
- img = Image.open(uploaded_file)
70
- st.write("Processing...")
71
-
72
- processed_img, plate_texts = detect_license_plate(img)
73
-
74
- st.image(processed_img, caption="Detected Plates Image", use_container_width=True)
75
- st.write("**Detected License Plates:**")
76
- if plate_texts:
77
- plates = pd.DataFrame({"License Plate": plate_texts})
78
- plates.index = plates.index + 1
79
- st.table(plates)
80
- else:
81
- st.write("No license plates detected.")
82
-
83
- elif option == "Upload Video":
84
- uploaded_video = st.file_uploader("Choose a video...", type=["mp4", "avi", "mov"])
85
- if uploaded_video is not None:
86
- st.write("Processing video...")
87
- tfile = tempfile.NamedTemporaryFile(delete=False)
88
- tfile.write(uploaded_video.read())
89
- cap = cv2.VideoCapture(tfile.name)
90
- frame_placeholder = st.empty()
91
-
92
- while cap.isOpened():
93
- ret, frame = cap.read()
94
- if not ret:
95
- break
96
- processed_frame, plate_texts = detect_license_plate(frame)
97
-
98
- frame_placeholder.image(processed_frame, caption="Detected Plates Video", use_container_width=True)
99
- cap.release()
100
-
101
- elif option == "Webcam":
102
- if "running" not in st.session_state:
103
- st.session_state.running = True
104
- if st.button("Stop"):
105
- st.session_state.running = False
106
-
107
- st.write("Starting Webcam... Press **Stop** to end.")
108
- cap = cv2.VideoCapture(0)
109
- frame_placeholder = st.empty()
110
-
111
- while cap.isOpened():
112
- ret, frame = cap.read()
113
- if not ret:
114
- st.warning("Failed to capture webcam feed.")
115
- break
116
-
117
- processed_frame, plate_texts = detect_license_plate(frame)
118
-
119
- frame_placeholder.image(processed_frame, channels="BGR", caption="Webcam Feed", use_container_width=True)
120
-
121
- if not st.session_state.running:
122
- break
123
-
 
 
 
 
 
 
124
  cap.release()
 
1
+ import streamlit as st
2
+ from ultralytics import YOLO
3
+ import cv2
4
+ import easyocr
5
+ import numpy as np
6
+ import pandas as pd
7
+ from PIL import Image
8
+ import tempfile
9
+
10
+ @st.cache_resource
11
+ def load_model():
12
+ model = YOLO('yolo11n-custom.pt')
13
+ model.fuse()
14
+ return model
15
+
16
+ model = load_model()
17
+
18
+ reader = easyocr.Reader(['en'])
19
+
20
+ def detect_license_plate(image):
21
+ results = model.predict(image, conf=0.15, iou=0.3, classes=[0])
22
+ plate_texts = []
23
+ img_array = np.array(image)
24
+ # img = cv2.imread(image_path)
25
+ img = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
26
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
27
+
28
+ img_height, img_width, _ = img.shape
29
+
30
+ for result in results:
31
+ for bbox in result.boxes.xyxy:
32
+ x1, y1, x2, y2 = map(int, bbox.tolist())
33
+ plate = img[int(y1):int(y2), int(x1):int(x2)]
34
+ scale=2
35
+ height, width = plate.shape[:2]
36
+ plate = cv2.resize(plate, (width * scale, height * scale), interpolation=cv2.INTER_CUBIC)
37
+ lab = cv2.cvtColor(plate, cv2.COLOR_RGB2LAB)
38
+ l, a, b = cv2.split(lab)
39
+ clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
40
+ l = clahe.apply(l)
41
+ plate = cv2.merge((l, a, b))
42
+ plate = cv2.cvtColor(plate, cv2.COLOR_LAB2RGB)
43
+
44
+ text = reader.readtext(plate, detail=0, allowlist="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-")
45
+ text = " ".join(text).upper()
46
+
47
+ text_scale = max(1, width / 250)
48
+ thickness = max(2, width // 200)
49
+ cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), thickness)
50
+ (text_width, text_height), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, text_scale, thickness)
51
+ text_x = x1 + (width - text_width) // 2 # Centered horizontally
52
+ text_y = y1 - 10 if y1 > 50 else y2 + text_height + 20 # Above unless too high
53
+ text_box_y1 = text_y - text_height - 5
54
+ text_box_y2 = text_y + 5
55
+ cv2.rectangle(img, (text_x - 8, text_box_y1 - 3), (text_x + text_width + 8, text_box_y2 + 3), (0, 0, 0), -1)
56
+ cv2.rectangle(img, (text_x - 5, text_box_y1), (text_x + text_width + 5, text_box_y2), (255, 255, 255), -1)
57
+ cv2.putText(img, text, (text_x, text_y), cv2.FONT_HERSHEY_SIMPLEX, text_scale, (0, 0, 0), thickness)
58
+
59
+ plate_texts.append(text)
60
+ image = img
61
+ return image, plate_texts
62
+
63
+ st.title("🚘 Real-Time License Plate Detection", anchor=False)
64
+
65
+ st.write("For better license plate detection, ensure you use high-quality images. If detection is unclear, try enhancing the image first. Use the Refine Image for Detection tool.")
66
+
67
+ st.write("Upload an image, upload a video, or use your webcam for real-time license plate detection.")
68
+
69
+ option = st.radio("Choose Input Source:", ("Upload Image", "Upload Video", "Webcam"), horizontal=True )
70
+
71
+
72
+ if option == "Upload Image":
73
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
74
+ if uploaded_file:
75
+ img = Image.open(uploaded_file)
76
+ st.write("Processing...")
77
+
78
+ processed_img, plate_texts = detect_license_plate(img)
79
+
80
+ st.image(processed_img, caption="Detected Plates Image", use_container_width=True)
81
+ st.write("**Detected License Plates:**")
82
+ if plate_texts:
83
+ plates = pd.DataFrame({"License Plate": plate_texts})
84
+ plates.index = plates.index + 1
85
+ st.table(plates)
86
+ else:
87
+ st.write("No license plates detected.")
88
+
89
+ elif option == "Upload Video":
90
+ uploaded_video = st.file_uploader("Choose a video...", type=["mp4", "avi", "mov"])
91
+ if uploaded_video is not None:
92
+ st.write("Processing video...")
93
+ tfile = tempfile.NamedTemporaryFile(delete=False)
94
+ tfile.write(uploaded_video.read())
95
+ cap = cv2.VideoCapture(tfile.name)
96
+ frame_placeholder = st.empty()
97
+
98
+ while cap.isOpened():
99
+ ret, frame = cap.read()
100
+ if not ret:
101
+ break
102
+ processed_frame, plate_texts = detect_license_plate(frame)
103
+
104
+ frame_placeholder.image(processed_frame, caption="Detected Plates Video", use_container_width=True)
105
+ cap.release()
106
+
107
+ elif option == "Webcam":
108
+ if "running" not in st.session_state:
109
+ st.session_state.running = True
110
+ if st.button("Stop"):
111
+ st.session_state.running = False
112
+
113
+ st.write("Starting Webcam... Press **Stop** to end.")
114
+ cap = cv2.VideoCapture(0)
115
+ frame_placeholder = st.empty()
116
+
117
+ while cap.isOpened():
118
+ ret, frame = cap.read()
119
+ if not ret:
120
+ st.warning("Failed to capture webcam feed.")
121
+ break
122
+
123
+ processed_frame, plate_texts = detect_license_plate(frame)
124
+
125
+ frame_placeholder.image(processed_frame, channels="BGR", caption="Webcam Feed", use_container_width=True)
126
+
127
+ if not st.session_state.running:
128
+ break
129
+
130
  cap.release()