opencv+yolov3实现目标检测
效果图
代码/font>
语言:python
import cv2 as cv
import argparse
import numpy as np# Initialize the parameters
confThreshold = 0.25 # Confidence threshold
nmsThreshold = 0.4 # Non-maximum suppression threshold
inpWidth = 320 # Width of network's input image
inpHeight = 320 # Height of network's input image# Give the configuration and weight files for the model and load the network using them.
modelConfiguration = "Yolo-Fastest-voc/yolo-fastest-xl.cfg"
modelWeights = "Yolo-Fastest-voc/yolo-fastest-xl.weights"
# Load names of classes
classesFile = "voc.names"
classes = None
with open(classesFile, 'rt') as f:classes = f.read().rstrip('\n').split('\n')
colors = [np.random.randint(0, 255, size=3).tolist() for _ in range(len(classes))]# Get the names of the output layers
def getOutputsNames(net):# Get the names of all the layers in the networklayersNames = net.getLayerNames()# print(dir(net))# Get the names of the output layers, i.e. the layers with unconnected outputsreturn [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]# Draw the predicted bounding box
def drawPred(classId, conf, left, top, right, bottom):# Draw a bounding box.cv.rectangle(frame, (left, top), (right, bottom), (0,0,255), thickness=4)label = '%.2f' % conf# Get the label for the class name and its confidenceif classes:assert (classId < len(classes))label = '%s:%s' % (classes[classId], label)# Display the label at the top of the bounding boxlabelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)top = max(top, labelSize[1])# cv.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine), (255,255,255), cv.FILLED)cv.putText(frame, label, (left, top-10), cv.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), thickness=2)# Remove the bounding boxes with low confidence using non-maxima suppression
def postprocess(frame, outs):frameHeight = frame.shape[0]frameWidth = frame.shape[1]classIds = []confidences = []boxes = []# Scan through all the bounding boxes output from the network and keep only the# ones with high confidence scores. Assign the box's class label as the class with the highest score.classIds = []confidences = []boxes = []for out in outs:for detection in out:scores = detection[5:]classId = np.argmax(scores)confidence = scores[classId]if confidence > confThreshold:center_x = int(detection[0] * frameWidth)center_y = int(detection[1] * frameHeight)width = int(detection[2] * frameWidth)height = int(detection[3] * frameHeight)left = int(center_x - width / 2)top = int(center_y - height / 2)classIds.append(classId)confidences.append(float(confidence))boxes.append([left, top, width, height])# Perform non maximum suppression to eliminate redundant overlapping boxes with# lower confidences.indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)for i in indices:i = i[0]box = boxes[i]left = box[0]top = box[1]width = box[2]height = box[3]drawPred(classIds[i], confidences[i], left, top, left + width, top + height)if __name__=='__main__':parser = argparse.ArgumentParser(description='Object Detection using YOLO in OPENCV')parser.add_argument('--image', type=str, default='person.jpg', help='Path to image file.')args = parser.parse_args()net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)# Process inputsframe = cv.imread(args.image)# Create a 4D blob from a frame.blob = cv.dnn.blobFromImage(frame, 1/255.0, (inpWidth, inpHeight), [0, 0, 0], swapRB=False, crop=False)# Sets the input to the networknet.setInput(blob)# Runs the forward pass to get output of the output layersouts = net.forward(getOutputsNames(net))# Remove the bounding boxes with low confidencepostprocess(frame, outs)# Put efficiency information. The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in layersTimes)t, _ = net.getPerfProfile()label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))winName = 'Deep learning object detection in OpenCV'cv.namedWindow(winName,0)cv.imshow(winName, frame)cv.waitKey(0)cv.destroyAllWindows()
代码的中图 存放位置 是和资源代码一个文件夹。路径为相对路径
parser.add_argument(’–image’, type=str, default=‘person.jpg’, help=‘Path to image file.’)
所有代码见个人资源:
https://download.csdn.net/download/KOBEYU652453/13082584
作者:电气余登武
opencv+yolov3实现目标检测相关推荐
- OpenCV+yolov3实现目标检测(C++,Python)
OpenCV+yolov3实现目标检测(C++,Python) 目标检测算法主要分为两类:一类是基于Region Proposal(候选区域)的算法,如R-CNN系算法(R-CNN,Fast R-CN ...
- OpenCV+yolov2-tiny实现目标检测(C++)
OpenCV+yolov2-tiny实现目标检测(C++) 目标检测算法主要分为两类:一类是基于Region Proposal(候选区域)的算法,如R-CNN系算法(R-CNN,Fast R-CNN, ...
- 【教程】opencv-python+yolov3实现目标检测
目录 [教程]opencv-python+yolov3实现目标检测 目标检测概况 目标检测是? 目标检测算法? yolov3模型简介 性能介绍 架构介绍 opencv-python实现 why ope ...
- 智慧交通day02-车流量检测实现12:基于yoloV3的目标检测
在本章节代码编写中,发现之前的代码所处的环境是python3,因此导致了cv2.dnn.readNetFromDarknet()在代码运行中导致了i[0]的获值失败,故总结如下: cv2.dnn.re ...
- 用C++ 和OpenCV 实现视频目标检测(YOLOv4模型)
点击上方"视学算法",选择加"星标"或"置顶" 重磅干货,第一时间送达 据说,现在很多小区都上线了AI抓拍高空抛物的黑科技,可以自动分析抛物 ...
- yolov3为什么对大目标检测不好_基于改进Yolov3的目标检测的研究
晏世武 罗金良 严庆 摘要:目标检测在视频监控.无人驾驶系统.机械自动化等领域起着重要作用.在如今大数据的背景下,为进一步提高Yolov3在不同数据集下的性能,本文以KITTI数据集为基础,利用重新調 ...
- python简单目标检测代码_Python Opencv实现单目标检测的示例代码
一 简介 目标检测即为在图像中找到自己感兴趣的部分,将其分割出来进行下一步操作,可避免背景的干扰.以下介绍几种基于opencv的单目标检测算法,算法总体思想先尽量将目标区域的像素值全置为1,背景区域全 ...
- YOLOv4 | 用C++ 和OpenCV 实现视频目标检测
据说,现在很多小区都上线了AI抓拍高空抛物的黑科技,可以自动分析抛物轨迹,用来协助检查很多不文明行为. 你想不想知道,这类检测视频中目标物的黑科技是怎么实现的呢? 虽然不同场景下的目标检测模型训练不同 ...
- YOLOv3物体/目标检测之实战篇(Windows系统、Python3、TensorFlow2版本)
前言 基于YOLO进行物体检测.对象识别,在搭建好开发环境后,先和大家进行实践应用中,体验YOLOv3物体/目标检测效果和魅力:同时逐步了解YOLOv3的不足和优化思路. 开发环境参数 系统:Wind ...
最新文章
- android studio编辑页面案例,2.4、Android Studio使用主题编辑器设计主题
- linux CentOs 权限导致的Apache - DocumentRoot must be a directory的解决方案
- 微信获取位置 转化为 高德地图 位置 地址
- mysql or走索引吗_加了索引,mysql查询就一定会用吗?
- c 子类对象 访问父类对象受保护成员_看了这个,你就会搞对象了
- 有了世界级的数据中心,你还会担心 “全年无休”吗?
- 一个简单的C#委托小例子
- 线条边框简笔画图片大全_表情包丨表情包简笔画图片大全可爱
- linux 每日学一点《将LINUX变成路由器》
- 蓝桥杯 c语言入门试题,蓝桥杯c语言试题2015
- python jinja2_Python jinja2
- 固定效应和随机效应模型
- 如何把晨光计算机调成音乐模式,伴着晨光走向你——广播《晨光音乐行》栏目运作心得...
- 王者荣耀游戏高清壁纸(手机|电脑),来袭
- Debian Etch 源配置
- python对外正式发布年份_python正式对外发布的年份
- 猫狗二分类实战(PyTorch)
- vue各类轮播图大全
- 记录一次redis莫名其妙丢失token的解决方案
- html怎么查看cad文件,怎么将电脑CAD文件在手机上查看?原来怎么简单!
热门文章
- 面试官:什么是HTTP连接池?你怎么回答?Feign性能调优之HTTP连接池
- mysql数据库系统配置文件_MySQL数据库(6)----配置文件 my.cnf 的使用
- C语言模拟质点运动轨迹坐标,C语言定时器的使用 计算质点运动的移位
- python +java 用socket在局域网进行图片上传给springboot后端并进行前端访问
- VUE基本语法1-插值 属性绑定
- Python基础day05【函数(函数传参的两种形式、函数形参)、拆包、引用、可变与不可变类型、引用做函数参数注意点】
- Android 中的线程及 AsyncTask(线程形态之一)解析一下
- PHP对二维数组中的某个字段的值进行排序
- 深入浅出理解锁之—— AbstractQueuedSynchronizer
- 写接口文档及生成mock数据