10分钟学会使用YOLO及Opencv实现目标检测(下)|附源码

摘要: 本文介绍使用opencv和yolo完成视频流目标检测,代码解释详细,附源码,上手快。

在上一节内容中,介绍了如何将YOLO应用于图像目标检测中,那么在学会检测单张图像后,咱们也能够利用YOLO算法实现视频流中的目标检测。python

将YOLO应用于视频流对象检测

首先打开 yolo_video.py文件并插入如下代码:算法

# import the necessary packages
import numpy as np
import argparse
import imutils
import time
import cv2
import os

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
    help="path to input video")
ap.add_argument("-o", "--output", required=True,
    help="path to output video")
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 applyong non-maxima suppression")
args = vars(ap.parse_args())

一样,首先从导入相关数据包和命令行参数开始。与以前不一样的是,此脚本没有-- image参数,取而代之的是量个视频路径:网络

  • -- input  :输入视频文件的路径;
  • -- output  :输出视频文件的路径;

视频的输入能够是手机拍摄的短视频或者是网上搜索到的视频。另外,也能够经过将多张照片合成为一个短视频也能够。本博客使用的是在PyImageSearch上找到来自imutils的VideoStream类的 示例。
下面的代码与处理图形时候相同:架构

# load the COCO class labels our YOLO model was trained on
labelsPath = 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 label
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3),
    dtype="uint8")

# derive the paths to the YOLO weights and model configuration
weightsPath = 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)
# and determine only the *output* layer names that we need from YOLO
print("[INFO] loading YOLO from disk...")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]

在这里,加载标签并生成相应的颜色,而后加载YOLO模型并肯定输出层名称。
接下来,将处理一些特定于视频的任务:app

# initialize the video stream, pointer to output video file, and
# frame dimensions
vs = cv2.VideoCapture(args["input"])
writer = None
(W, H) = (None, None)

# try to determine the total number of frames in the video file
try:
    prop = cv2.cv.CV_CAP_PROP_FRAME_COUNT if imutils.is_cv2() \
        else cv2.CAP_PROP_FRAME_COUNT
    total = int(vs.get(prop))
    print("[INFO] {} total frames in video".format(total))

# an error occurred while trying to determine the total
# number of frames in the video file
except:
    print("[INFO] could not determine # of frames in video")
    print("[INFO] no approx. completion time can be provided")
    total = -1

在上述代码块中:dom

  • 打开一个指向视频文件的文件指针,循环读取帧;
  • 初始化视频编写器 (writer)和帧尺寸;
  • 尝试肯定视频文件中的总帧数(total),以便估计整个视频的处理时间;

以后逐个处理帧:ide

# loop over frames from the video file stream
while True:
    # read the next frame from the file
    (grabbed, frame) = vs.read()

    # if the frame was not grabbed, then we have reached the end
    # of the stream
    if not grabbed:
        break

    # if the frame dimensions are empty, grab them
    if W is None or H is None:
        (H, W) = frame.shape[:2]

上述定义了一个 while循环, 而后从第一帧开始进行处理,而且会检查它是不是视频的最后一帧。接下来,若是还没有知道帧的尺寸,就会获取一下对应的尺寸。
接下来,使用当前帧做为输入执行YOLO的前向传递 :函数

ect Detection with OpenCVPython

    # construct a blob from the input frame and then perform a forward
    # pass of the YOLO object detector, giving us our bounding boxes
    # and associated probabilities
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),
        swapRB=True, crop=False)
    net.setInput(blob)
    start = time.time()
    layerOutputs = net.forward(ln)
    end = time.time()

    # initialize our lists of detected bounding boxes, confidences,
    # and class IDs, respectively
    boxes = []
    confidences = []
    classIDs = []

在这里,构建一个 blob 并将其传递经过网络,从而得到预测。而后继续初始化以前在图像目标检测中使用过的三个列表: boxes 、 confidencesclassIDs :oop

# loop over each of the layer outputs
    for 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)

在上述代码中,与图像目标检测相同的有:学习

  • 循环输出层和检测;
  • 提取 classID并过滤掉弱预测;
  • 计算边界框坐标;
  • 更新各自的列表;

接下来,将应用非最大值抑制:

# apply non-maxima suppression to suppress weak, overlapping
    # bounding boxes
    idxs = cv2.dnn.NMSBoxes(boxes, confidences, args["confidence"],
        args["threshold"])

    # ensure at least one detection exists
    if len(idxs) > 0:
        # loop over the indexes we are keeping
        for i in idxs.flatten():
            # extract the bounding box coordinates
            (x, y) = (boxes[i][0], boxes[i][1])
            (w, h) = (boxes[i][2], boxes[i][3])

            # draw a bounding box rectangle and label on the frame
            color = [int(c) for c in COLORS[classIDs[i]]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            text = "{}: {:.4f}".format(LABELS[classIDs[i]],
                confidences[i])
            cv2.putText(frame, text, (x, y - 5),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

一样的,在上述代码中与图像目标检测相同的有:

  • 使用cv2.dnn.NMSBoxes函数用于抑制弱的重叠边界框,能够在此处阅读有关非最大值抑制的更多信息;
  • 循环遍历由NMS计算的idx,并绘制相应的边界框+标签;

最终的部分代码以下:

# check if the video writer is None
    if writer is None:
        # initialize our video writer
        fourcc = cv2.VideoWriter_fourcc(*"MJPG")
        writer = cv2.VideoWriter(args["output"], fourcc, 30,
            (frame.shape[1], frame.shape[0]), True)

        # some information on processing single frame
        if total > 0:
            elap = (end - start)
            print("[INFO] single frame took {:.4f} seconds".format(elap))
            print("[INFO] estimated total time to finish: {:.4f}".format(
                elap * total))

    # write the output frame to disk
    writer.write(frame)

# release the file pointers
print("[INFO] cleaning up...")
writer.release()
vs.release()

总结一下:

  • 初始化视频编写器(writer),通常在循环的第一次迭代被初始化;
  • 打印出对处理视频所需时间的估计;
  • 将帧(frame)写入输出视频文件;
  • 清理和释放指针;

如今,打开一个终端并执行如下命令:

$ python yolo_video.py --input videos/car_chase_01.mp4 \
    --output output/car_chase_01.avi --yolo yolo-coco
[INFO] loading YOLO from disk...
[INFO] 583 total frames in video
[INFO] single frame took 0.3500 seconds
[INFO] estimated total time to finish: 204.0238
[INFO] cleaning up...

图6:YOLO应用于车祸视频对象检测

在视频/ GIF中,你不只能够看到被检测到的车辆,还能够检测到人员以及交通讯号灯!
YOLO目标检测器在该视频中表现至关不错。让如今尝试同一车追逐视频中的不一样视频:

$ python yolo_video.py --input videos/car_chase_02.mp4 \
    --output output/car_chase_02.avi --yolo yolo-coco
[INFO] loading YOLO from disk...
[INFO] 3132 total frames in video
[INFO] single frame took 0.3455 seconds
[INFO] estimated total time to finish: 1082.0806
[INFO] cleaning up...

图7:在该视频中,使用OpenCV和YOLO对象检测来找到该嫌疑人,嫌疑人如今已经逃离汽车并正位于停车场

YOLO再一次可以检测到行人!或者嫌疑人回到他们的车中并继续追逐:

$ python yolo_video.py --input videos/car_chase_03.mp4 \
    --output output/car_chase_03.avi --yolo yolo-coco
[INFO] loading YOLO from disk...
[INFO] 749 total frames in video
[INFO] single frame took 0.3442 seconds
[INFO] estimated total time to finish: 257.8418
[INFO] cleaning up...

图8: YOLO是一种快速深度学习对象检测器,可以在使用GPU的状况下用于实时视频

最后一个例子,让咱们看看如何使用YOLO做为构建流量计数器:

$ python yolo_video.py --input videos/overpass.mp4 \
    --output output/overpass.avi --yolo yolo-coco
[INFO] loading YOLO from disk...
[INFO] 812 total frames in video
[INFO] single frame took 0.3534 seconds
[INFO] estimated total time to finish: 286.9583
[INFO] cleaning up...

图9:立交桥交通视频代表,YOLO和OpenCV可准确、快速地检测汽车

下面汇总YOLO视频对象检测完整视频:

YOLO目标检测器的局限和缺点

YOLO目标检测器的最大限制和缺点是:

  • 它并不总能很好地处理小物体;
  • 它尤为不适合处理密集的对象;

限制的缘由是因为YOLO算法其自己:

  • YOLO对象检测器将输入图像划分为SxS网格,其中网格中的每一个单元格仅预测单个对象;
  • 若是单个单元格中存在多个小对象,则YOLO将没法检测到它们,最终致使错过对象检测;

所以,若是你的数据集是由许多靠近在一块儿的小对象组成时,那么就不该该使用YOLO算法。就小物体而言,更快的R-CNN每每效果最好,可是其速度也最慢。在这里也可使用SSD算法, SSD一般在速度和准确性方面也有很好的权衡。
值得注意的是,在本教程中,YOLO比SSD运行速度慢,大约慢一个数量级。所以,若是你正在使用预先训练的深度学习对象检测器供OpenCV使用,可能须要考虑使用SSD算法而不是YOLO算法。
所以,在针对给定问题选择对象检测器时,我倾向于使用如下准则:

  • 若是知道须要检测的是小物体而且速度方面不做求,我倾向于使用faster R-CNN算法;
  • 若是速度是最重要的,我倾向于使用YOLO算法;
  • 若是须要一个平衡的表现,我倾向于使用SSD算法;

想要训练本身的深度学习目标检测器?

图10:在个人书“使用Python进行计算机视觉的深度学习”中,我介绍了多种对象检测算法,包括faster R-CNN、SSD、RetinaNet。书中讲述了如何建立对象检测图像数据集、训练对象检测器并进行预测。

在本教程中,使用的YOLO模型是在COCO数据集上预先训练的.。可是,若是想在本身的数据集上训练深度学习对象检测器,该如何操做呢?
大致思路是本身标注数据集,按照darknet网站上的指示及网上博客本身更改相应的参数训练便可。或者在个人书“ 深度学习计算机视觉与Python”中,详细讲述了如何将faster R-CNN、SSD和RetinaNet应用于:

  • 检测图像中的徽标;
  • 检测交通标志;
  • 检测车辆的前视图和后视图(用于构建自动驾驶汽车应用);
  • 检测图像和视频流中武器;

书中的全部目标检测章节都包含对算法和代码的详细说明,确保你可以成功训练本身的对象检测器。在这里能够了解有关个人书的更多信息(并获取免费的示例章节和目录)。

总结

在本教程中,咱们学习了如何使用Deep Learning、OpenCV和Python完成YOLO对象检测。而后,咱们简要讨论了YOLO架构,并用Python实现:

  • 将YOLO对象检测应用于单个图像;
  • 将YOLO对象检测应用于视频流;

在配备的3GHz Intel Xeon W处理器的机器上,YOLO的单次前向传输耗时约0.3秒; 可是,使用单次检测器(SSD),检测耗时只需0.03秒,速度提高了一个数量级。对于使用OpenCV和Python在CPU上进行基于实时深度学习的对象检测,你可能须要考虑使用SSD算法。



本文做者:【方向】

阅读原文

本文为云栖社区原创内容,未经容许不得转载。

相关文章
相关标签/搜索