opencv--使用YOLOv3实现目标检测

opencv的安装

在终端输入

pip install opencv-python
pip install opencv-contrib-python

如果下载速度过慢,可以使用国内的镜像源:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-contrib-python

一个简单的目标检测程序

这里的程序参考自https://pysource.com/2019/06/27/yolo-object-detection-using-opencv-with-python/(需科学上网)
注:运行此代码还需要yolov3.weights,yolov3.cfg和coco.names文件

import cv2
import numpy as np

# 加载配置文件和权重(cfg文件包含模型的结构参数)
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
classes = []
#读取所有类别名称(coco.names中包含了所有可以识别出的类别名称)
with open("coco.names", "r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames() #获取网络结构中所有层结构的名称

#得到网络的输出层,getUnconnectedOutLayers()函数可以获得未连接的输出层的名字
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
#设置方框和文字的颜色
colors = np.random.uniform(0, 255, size=(len(classes), 3))

# 加载待检测的图片
img = cv2.imread("room_ser.jpg")
# 将原图片的x轴和y轴变为原来的0.4倍
img = cv2.resize(img, None, fx=0.4, fy=0.4)
# 获取图片的高度,宽度以及通道数
height, width, channels = img.shape

# 图像预处理,img是待预处理的图片,第二个参数0.00392是指将原始图像中R,G,B三个通道的数值缩放为原来的
# 0.00392倍,第三个参数是YOLOv3网络的输入大小,即一张像素为416*416的图片,这个预处理函数会将我们的图
# 片转换为这个大小,第四个参数(0,0,0)是要对三个通道减去的值,这里三个值都是0,也就是不进行操作,下一个
# 参数,由于OpenCV认为图像 通道顺序是B、G、R,而减均值时顺序是R、G、B,为了解决这个矛盾,
# 设置swapRB=True即可,最后一个参数是设置是否裁剪图像
blob = cv2.dnn.blobFromImage(img, 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)
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, 3)# 向图片上添加文字


cv2.imshow("Image", img)# 显示图片
cv2.waitKey(0)# 等待0毫秒
cv2.destroyAllWindows()# 删除所有窗口


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值