# Showing informations on the screen class_ids = [] 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.3: # Object detected print(class_id) center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height)
# Rectangle coordinates 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, 0.5, 0.4) print(indexes) font = cv2.FONT_HERSHEY_PLAIN for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) color = colors[class_ids[i]] cv2.rectangle(img, (x, y), (x + w, y + h), color, 2) cv2.putText(img, label, (x, y + 30), font, 3, color, 2)
cv2.imshow("Image", img) key = cv2.waitKey(0)
cv2.destroyAllWindows()
检测实例
最后,你可以看到我们的检测成功了。现在我们的系统可以检测到坦克。
5. 视频中的自定义对象检测
import cv2 import numpy as np import time
# Load Yolo net = cv2.dnn.readNet("yolov3_training_last.weights", "yolov3_testing.cfg") classes = [] with open("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))
# Loading image cap = cv2.VideoCapture("tests/test.mp4")
for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = confidences[i] color = colors[class_ids[i]] cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y + 30), font, 3, color, 3)
# Load Yolo net = cv2.dnn.readNet("yolov3_training_last.weights", "yolov3_testing.cfg") classes = [] with open("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))
for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] label = str(classes[class_ids[i]]) confidence = confidences[i] color = colors[class_ids[i]] cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2) cv2.putText(frame, label + " " + str(round(confidence, 2