darknet yolo4:
"""
Created on Sat Mar 13 10:24:50 2021
@author: S
"""
import numpy as np
import cv2
import os
import time
def video_demo():
weightsPath = "./backup/yolo-obj_fre_final.weights"
configPath = "./backup/yolo-obj_fre.cfg"
labelsPath = "./backup/fre.names"
LABELS = open(labelsPath).read().strip().split("\n")
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8")
boxes = []
confidences = []
classIDs = []
central_points = []
counts = 0
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
capture = cv2.VideoCapture("./E20.mp4")
while (True):
start_drawing = time.time()
fps = int(capture.get(cv2.CAP_PROP_FPS))
ref, image = capture.read()
(H, W) = image.shape[:2]
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
layerOutputs = net.forward(ln)
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
if confidence > 0.5:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
idxs = cv2.dnn.NMSBoxes(boxes, confidences, 0.3, 0.3)
if len(idxs) > 0:
for i in idxs.flatten():
counts=counts +1
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
(x_center,y_center) = ( int(x+w/2), int(y + h/2))
central_points.append([x_center,y_center])
color = [int(c) for c in COLORS[classIDs[i]]]
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.circle(image,(x_center, y_center),10,(0,0,255),2)
text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
counts=len(idxs)
end_drawing = time.time()
fps_label = "FPS: %.2d" % fps
cv2.putText(image,fps_label , (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 2)
cv2.imshow("Image", image)
c = cv2.waitKey(1) & 0xff
if c == 27:
capture.release()
break
boxes = []
confidences = []
classIDs =[]
video_demo()