import cv2 import numpy as np

定义类别名称

classes = [] with open("yolov3.txt", "r") as f: classes = [line.strip() for line in f.readlines()]

网络参数

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")

输入图片尺寸

input_size = 416

def detect_objects(img): # 创建一个blob blob = cv2.dnn.blobFromImage(img, 1/255, (input_size, input_size), swapRB=True)

# 设置网络输入
net.setInput(blob)

# 获取输出层名称
output_layers_names = net.getUnconnectedOutLayersNames()

# 运行网络
layer_outputs = net.forward(output_layers_names)

# 初始化变量
boxes = []
confidences = []
class_ids = []

# 遍历所有输出层
for output in layer_outputs:
    # 遍历每个检测框
    for detection in output:
        # 获取置信度
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]

        # 过滤掉低置信度的检测结果
        if confidence > 0.5:
            # 获取检测框在原图上的位置
            center_x = int(detection[0] * img.shape[1])
            center_y = int(detection[1] * img.shape[0])
            width = int(detection[2] * img.shape[1])
            height = int(detection[3] * img.shape[0])

            # 计算左上角坐标
            left = int(center_x - width / 2)
            top = int(center_y - height / 2)

            # 添加检测结果
            boxes.append([left, top, width, height])
            confidences.append(float(confidence))
            class_ids.append(class_id)

# 进行非极大值抑制
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

# 绘制结果
for i in indices:
    i = i[0]
    left, top, width, height = boxes[i]
    label = f"{classes[class_ids[i]]}: {confidences[i]:.2f}"

    cv2.rectangle(img, (left, top), (left+width, top+height), (0, 255, 0), 2)
    cv2.putText(img, label, (left, top-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

return img

加载图片

img = cv2.imread("test.jpg")

检测物体

result_img = detect_objects(img)

显示结果

cv2.imshow("Object Detection", result_img) cv2.waitKey(0) cv2.destroyAllWindows()

编写cv2使用YOLOv3的程序加中文注释

原文地址: https://www.cveoy.top/t/topic/npI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录