1. 程式人生 > >10分鐘學會使用YOLO及Opencv實現目標檢測(下)|附原始碼

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("\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 、 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進行計算機視覺深度學習”,其中提供了有關如何成功訓練自己的檢測器的詳細指南。

 

原文連結
本文為雲棲社群原創內容,未經允許不得轉載。