谈起深度学习进行目标检测,我们能想到的一个分支就是端到端的YOLO系列。
我们之前接触过YOLO,也学习过YOLO,
文章如下:
https://blog.csdn.net/qq_29367075/article/details/109269472
https://blog.csdn.net/qq_29367075/article/details/109269477
https://blog.csdn.net/qq_29367075/article/details/109269483

因此呢,我们这里只是大概复习下YOLO的一些内容即可。

假如在一个anchor是1 的网络中,训练模型是有N个类别。
那么YOLO的每一个结果输出都是包含了(cx, cy, w, h, confindence, p1, p2, p3,……,pN),分别表示目标中心点的坐标和boundingbox的长宽,以及是否含有object,以及N个类别的softmax值。需要注意的是其中目标中心点坐标和boundingbox的长宽都是和长度、宽度进行了归一化的,就是占长和宽的比例。

我们先来看看今天涉及到的一些知识
1:YOLO-V3的网络结构

可以看出来,它有三个输出层,结果很多,定位也很详细。
参考自:https://zhuanlan.zhihu.com/p/40332004

2:COCO数据集 MS COCO的全称是Microsoft Common Objects in Context,起源于微软于2014年出资标注的Microsoft COCO数据集,与ImageNet竞赛一样,被视为是计算机视觉领域最受关注和最权威的比赛之一。 提供的类别有80 类,有超过33 万张图片,其中20 万张有标注,整个数据集中个体的数目超过150 万个。80个类别部分如下:

学习自:https://blog.csdn.net/qq_41185868/article/details/82939959

3:我们今天使用在coco数据集上训练好的yolov3模型,专门用于多物体的识别和定位。
下载地址:https://pjreddie.com/darknet/yolo/,今天我们不现场训练,而是使用现成的训练好的网络。

我们下载cfg文件(网络的架构)和weights文件(所有参数的权重)
我们可以看到yolov3-type,type越大,模型越大,输出结果越多,识别结果越精细,但是速度降低,FPS就越低了。相反type越小,模型越简单,输出结果越少, 识别结果越粗糙一点,但是速度提升了,FPS越高了。

点击后可以下载到本地。后续程序中要使用的。

4:opencv也是可以调用现成的深度神经网络模型的
可以调用,pytorch、tensorflow、darknet等深度学习模型。这里我们使用darknet的模型调用,其他的都是可以触类旁通的啊。
学习自:https://zhuanlan.zhihu.com/p/51928656
主要是学习主要的函数的使用。

第一部分:用一张图像测试

