注意:opencv-python 目前只有 4.4.0 版本适配了 YOLOv4
1.模型获取
百度网盘下载链接:https://pan.baidu.com/s/1XrcPHdp2_4c-dKge2Guw4w 提取码:xsxb 。
2.导入 YOLOv4配置和权重文件并加载网络:
例:net =cv2.dnn_DetectionModel('yolov4.cfg', 'yolov4.weights')
3.检测函数 cv2.dnn_DetectionModel.detect(frame[, confThreshold[, nmsThreshold]])
[in] frame:识别图像
[in] confThreshold 用于根据置信度筛选框的阈值
[in] nmsThreshold非极大值抑制中使用的阈值
该函数返回值:
[out] classIds 结果检测中的类索引
[out] confidences 一组相应的置信度
[out] boxes 一组边界框。
例:detection=net.detect(img)
4.画出检测框
函数cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
pt1:左上的点坐标,pt2:右下的点坐标
[1] x,y,w,h=detection[2][0][0:4]
[2] cv2.rectangle(img, (x, y),(x+w, y+h),(255, 0,0 ), 2)
[3] cv2.imshow('detect',img)