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


      

    将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("
    ")
     
    # 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模型并确定输出层名称。
    接下来,将处理一些特定于视频的任务:

    # 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

    在上述代码块中:

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

    之后逐个处理帧:

    # 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 :

      # 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
    图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
    图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
    图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
    图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
    图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算法。
    如果你有兴趣在自己的自定义数据集上训练深度学习对象检测器,请务必参阅写的“使用Python进行计算机视觉深度学习”,其中提供了有关如何成功训练自己的检测器的详细指南。

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

  • 相关阅读:
    4-9 内置函数和匿名函数的题
    4-09 试题
    4--2日 函数 装饰器 作业题
    if 语句
    4-4日 内置函数,匿名函数
    4-4日 列表推导式,生成器推导式
    4-3日 迭代器 生成器
    4-2日装饰器,带参数的装饰器
    python 函数名 、闭包 装饰器 day13
    [LeetCode]-DataBase-Department Top Three Salaries
  • 原文地址:https://www.cnblogs.com/yunqishequ/p/9999591.html
Copyright © 2020-2023  润新知