簡體   English   中英

有條件的開啟 CV 汽車檢測

[英]Open CV Car Detection with conditions

我正在嘗試創建一個程序,在該程序中我的代碼分析來自我的安全攝像頭的視頻並定位被發現的汽車。 我已經弄清楚如何找到汽車並在它們周圍繪制紅色矩形,但我想添加一個條件,如果檢測到超過 5 輛汽車,則僅繪制框。 但是,由於數組的存在,我無法這樣做。 我將如何修復此代碼?


import cv2

classifier_file = 'cars.xml'

car_tracker = cv2.CascadeClassifier(classifier_file)

video = cv2.VideoCapture("footage.mp4")


while True:
    (read_successful, frame) = video.read()

    if read_successful:
        grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    else:
        break
    
    cars = car_tracker.detectMultiScale(grayscaled_frame)

    if cars > 4:
        for (x, y, w, h) in cars:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)


    cv2.imshow('Car Detector', frame)
    cv2.waitKey(0)

順便說一句,我正在使用 anaconda 環境和 python 3.8.8

這是使用不同技術的一個示例,在這種情況下,您可以使用 cvlib 它有一個類object_detection來檢測多個類。 這使用 yolov4 權重,您將能夠檢測道路上的任何汽車,或者在這種情況下通過一個網絡攝像頭,只需確保汽車在攝像頭前面而不是在 2d 位置。

import cv2
import matplotlib.pyplot as plt
# pip install cvlib
import cvlib as cv
from cvlib.object_detection import draw_bbox


im = cv2.imread('cars3.jpg')

#cv2.imshow("cars", im)
#cv2.waitKey(0)

bbox, label, conf = cv.detect_common_objects(im) 
#yolov4 weights will be downloaded. Check: C:\Users\USER_NAME\.cvlib\object_detection\yolo
# if the download was not successful delete yolo folder and try again, it will be downloaded again
# after download the weights keep running the script it will say 0 cars, then close Anaconda spyder anda reopen it and try again.

#get bbox
output_image_with_bbox = draw_bbox(im, bbox, label, conf)


number_cars = label.count('car')
if number_cars > 5:
    print('Number of cars in the image is: '+ str(number_cars))
    plt.imshow(output_image_with_bbox)
    plt.show()
else:
    print('Number of cars in the image is: '+ str(number_cars))
    plt.imshow(im)
    plt.show()

輸出:

在此處輸入圖片說明

問候。

您有一系列檢測。

您只需要在數組上調用len()即可獲取元素數。 這是 Python 的內置函數。

cars = car_tracker.detectMultiScale(grayscaled_frame)

if len(cars) >= 5:
    for (x, y, w, h) in cars:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

不需要任何其他庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM