yolov3.weights包含已训练好的模型权重,yolov3.cfg包含模型结构,直接调用即可。
import torch as t
import numpy as np
import cv2
import sys
# print(cv2.__version__)
net = cv2.dnn.readNet("yolov3/yolov3.weights", "yolov3/yolov3.cfg")
classes = []
with open("yolov3/coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
height, width, channels = frame.shape
# Detecting objects
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# Show information
class_idx = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence >= 0.5:
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_idx.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
print(indexes)
font = cv2.FONT_HERSHEY_PLAIN
for i in range(len(boxes)):
for i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_idx[i]])
color = colors[i]
cv2.rectangle(frame, (x, y), (x+w, x+h), color, 2)
cv2.putText(frame, label, (x, y+30), font, 3, color,3)
cv2.imshow("image", frame)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()