OpenCV Python program for Vehicle detection in a Video frame

4

Face Detection Basics

The objective of the program given is to detect object of interest(Car) in video frames and to keep tracking the same object. This is an example of how to detect vehicles in Python.

Why Vehicle Detection?

  • The startling losses both in human lives and finance caused by vehicle accidents.
  • Detecting vehicles in images acquired from a moving platform is a challenging problem.

Steps to download the requirements below:

  • Download Python 2.7.x version, numpy and OpenCV 2.4.x version.Check if your Windows either 32 bit or 64 bit is compatible and install accordingly.
    sudo apt-get install python
    pip install numpy
    • install OpenCV from here
    • Make sure that numpy is running in your python then try to install opencv.
    • Put the cars.xml file in the same folder. Save this as .xml file.
    • Download this video from here as input
    # OpenCV Python program to detect cars in video frame
    # import libraries of python OpenCV 
    import cv2
    
    # capture frames from a video
    cap = cv2.VideoCapture('video.avi')
    
    # Trained XML classifiers describes some features of some object we want to detect
    car_cascade = cv2.CascadeClassifier('cars.xml')
    
    # loop runs if capturing has been initialized.
    while True:
        # reads frames from a video
        ret, frames = cap.read()
        
        # convert to gray scale of each frames
        gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY)
        
    
        # Detects cars of different sizes in the input image
        cars = car_cascade.detectMultiScale(gray, 1.1, 1)
        
        # To draw a rectangle in each cars
        for (x,y,w,h) in cars:
            cv2.rectangle(frames,(x,y),(x+w,y+h),(0,0,255),2)
    
       # Display frames in a window 
       cv2.imshow('video2', frames)
        
        # Wait for Esc key to stop
        if cv2.waitKey(33) == 27:
            break
    
    # De-allocate any associated memory usage
    cv2.destroyAllWindows()
    

    Output:
    OpenCV Python program for Vehicle detection in a Video frame

    References:

    This article is contributed by Afzal Ansari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

    GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



4 Average Difficulty : 4/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.