import cv2
import numpy as npdef readAllCleassNames(filename):with open(filename, 'rt') as f:classNames = f.read().rstrip('\n').split('\n')return classNamesdef findAllObjects(outputs, img):confidence_threshold = 0.5h_src, w_src, c_src = img.shapeboundingbox = []  # 存储所有检结果的 boundingboxclassIds = []  # 存储所有检结果的 classnamecondiences = []  # 存储所有检结果的 confidence度,置信度for output in outputs:for result in output:head_confidence = result[4]  # 第五个值是总的置信度classes_confience = result[5:]  # 从第6个值开始到最后一共80个数值是每个class的置信度class_id = np.argmax(classes_confience)  # 获得哪个置信度最高就是认为是哪个classclass_max_confidence = classes_confience[class_id]  # 得到最高的置信度的数值# 进行置信度值过滤,confidence很低的就过滤掉if head_confidence > confidence_threshold and class_max_confidence > confidence_threshold:# 现在我们获得了一个结果cx, cy, w, h = result[0:4]  # 前俩个值是中心点的坐标,是算比例的,后俩数值是宽度和长度的比例# 将上述结果换算到原始图像上res_w, res_h = int(w_src * w), int(h_src * h)res_x, res_y = int(w_src * cx - 0.5 * res_w), int(h_src * cy - 0.5 * res_h)# 保存该结果boundingbox.append([res_x, res_y, res_w, res_h])classIds.append(class_id)condiences.append(class_max_confidence)# 进行NMS处理,这样经过非极大抑制后的结果更加准确,去掉了一些重复的区域。# 返回的结果indices是,保留了结果boundingbox的list下标。indices = cv2.dnn.NMSBoxes(boundingbox, condiences, confidence_threshold, nms_threshold=0.3)return boundingbox, classIds, condiences, indicesif __name__ == '__main__':# ======================= step 1: 先获得所有的类别信息classNames = readAllCleassNames('file/coco_classnames.txt')print(len(classNames))  # 一共有80个类别print(classNames)# ======================= step 2: 加载预先训练好的yolov3模型,加载模型和各个模型各个参数的权重值。# 这里加载的用DarkNet训练的模型和权重,还可以从Caffe, pytorch, tensor-flow, ONNX上加载对应的文件modelcfg = 'file/yolov3_320.cfg'modelWeights = 'file/yolov3_320.weights'# modelcfg = 'file/yolov3_tiny.cfg'# modelWeights = 'file/yolov3_tiny.weights'# 得到DarkNet上训练的yolov3模型和权重,得到了一个神经网络对象net = cv2.dnn.readNetFromDarknet(modelcfg, modelWeights)# 设置运行的背景,一般情况都是使用opencv dnn作为后台计算net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)# 设置目标设备, DNN_TARGET_CPU其中表示使用CPU计算,默认是的net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)# ======================= step 3: 得到一个图像,转换后将其输入模型。img = cv2.imread('images/car_person.jpeg')# cv2.imshow('cat', img)# cv2.waitKey(0)# 转成blob的形式w_h_size = 320blob = cv2.dnn.blobFromImage(image=img,  # 输入图像scalefactor=1 / 255,  # 进行缩放,这个就是归一化操作,值全部在[0,1]之间size=(w_h_size, w_h_size),  # 输入图像的mean=[0, 0, 0],  # 给输入图像的每个通道的均值swapRB=1)  # 交换R和B通道net.setInput(blob)  # 设置输入# ======================= step 4: 得到输出结果,取出三个输出层的结果layerNames = net.getLayerNames()print(layerNames)  # 输入所有的每一层的名字和序号,这里返回layers的名字output_layers_ids = net.getUnconnectedOutLayers()  # yolov3有三个输出层print(output_layers_ids)  # 输入所有的输出层的序号,这里返回layers的下标序号,注意是从1开始的output_layers_names = [layerNames[layer_id - 1] for layer_id in output_layers_ids]print(output_layers_names)  # 得到所有的输出层的名字outputs = net.forward(output_layers_names)  # 设置前向传播的需要拿到的层的数据# print(len(outputs))  # 值是3, 因为yolov3有三个输出层# print(type(outputs))  # <class 'tuple'># 下面是yolov3-320的输出结果,它有三个输出层# print(type(outputs[0]))  # <class 'numpy.ndarray'># print(outputs[0].shape)  # (300, 85),有300个结果,每个结果是(cx, cy, w, h, confidence, 80 * class_confidence)# print(type(outputs[1]))  # <class 'numpy.ndarray'># print(outputs[1].shape)  # (1200, 85),有1200个结果,每个结果是(cx, cy, w, h, confidence, 80 * class_confidence)# print(type(outputs[2]))  # <class 'numpy.ndarray'># print(outputs[2].shape)  # (4800, 85),有4800个结果,每个结果是(cx, cy, w, h, confidence, 80 * class_confidence)# 下面是yolov3-tiny的输出结果,yolov3-tiny只有两个输出层# print(type(outputs[0]))  # <class 'numpy.ndarray'># print(outputs[0].shape)  # (300, 85),有300个结果,每个结果是(cx, cy, w, h, confidence, 80 * class_confidence)# print(type(outputs[1]))  # <class 'numpy.ndarray'># print(outputs[1].shape)  # (1200, 85),有1200个结果,每个结果是(cx, cy, w, h, confidence, 80 * class_confidence)# ======================= step 5: 将结果解析,定在图上画出来bboxes, classids, confidences, indices = findAllObjects(outputs=outputs, img=img)print('In the end, we get {} results.'.format(len(indices)))  # 打印出我们得到了多少结果# 在原始图像上画出这个矩形框,以及在框上画出类别和置信度for idx in indices:bbox = bboxes[idx]class_name = classNames[classids[idx]]confidence = confidences[idx]x, y, w, h = bboxcv2.rectangle(img, pt1=(x, y), pt2=(x+w, y+h), color=(255, 0, 0), thickness=3)cv2.putText(img, text="classN_name:{}, confidence:{}%".format(class_name.upper(), "%.2f" % (confidence * 100)),org=(x, y-10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.6,color=(0, 0, 255), thickness=2)# 展示结果cv2.imshow('car_person', img)cv2.waitKey(0)

使用yolov3-320模型测试,准去度高,但是速度慢。

使用yolov3-tiny模型测试,准去度低很多,但是速度块很多。

第二部分:开启摄像头

import cv2
import numpy as npdef readAllCleassNames(filename):with open(filename, 'rt') as f:classNames = f.read().rstrip('\n').split('\n')return classNamesdef findAllObjects(outputs, img):confidence_threshold = 0.5h_src, w_src, c_src = img.shapeboundingbox = []  # 存储所有检结果的 boundingboxclassIds = []  # 存储所有检结果的 classnamecondiences = []  # 存储所有检结果的 confidence度,置信度for output in outputs:for result in output:head_confidence = result[4]  # 第五个值是总的置信度classes_confience = result[5:]  # 从第6个值开始到最后一共80个数值是每个class的置信度class_id = np.argmax(classes_confience)  # 获得哪个置信度最高就是认为是哪个classclass_max_confidence = classes_confience[class_id]  # 得到最高的置信度的数值# 进行置信度值过滤,confidence很低的就过滤掉if head_confidence > confidence_threshold and class_max_confidence > confidence_threshold:# 现在我们获得了一个结果cx, cy, w, h = result[0:4]  # 前俩个值是中心点的坐标,是算比例的,后俩数值是宽度和长度的比例# 将上述结果换算到原始图像上res_w, res_h = int(w_src * w), int(h_src * h)res_x, res_y = int(w_src * cx - 0.5 * res_w), int(h_src * cy - 0.5 * res_h)# 保存该结果boundingbox.append([res_x, res_y, res_w, res_h])classIds.append(class_id)condiences.append(class_max_confidence)# 进行NMS处理,这样经过非极大抑制后的结果更加准确,去掉了一些重复的区域。# 返回的结果indices是,保留了结果boundingbox的list下标。indices = cv2.dnn.NMSBoxes(boundingbox, condiences, confidence_threshold, nms_threshold=0.3)return boundingbox, classIds, condiences, indicesif __name__ == '__main__':# ======================= step 1: 先获得所有的类别信息classNames = readAllCleassNames('file/coco_classnames.txt')print(len(classNames))  # 一共有80个类别print(classNames)# ======================= step 2: 加载预先训练好的yolov3模型,加载模型和各个模型各个参数的权重值。# 这里加载的用DarkNet训练的模型和权重,还可以从Caffe, pytorch, tensor-flow, ONNX上加载对应的文件modelcfg = 'file/yolov3_320.cfg'modelWeights = 'file/yolov3_320.weights'# modelcfg = 'file/yolov3_tiny.cfg'# modelWeights = 'file/yolov3_tiny.weights'# 得到DarkNet上训练的yolov3模型和权重,得到了一个神经网络对象net = cv2.dnn.readNetFromDarknet(modelcfg, modelWeights)# 设置运行的背景,一般情况都是使用opencv dnn作为后台计算net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)# 设置目标设备, DNN_TARGET_CPU其中表示使用CPU计算,默认是的net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)# ======================= step 3: 开启摄像头,得到一个图像,转换后将其输入模型。cap = cv2.VideoCapture(0)while True:ret, img = cap.read()if img is None:print("video is over...")break# 转成blob的形式w_h_size = 320blob = cv2.dnn.blobFromImage(image=img,  # 输入图像scalefactor=1 / 255,  # 进行缩放,这个就是归一化操作,值全部在[0,1]之间size=(w_h_size, w_h_size),  # 输入图像的mean=[0, 0, 0],  # 给输入图像的每个通道的均值swapRB=1)  # 交换R和B通道net.setInput(blob)  # 设置输入# ======================= step 4: 得到输出结果,取出三个输出层的结果layerNames = net.getLayerNames()# print(layerNames)  # 输入所有的每一层的名字和序号,这里返回layers的名字output_layers_ids = net.getUnconnectedOutLayers()  # yolov3有三个输出层# print(output_layers_ids)  # 输入所有的输出层的序号,这里返回layers的下标序号,注意是从1开始的output_layers_names = [layerNames[layer_id - 1] for layer_id in output_layers_ids]print(output_layers_names)  # 得到所有的输出层的名字outputs = net.forward(output_layers_names)  # 设置前向传播的需要拿到的层的数据# print(len(outputs))  # 值是3, 因为yolov3有三个输出层# print(type(outputs))  # <class 'tuple'># ======================= step 5: 将结果解析,定在图上画出来bboxes, classids, confidences, indices = findAllObjects(outputs=outputs, img=img)print('In the end, we get {} results.'.format(len(indices)))  # 打印出我们得到了多少结果# 在原始图像上画出这个矩形框,以及在框上画出类别和置信度for idx in indices:bbox = bboxes[idx]class_name = classNames[classids[idx]]confidence = confidences[idx]x, y, w, h = bboxcv2.rectangle(img, pt1=(x, y), pt2=(x+w, y+h), color=(255, 0, 0), thickness=3)cv2.putText(img, text="classN_name:{}, confidence:{}%".format(class_name.upper(), "%.2f" % (confidence * 100)),org=(x, y-10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.6,color=(0, 0, 255), thickness=2)# 展示结果cv2.imshow('test', img)cv2.waitKey(1)

