
在计算机视觉领域,目标检测一直是诸如面部识别和行人检测等工业应用中相对流行和成熟的应用领域. 鄙视技术和上堂科技等国内公司在该领域处于领先地位. 与图像分类任务相比,目标检测将更加复杂,不仅需要知道图像是什么样的图像,而且还需要知道图像中包含的图像及其在图像中的位置,因此,其工业应用得到了广泛的比较. . 因此,今天,我将向读者介绍一种在该领域中效果很好的算法-“您只看一次”(yolo)目标识别 opencv,算法的作者很幽默,他的个人主页和论文风格也显示出它的气质,该算法目前是第三个版本,称为YoLo V3. 闲话少说目标识别 opencv,让我们在下面输入本教程的主要内容. 在本教程中,您将学习如何使用YOLO,OpenCV和Python检测图像和视频流中的对象. 主要内容是:
图1: YOLO目标检测器的简化
在基于深度学习的对象检测中,三种常用算法是:
R-CNN算法是最早的基于深度学习的目标检测器之一,其结构是一个两层网络:
R-CNN算法的问题在于其仿真速度慢,并且不是一个完整的端到端目标检测器.
快速R-CNN算法对原始R-CNN进行了相当大的改进,即提高了准确性并减少了执行正向传递所需的时间,但是,该模型仍然依赖于外部区域搜索算法. 直到2015年,[更快的R-CNN]()才成为真正的端到端深度学习目标检测器,消除了选择性搜索的要求,而是依靠(1)完全卷积的区域提案网络(RPN) (2)可以预测对象的边界框和“对象”分数(该分数量化了它是一个区域的可能性). 然后将RPN的输出传递到R-CNN组件,以进行最终分类和标记. R-CNN系列算法的检测结果通常非常准确,但是R-CNN系列算法的最大问题是仿真速度非常慢,GPU上甚至只有5 FPS. 为了提高基于深度学习的目标检测器的速度,单发检测器(SSD)和YOLO都使用单阶段检测器策略(一个阶段). 这种类型的算法将对象检测视为回归问题,获得给定的输入图像,并同时了解边界框坐标和相应的类标签概率. 通常,单级检测器通常不如两级检测器准确,但是其速度明显更快. YOLO是单级检测器中的一种很好的算法. YOLO算法于2015年提出,并在GPU上实现了45 FPS性能. 此外,还提出了一个较小的变体“ Fast YOLO”,以在GPU上实现155 FPS性能. YOLO经历了许多迭代,包括YOLOv2,能够检测9,000多个目标. 在最近提出的YOLOv3算法之前,YOLOv3模型要比以前的版本复杂得多,但是它是YOLO系列目标检测器中最好的. 本文使用YOLOv3并在COCO数据集上进行训练. COCO数据集由80个标签组成,您可以使用此链接找到YOLO在COCO数据集上培训过的内容的完整列表.
使用终端中的tree命令,您可以快速轻松地生成目标树:
$ tree . ├── images │ ├── baggage_claim.jpg │ ├── dining_table.jpg │ ├── living_room.jpg │ └── soccer.jpg ├── output │ ├── airport_output.avi │ ├── car_chase_01_output.avi │ ├── car_chase_02_output.avi │ └── overpass_output.avi ├── videos │ ├── airport.mp4 │ ├── car_chase_01.mp4 │ ├── car_chase_02.mp4 │ └── overpass.mp4 ├── yolo-coco │ ├── coco.names │ ├── yolov3.cfg │ └── yolov3.weights ├── yolo.py └── yolo_video.py
从上面可以看到,该项目包括4个文件夹和2个Python脚本. 目录(按重要性排序)为:

此外,有两个Python脚本yolo.py和yolo_video.py,第一个脚本用于图像处理,第二个脚本用于视频处理. 现在输入实际战斗内容,您准备好了吗?
首先将YOLO目标检测器应用于图像,首先在项目中打开yolo .py并插入以下代码:
# import the necessary packagesimport numpy as npimport argparseimport timeimport cv2import os
# construct the argument parse and parse the argumentsap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to input image")
ap.add_argument("-y", "--yolo", required=True,
help="base path to YOLO directory")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
help="minimum probability to filter weak detections")
ap.add_argument("-t", "--threshold", type=float, default=0.3,
help="threshold when applying non-maxima suppression")
args = vars(ap.parse_args())
在使用之前,您需要为此脚本安装OpenCV版本3.4.2+或更高版本. 您可以直接使用pip install opencv-python == 3.4.2进行安装. 您也可以在这里找到OpenCV安装教程. OpenCV 4目前处于测试阶段. 建议在此处安装OpenCV 3.4.2+. 首先,导入所需的数据包-OpenCV和NumPy. 现在解析四个在运行时处理的命令行参数,使我们能够从终端更改脚本的输入. 如果您不熟悉它,建议阅读相关内容. 命令行参数包括:
解析后,args变量是一个字典,其中包含命令行参数的键值对. 让我们为每个标签设置随机颜色:
# load the COCO class labels our YOLO model was trained onlabelsPath = os.path.sep.join([args["yolo"], "coco.names"])
LABELS = open(labelsPath).read().strip().split("\n")
# initialize a list of colors to represent each possible class labelnp.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
dtype="uint8")
以上所有标签均已加载,类型为列表,保存了类别名称,然后为每个标签分配了随机颜色. 设置YOLO权重和配置文件的路径,然后从磁盘加载YOLO文件:
# derive the paths to the YOLO weights and model configurationweightsPath = os.path.sep.join([args["yolo"], "yolov3.weights"])
configPath = os.path.sep.join([args["yolo"], "yolov3.cfg"])
# load our YOLO object detector trained on COCO dataset (80 classes)print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
从磁盘加载YOLO文件,并在OpenCV中使用cv2.dnn.readNetFromDarknet函数读取网络文件和权重参数后,该函数需要两个参数configPath和weightsPath,这里再次强调: OpenCV至少需要3.4.2及更高版本才能运行此代码,因为它需要加载YOLO所需的更新的dnn模块. 加载图像并在下面进行处理:

# load our input image and grab its spatial dimensionsimage = cv2.imread(args["image"])
(H, W) = image.shape[:2]
# determine only the *output* layer names that we need from YOLOln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# construct a blob from the input image and then perform a forward# pass of the YOLO object detector, giving us our bounding boxes and# associated probabilitiesblob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416),
swapRB=True, crop=False)
net.setInput(blob)
start = time.time()
layerOutputs = net.forward(ln)
end = time.time()
# show timing information on YOLOprint("[INFO] YOLO took {:.6f} seconds".format(end - start))
在此代码中:
如果对blob和cv2.dnn.blobFromImage有疑问,可以阅读此博客以了解更多信息. 当Blob准备好后,我们将
# initialize our lists of detected bounding boxes, confidences, and# class IDs, respectivelyboxes = [] confidences = [] classIDs = []
这些列表包括:
以下使用YOLO layerOutputs的数据填充这些列表:
# loop over each of the layer outputsfor output in layerOutputs: # loop over each of the detections
for detection in output: # extract the class ID and confidence (i.e., probability) of
# the current object detection
scores = detection[5:]
classID = np.argmax(scores)
confidence = scores[classID]
# filter out weak predictions by ensuring the detected
# probability is greater than the minimum probability
if confidence > args["confidence"]: # scale the bounding box coordinates back relative to the
# size of the image, keeping in mind that YOLO actually
# returns the center (x, y)-coordinates of the bounding
# box followed by the boxes' width and height
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
# use the center (x, y)-coordinates to derive the top and
# and left corner of the bounding box
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
# update our list of bounding box coordinates, confidences,
# and class IDs
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-218523-1.html
马云先生