python实现 yolov3 目标检测算法 代码实战

目标检测是计算机视觉中的重要任务,常用的方法有基于深度学习的方法(如YOLO、Faster R-CNN、SSD等)以及基于传统图像处理和机器学习的方法(如Haar级联检测器、HOG特征+SVM等)。以下是一个使用现成的深度学习模型(YOLOv3)进行目标检测的示例。

首先,确保安装了必要的库。你需要安装 opencv-pythonnumpy

pip install opencv-python numpy

然后,以下是一个使用 OpenCV 和 YOLOv3 进行目标检测的示例:

import cv2
import numpy as np

# 加载 YOLOv3 配置文件和预训练权重
net = cv2.dnn.readNet("yolov3.weights", "yolov3.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()]

# 加载图像进行目标检测
image = cv2.imread("image.jpg")  # 替换为你自己的图像路径
height, width, channels = image.shape

# 预处理图像
blob = cv2.dnn.blobFromImage(image, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)

# 处理检测结果
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.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_ids.append(class_id)

# 应用非最大抑制筛选重叠的边界框
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

# 绘制检测结果
font = cv2.FONT_HERSHEY_PLAIN
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]])
        color = colors[class_ids[i]]
        cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
        cv2.putText(image, label, (x, y + 30), font, 3, color, 3)

# 显示检测结果图像
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

这段代码使用了YOLOv3模型来进行目标检测。请注意,你需要将 yolov3.weightsyolov3.cfgcoco.names 替换为你自己的权重文件、配置文件和类别名称文件。这是一个简单的示例,你可以根据需要调整参数和阈值以及尝试其他预训练模型来获得更好的目标检测结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值