效果如下:

【opencv有趣应用】opencv + YOLOV3 + COCO数据集的简单应用相关推荐

  1. cocostuff10k数据集介绍_(六)COCO数据集的简单介绍

    COCO通过大量使用Amazon Mechanical Turk来收集数据.COCO数据集现在有3种标注类型:object instances(目标实例), object keypoints(目标上的 ...

  2. 【opencv有趣应用】基于MobileNet + SSD的物体检测

    今天学习使用另外的模型进行物体检测 当前目标检测的算法有很多,如rcnn系列.yolo系列和ssd,前端网络如vgg.AlexNet.SqueezeNet,一种常用的方法是将前端网络设为MobileN ...

  3. 如何正确使用COCO数据集

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 简介 COCO数据集,意为"Common Objects ...

  4. COCO数据集格式解析

    COCO数据集是我们经常使用的一个数据集,并且 COCO数据集格式也很受大家欢迎,但不同于 VOC数据格式,COCO是将所有的标注数据存放在一个json文件中,使得查看的时候云里雾里,最近也在用COC ...

  5. COCO数据集可视化程序(包括bbox和segmentation)

    出于项目需要,需要对COCO数据集做可视化,但网上没有比较好用的可视化方法,于是自己写了一个.分为三部分:1.标注框bbox的单独可视化,2.分割标注segmentation的单独可视化,3.bbox ...

  6. coco数据集转voc格式(附pycocotools下载方法)

    1.coco数据集高速下载 我下载的是train2017.val2017和annotations_trainval2017,即coco2017的训练集(118287张图片).测试集(5000张图片)和 ...

  7. OpenMMLab-AI实战营第二期——相关1. COCO数据集格式和pycocotools使用(目标检测方向)

    文章目录 1. COCO数据集 1.1 COCO数据集介绍 1.2 COCO数据集格式 1.2.1 常见目标检测数据格式 1.2.2 COCO数据集文件结构及标注文件说明 1.2.3 RLE格式 1. ...

  8. Dataset之COCO数据集:COCO数据集的简介、下载、使用方法之详细攻略

    Dataset之COCO数据集:COCO数据集的简介.安装.使用方法之详细攻略 目录 COCO数据集的简介 0.COCO数据集的80个类别-YoloV3算法采用的数据集 1.COCO数据集的意义 2. ...

  9. COCO 数据集的使用

    Windows 10 编译 Pycocotools 踩坑记 COCO数据库简介 微软发布的COCO数据库, 除了图片以外还提供物体检测, 分割(segmentation)和对图像的语义文本描述信息. ...

最新文章

  1. php数据分析引擎,PHP数据分析引擎计算余弦相似度算法示例
  2. R语言保存加载工作空间或者工作空间数据对象实战(Save Load RData Workspace)
  3. Oracle 12C -- 扩展varchar2、nvarchar2、和raw数据类型的大小限制
  4. fatal error C1083: Cannot open include file: 'ceconfig.h': No such file or directory
  5. 有趣的php实例,8个必备的PHP功能实例代码
  6. 成长 | 《大厂晋升指南》学习总结(上)
  7. 中国“鸭王”失宠的第8年,终于撑不住了!
  8. 【SAS BASE】SAS函数
  9. 在 Mac 上的 Pages 文稿中如何添加和替换文本?
  10. 最新CleanMyMac支持MacOS 12.x
  11. 21世纪经济网APP
  12. 管理感悟:经历不是经验,套路才是
  13. 学生信息管理系统(JAVA+MYSQL)
  14. python语言与存货管理,(二)实现对库存管理系统的模块化编程
  15. 提升用户体验的40个Firefox 4扩展
  16. envi精度评定_利用ArcGIS+envi实现遥感分类精度评价(分层抽样法),ArcGISENVI,评估,的...
  17. 金蝶K3即时库存成本计算逻辑是什么?
  18. html页面打印a4尺寸,html网页打印A4样式
  19. 约分最简分式 (15 分)
  20. 关于大象,冰箱和软件项目报价的故事

热门文章

  1. 25k英里高速建48个充电走廊,美国电动汽车产业迎来春天
  2. 基于HTML5 的人脸识别技术
  3. 修改数据库端口为51433
  4. 从BIOS自检报警声判断电脑故障
  5. Vue-cli3配置教程入门
  6. JavaScript缓存处理代码
  7. 容器编排技术 -- 使用Minikube在Kubernetes中运行应用
  8. 修改oracle实例名orcl为demo
  9. Java 11新特性
  10. c语言 数组循环左移m位