Spaces:
No application file
No application file
Prateek954
commited on
Commit
•
84cc058
1
Parent(s):
cf45035
Update main.py
Browse files
main.py
CHANGED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from ultralytics import YOLO
|
2 |
+
import cv2
|
3 |
+
|
4 |
+
import util
|
5 |
+
from sort.sort import *
|
6 |
+
from util import get_car, read_license_plate, write_csv
|
7 |
+
|
8 |
+
|
9 |
+
results = {}
|
10 |
+
|
11 |
+
mot_tracker = Sort()
|
12 |
+
|
13 |
+
# load models
|
14 |
+
coco_model = YOLO('yolov8n.pt')
|
15 |
+
license_plate_detector = YOLO('./models/license_plate_detector.pt')
|
16 |
+
|
17 |
+
# load video
|
18 |
+
cap = cv2.VideoCapture('./sample.mp4')
|
19 |
+
|
20 |
+
vehicles = [2, 3, 5, 7]
|
21 |
+
|
22 |
+
# read frames
|
23 |
+
frame_nmr = -1
|
24 |
+
ret = True
|
25 |
+
while ret:
|
26 |
+
frame_nmr += 1
|
27 |
+
ret, frame = cap.read()
|
28 |
+
if ret:
|
29 |
+
results[frame_nmr] = {}
|
30 |
+
# detect vehicles
|
31 |
+
detections = coco_model(frame)[0]
|
32 |
+
detections_ = []
|
33 |
+
for detection in detections.boxes.data.tolist():
|
34 |
+
x1, y1, x2, y2, score, class_id = detection
|
35 |
+
if int(class_id) in vehicles:
|
36 |
+
detections_.append([x1, y1, x2, y2, score])
|
37 |
+
|
38 |
+
# track vehicles
|
39 |
+
track_ids = mot_tracker.update(np.asarray(detections_))
|
40 |
+
|
41 |
+
# detect license plates
|
42 |
+
license_plates = license_plate_detector(frame)[0]
|
43 |
+
for license_plate in license_plates.boxes.data.tolist():
|
44 |
+
x1, y1, x2, y2, score, class_id = license_plate
|
45 |
+
|
46 |
+
# assign license plate to car
|
47 |
+
xcar1, ycar1, xcar2, ycar2, car_id = get_car(license_plate, track_ids)
|
48 |
+
|
49 |
+
if car_id != -1:
|
50 |
+
|
51 |
+
# crop license plate
|
52 |
+
license_plate_crop = frame[int(y1):int(y2), int(x1): int(x2), :]
|
53 |
+
|
54 |
+
# process license plate
|
55 |
+
license_plate_crop_gray = cv2.cvtColor(license_plate_crop, cv2.COLOR_BGR2GRAY)
|
56 |
+
_, license_plate_crop_thresh = cv2.threshold(license_plate_crop_gray, 64, 255, cv2.THRESH_BINARY_INV)
|
57 |
+
|
58 |
+
# read license plate number
|
59 |
+
license_plate_text, license_plate_text_score = read_license_plate(license_plate_crop_thresh)
|
60 |
+
|
61 |
+
if license_plate_text is not None:
|
62 |
+
results[frame_nmr][car_id] = {'car': {'bbox': [xcar1, ycar1, xcar2, ycar2]},
|
63 |
+
'license_plate': {'bbox': [x1, y1, x2, y2],
|
64 |
+
'text': license_plate_text,
|
65 |
+
'bbox_score': score,
|
66 |
+
'text_score': license_plate_text_score}}
|
67 |
+
|
68 |
+
# write results
|
69 |
+
write_csv(results, './test.csv')
|