摘要: 本文介绍使用opencv和yolo完成视频流目标检测,代码解释详细,附源码,上手快。
在上一节内容中,介绍了如何将YOLO应用于图像目标检测中,那么在学会检测单张图像后,我们也可以利用YOLO算法实现视频流中的目标检测。
将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.re