-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyolo_detect.py
83 lines (72 loc) · 2.69 KB
/
yolo_detect.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 18 19:50:56 2022
@author: Samad
"""
import cv2
import numpy as np
net = cv2.dnn.readNetFromDarknet("yolov3_custom.cfg","yolov3_custom_4000.weights")
classes = ['tired','not_tired']
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
while 1:
_, img = cap.read()
img = cv2.resize(img,(1280,720))
hight,width,_ = img.shape
blob = cv2.dnn.blobFromImage(img, 1/255,(416,416),(0,0,0),swapRB = True,crop= False)
net.setInput(blob)
output_layers_name = net.getUnconnectedOutLayersNames()
layerOutputs = net.forward(output_layers_name)
boxes =[]
confidences = []
class_ids = []
for output in layerOutputs:
for detection in output:
score = detection[5:]
class_id = np.argmax(score)
confidence = score[class_id]
if confidence > 0.7:
center_x = int(detection[0] * width)
center_y = int(detection[1] * hight)
w = int(detection[2] * width)
h = int(detection[3]* hight)
x = int(center_x - w/2)
y = int(center_y - h/2)
boxes.append([x,y,w,h])
confidences.append((float(confidence)))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes,confidences,.5,.4)
boxes =[]
confidences = []
class_ids = []
for output in layerOutputs:
for detection in output:
score = detection[5:]
class_id = np.argmax(score)
confidence = score[class_id]
if confidence > 0.5:
center_x = int(detection[0] * width)
center_y = int(detection[1] * hight)
w = int(detection[2] * width)
h = int(detection[3]* hight)
x = int(center_x - w/2)
y = int(center_y - h/2)
boxes.append([x,y,w,h])
confidences.append((float(confidence)))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes,confidences,.8,.4)
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0,255,size =(len(boxes),3))
if len(indexes)>0:
for i in indexes.flatten():
x,y,w,h = boxes[i]
label = str(classes[class_ids[i]])
print(label)
confidence = str(round(confidences[i],2))
color = colors[i]
cv2.rectangle(img,(x,y),(x+w,y+h),color,2)
cv2.putText(img,label + " " + confidence, (x,y+400),font,2,color,2)
cv2.imshow('img',img)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()