-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCar_Detection.py
54 lines (49 loc) · 2.21 KB
/
Car_Detection.py
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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
class cd:
def car_img_de(self,img_path):
import numpy as np
import cv2
label_path = "coco.names"
config_path = "yolov3.cfg"
weights_path = "yolov3.weights"
yolo_shape = (416,416)
network = cv2.dnn.readNetFromDarknet(config_path,weights_path)
ln = network.getUnconnectedOutLayersNames()
label = open(label_path).read().split()
def car_detection(img):
img = cv2.resize(img,(800,800))
H,W = img.shape[:2]
pre_image = cv2.dnn.blobFromImage(img,1/255.0,yolo_shape,swapRB=True)
network.setInput(pre_image)
layers_out = network.forward(ln)
Box =[]
Confidance =[]
Label =[]
for out in layers_out:
for acc in out:
class_id = np.argmax(acc[5:])
confidance = acc[5:][class_id]
if float(confidance)>.85:
if label[class_id] in ["car","moterbike","bus","truck"]:
CenterX,CenterY,Width,Height = (acc[:4]*np.array([W,H,W,H])).astype("int")
X,Y = int(CenterX-Width/2),int(CenterY-Height/2)
Box.append([X,Y,int(Width),int(Height)])
Confidance.append(float(confidance))
Label.append(label[class_id])
best_out = cv2.dnn.NMSBoxes(Box,Confidance,.5,.4)
for i in range(len(Box)):
if i in best_out:
X,Y,W,H = Box[i]
cv2.rectangle(img,(X,Y),(X+W,Y+H),(0,255,0),2)
cv2.putText(img,Label[i],(X,Y-5),cv2.FONT_HERSHEY_COMPLEX,.6,(0,0,255),1)
return img
img = cv2.imread(img_path)
img = car_detection(img)
while True:
cv2.imshow("Image Car Detection",img)
if cv2.waitKey(1)==13:
break
cv2.destroyAllWindows()
return True