Object Tracking Using OpenCV Python Windows

Adam Aulia Rahmadi
Miloo Community
Published in
2 min readNov 26, 2017

--

before we start, first download opencv, not from pip install version.
here. you can choose opencv version (*I use opencv 3.1.0 for this tutorial)

Installation
after installation is done find file in installation folder ‘cv2.pyd’ , copy into python library folder “site-packages”.

back into opencv installation folder find “opencv_ffmpeg310.dll” and “opencv_ffmpeg310_64.dll” copy these file into python.exe directory

Video

for demonstration I use this video

Code

import necessary package

import numpy as np
import cv2
import sys

load video to opencv

video_path = 'M6 Motorway Traffic.mp4'
cv2.ocl.setUseOpenCL(False)

version = cv2.__version__.split('.')[0]
print version

#read video file
cap = cv2.VideoCapture(video_path)

for windows , I include this cv2.ocl.setUseOpenCL(False) otherwise error occurred.

if use linux, just comment cv2.ocl.setUseOpenCL(False).

check opencv version

#check opencv version
if version == '2' :
fgbg = cv2.BackgroundSubtractorMOG2()
if version == '3':
fgbg = cv2.createBackgroundSubtractorMOG2()

looping each frame.

while (cap.isOpened):

#if ret is true than no error with cap.isOpened
ret, frame = cap.read()

if ret==True:

ret is boolean parameter, if there’s nothing wrong ret = True otherwise ret=False, IF ret = False, frame will be none

apply background subtraction

#apply background substraction
fgmask = fgbg.apply(frame)

background subtraction is a method to separate background(static object) and foreground (moving object).

apply contours on foreground

#check opencv version
if version == '2' :
(contours, hierarchy) = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if version == '3' :
(im2, contours, hierarchy) = cv2.findContours(fgmask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

looping each contours

#looping for contours
for c in contours:
if cv2.contourArea(c) < 500:
continue

#get bounding box from countour
(x, y, w, h) = cv2.boundingRect(c)

#draw bounding box
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

show the result

cv2.imshow('foreground and background',fgmask)
cv2.imshow('rgb',frame)

add exit key

if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
cv2.destroyAllWindows()

wrap it up

result

source : https://gist.github.com/adamaulia/51e5a0ee4ad834d4d3d685db819ef2a0

--

--

Adam Aulia Rahmadi
Miloo Community

data enthusiast, data scientist, data engineer, machine learning, deep learning, analytics, chef