OpenCV Python Project for Vehicle Detection in a Video frame¶
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.
Steps to download the requirements below:¶
Step 1: Download and Install Python
Step 2: Install Numpy Library
- pip install numpy
Step 3: Install OpenCV Python Library
- pip install opencv-python
Import Libraries of Python OpenCV¶
In [2]:
import numpy as np
import cv2
Trained XML classifiers describes some features of some object we want to detect¶
In [3]:
car_cascade = cv2.CascadeClassifier('cars.xml')
Check If Video File is Opened Successfully?¶
In [4]:
vc = cv2.VideoCapture('data/video1.avi')
if vc.isOpened():
rval , frame = vc.read()
else:
rval = False
print('Video Not Found')
Detect Car From Video¶
In [5]:
rectangles = []
while rval:
rval, frame = vc.read()
frameHeight, frameWidth, fdepth = frame.shape
frame = cv2.resize(frame, ( 600, 400 ))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.2, 2)
for (x, y, w, h) in cars:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow("Result",frame)
if cv2.waitKey(33) == ord('q'):
break
vc.release()
cv2.destroyAllWindows()
Output¶
Combine the Complete Code¶
In [1]:
import numpy as np
import cv2
car_cascade = cv2.CascadeClassifier('cars.xml')
vc = cv2.VideoCapture('data/video1.avi')
if vc.isOpened():
rval , frame = vc.read()
else:
rval = False
print('Video Not Found')
rectangles = []
while rval:
rval, frame = vc.read()
frameHeight, frameWidth, fdepth = frame.shape
frame = cv2.resize(frame, ( 600, 400 ))
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cars = car_cascade.detectMultiScale(gray, 1.2, 2)
for (x, y, w, h) in cars:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow("Result",frame)
if cv2.waitKey(33) == ord('q'):
break
vc.release()
cv2.destroyAllWindows()
c:\users\karan\appdata\local\programs\python\python36\lib\site-packages\numpy\_distributor_init.py:32: UserWarning: loaded more than 1 DLL from .libs: c:\users\karan\appdata\local\programs\python\python36\lib\site-packages\numpy\.libs\libopenblas.IPBC74C7KURV7CB2PKT5Z5FNR3SIBV4J.gfortran-win_amd64.dll c:\users\karan\appdata\local\programs\python\python36\lib\site-packages\numpy\.libs\libopenblas.QVLO2T66WEPI7JZ63PS3HMOHFEY472BC.gfortran-win_amd64.dll stacklevel=1)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-1-04f00594e1c7> in <module> 15 while rval: 16 rval, frame = vc.read() ---> 17 frameHeight, frameWidth, fdepth = frame.shape 18 frame = cv2.resize(frame, ( 600, 400 )) 19 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) AttributeError: 'NoneType' object has no attribute 'shape'
In [ ]: