摘要: 本文介紹使用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.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
、 confidences
、classIDs
:
# 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...
在視頻/ 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...
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...
最後一個例子,讓我們看看如何使用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...
下面彙總YOLO視頻對象檢測完整視頻:
YOLO目標檢測器的侷限和缺點
YOLO目標檢測器的最大限制和缺點是:
- 它並不總能很好地處理小物體;
- 它尤其不適合處理密集的對象;
限制的原因是由於YOLO算法其本身:
- YOLO對象檢測器將輸入圖像劃分爲
SxS
網格,其中網格中的每個單元格僅預測單個對象; - 如果單個單元格中存在多個小對象,則YOLO將無法檢測到它們,最終導致錯過對象檢測;
因此,如果你的數據集是由許多靠近在一起的小對象組成時,那麼就不應該使用YOLO算法。就小物體而言,更快的R-CNN往往效果最好,但是其速度也最慢。在這裏也可以使用SSD算法, SSD通常在速度和準確性方面也有很好的權衡。
值得注意的是,在本教程中,YOLO比SSD運行速度慢,大約慢一個數量級。因此,如果你正在使用預先訓練的深度學習對象檢測器供OpenCV使用,可能需要考慮使用SSD算法而不是YOLO算法。
因此,在針對給定問題選擇對象檢測器時,我傾向於使用以下準則:
- 如果知道需要檢測的是小物體並且速度方面不作求,我傾向於使用faster R-CNN算法;
- 如果速度是最重要的,我傾向於使用YOLO算法;
- 如果需要一個平衡的表現,我傾向於使用SSD算法;
想要訓練自己的深度學習目標檢測器?
在本教程中,使用的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算法。
本文作者:【方向】
本文爲雲棲社區原創內容,未經允許不得轉載。