简体   繁体   中英

Open CV Car Detection with conditions

I'm attempting to create a program in which my code analyses a video from my security camera and locates the cars that have been spotted. I've figured out how to find the cars and draw red rectangles around them, but I'd like to add a condition that only draws boxes if there are more than 5 cars detected. However, I am unable to do so due to the presence of arrays. How would I go about fixing this code?


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)

By the way, I am using an anaconda environment along with python 3.8.8

Here is one example using a different technique, in this case you can use cvlib it has a class object_detection to detect multiple classes. This uses the yolov4 weights, you will be capable of detect any car in the road or in this case from one webcam, only make sure that the car are ahead the camera not in 2d position.

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()

output:

在此处输入图片说明

Greetings.

You have an array of detections.

All you need is to call len() on the array to get the number of elements. This is a built-in function of 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)

No need for any other libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM