Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 49 You must be signed in to star a gist
  • Fork 28 You must be signed in to fork a gist
  • Save pknowledge/623515e8ab35f1771ca2186630a13d14 to your computer and use it in GitHub Desktop.
Save pknowledge/623515e8ab35f1771ca2186630a13d14 to your computer and use it in GitHub Desktop.
Motion Detection and Tracking Using Opencv Contours
import cv2
import numpy as np
cap = cv2.VideoCapture('vtest.avi')
frame_width = int( cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height =int( cap.get( cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
out = cv2.VideoWriter("output.avi", fourcc, 5.0, (1280,720))
ret, frame1 = cap.read()
ret, frame2 = cap.read()
print(frame1.shape)
while cap.isOpened():
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
if cv2.contourArea(contour) < 900:
continue
cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.putText(frame1, "Status: {}".format('Movement'), (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
1, (0, 0, 255), 3)
#cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2)
image = cv2.resize(frame1, (1280,720))
out.write(image)
cv2.imshow("feed", frame1)
frame1 = frame2
ret, frame2 = cap.read()
if cv2.waitKey(40) == 27:
break
cv2.destroyAllWindows()
cap.release()
out.release()
@mihuzz
Copy link

mihuzz commented Aug 26, 2019

Ive got Error. Please help
Cant run this code
`Traceback (most recent call last):
File "/home/mihuzz/PycharmProjects/CV2/bas.py", line 15, in
print(frame1.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

Process finished with exit code 1
`

@jackson-sandland
Copy link

jackson-sandland commented Aug 27, 2019

@mihuzz what is the file extension of the video you are trying to run this code on?
If it is not avi you will need to handle the video with the appropriate openCV codec for your file tyoe.

For example, for an MP4 you could use:

fourcc = cv2.VideoWriter_fourcc(*"X264")
out = cv2.VideoWriter("output.mp4", fourcc, 15.0, (1280, 360))

@kim-mickey
Copy link

i got this error
Traceback (most recent call last):
File "basic_motion_detection_opencv_python.py", line 22, in
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

@sunllight
Copy link

Hello,
can you help me to find velocity of moving objects in this code?

@maxibianosoares
Copy link

Can you help me to count how many person in the video?

@a4438899
Copy link

I copied the code, the detection and tracking worked well, but after that, i got this error, can anyone help me?
Traceback (most recent call last):
File "/Users/guosicheng/PycharmProjects/test1/test11.py", line 19, in
diff = cv2.absdiff(frame1, frame2)
cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/core/src/arithm.cpp:669: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'arithm_op'

@ankushbanik1
Copy link

i got this error
Traceback (most recent call last):
File "basic_motion_detection_opencv_python.py", line 22, in
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

@mihuzz
Copy link

mihuzz commented Mar 4, 2020

i got this error
Traceback (most recent call last):
File "basic_motion_detection_opencv_python.py", line 22, in
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

HI!
Read tutuorial by link below, u forgot about "dilated":
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html

@PadmavathiPalakala
Copy link

PadmavathiPalakala commented Mar 4, 2020 via email

@shashwat623
Copy link

Hey, I have a question. Is this code not using any deep learning models for detection?? from what I can see, it is only detecting motion by extracting contours in the successive frames.

@suvarna236
Copy link

i got this error
Traceback (most recent call last):
File "basic_motion_detection_opencv_python.py", line 22, in
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

change contours, to contours,hierarchy
in next line change cnts into contours

@Geeky-star
Copy link

@mihuzz what is the file extension of the video you are trying to run this code on?
If it is not avi you will need to handle the video with the appropriate openCV codec for your file tyoe.

For example, for an MP4 you could use:

fourcc = cv2.VideoWriter_fourcc(*"X264")
out = cv2.VideoWriter("output.mp4", fourcc, 15.0, (1280, 360))

Ive got Error. Please help
Cant run this code
`Traceback (most recent call last):
File "/home/mihuzz/PycharmProjects/CV2/bas.py", line 15, in
print(frame1.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

Process finished with exit code 1
`

It is working even for mp4. These lines are working without any error. It might be an issue with IDE, I am using Spyder.

cap = cv2.VideoCapture('video.mp4')
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

fourcc = cv2.VideoWriter_fourcc('X', 'V', 'I', 'D')

out = cv2.VideoWriter("output.mp4", fourcc, 5.0, (1280,720))

ret, frame1 = cap.read()
ret, frame2 = cap.read()

print(frame1.shape)

@tonycpp
Copy link

tonycpp commented Jul 7, 2020

Hey guys,
I have a line error in every cv2. I have installed opencv and import at the first line.
image

I appreciate if someone could provide the solution
thanks!

@Geeky-star
Copy link

Geeky-star commented Jul 7, 2020

@tonycpp

You have imported cv2 as cv, and using cv2.

Replace cv2 with cv in program not while importing.
import cv2 as cv
cap=cv.VideoCapture("video.mp4);

Do like this.

@tonycpp
Copy link

tonycpp commented Jul 7, 2020

@tonycpp

You have imported cv2 as cv, and using cv2.

Replace cv2 with cv.

Hey @Geeky-star,
Same error
image

maybe the reason why is throwing an error is opencv version?

@git-ruthvik
Copy link

@tonycpp
You have imported cv2 as cv, and using cv2.
Replace cv2 with cv.

Hey @Geeky-star,
Same error
image

maybe the reason why is throwing an error is opencv version?

Are you using VS Code? I was also facing same issues with it but the same code will run well in any other IDE.
Quick fix if you still want to use VSCode, follow this thread https://stackoverflow.com/questions/50612169/pylint-not-recognizing-cv2-members

@suvarna236
Copy link

suvarna236 commented Jul 20, 2020 via email

@arunavijayan2299
Copy link

Hey guys,
I have a line error in every cv2. I have installed opencv and import at the first line.
image

I appreciate if someone could provide the solution
thanks!

@arunavijayan2299
Copy link

use cv instead of cv2 ,because you have imported cv2 as cv

@atziz
Copy link

atziz commented May 3, 2021

how can i get the test video???

@mekukun
Copy link

mekukun commented May 29, 2021

hi! How can I get the sample video shown in your youtube video?

@suvarna236
Copy link

suvarna236 commented May 30, 2021 via email

@OmarSalah26
Copy link

OmarSalah26 commented May 30, 2021

hi! How can I get the sample video shown in your youtube video?

I guess these two videos will help you
https://www.youtube.com/watch?v=MkcUgPhOlP8&t=2s

https://www.youtube.com/watch?v=PEApucRsaJ4&list=PLyhJeMedQd9QrXtCspclJ9ace2urp05o0&index=25

@omarsherif99
Copy link

hey there, does anyone know how to get the centroids of the boxes

@FavourChianumba
Copy link

Ive got Error. Please help
Cant run this code
`Traceback (most recent call last):
File "/home/mihuzz/PycharmProjects/CV2/bas.py", line 15, in
print(frame1.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

Process finished with exit code 1
`

I am having the same problem, are there any solutions

@mayurmoundekar5
Copy link

Hello,
I have a query. In this video, there is a No one is present in the video or No one Movement in the video.
So what code do I write for the No movement
I used lots of if statements in this code but is the problem is No Movement only 1-time display.

Simple I want to create Present or absent in the screen. I case the user left the screen so display Absent or User arrived so display Prenet

Can you Please Help Me

@Geeky-star
Copy link

Ive got Error. Please help
Cant run this code
`Traceback (most recent call last):
File "/home/mihuzz/PycharmProjects/CV2/bas.py", line 15, in
print(frame1.shape)
AttributeError: 'NoneType' object has no attribute 'shape'

Process finished with exit code 1
`

It does not run in my Python IDE also. It is not capturing any video that's why frame has None values and None does not have any shape.

@Svshah111
Copy link

print(frame1.shape)

AttributeError: 'NoneType' object has no attribute 'shape'

@Jjukkka
Copy link

Jjukkka commented Apr 5, 2022

Ive got Error. Please help
Cant run this code
Traceback (most recent call last): File "/home/mihuzz/PycharmProjects/CV2/bas.py", line 15, in print(frame1.shape) AttributeError: 'NoneType' object has no attribute 'shape' Process finished with exit code 1

I am having the same problem, are there any solutions

Ive got Error. Please help
Cant run this code
Traceback (most recent call last): File "/home/mihuzz/PycharmProjects/CV2/bas.py", line 15, in print(frame1.shape) AttributeError: 'NoneType' object has no attribute 'shape' Process finished with exit code 1

It does not run in my Python IDE also. It is not capturing any video that's why frame has None values and None does not have any shape.

print(frame1.shape)

AttributeError: 'NoneType' object has no attribute 'shape'

For some reason when I change video source file to be mp4 it works. avi file gives me this error
cap = cv2.VideoCapture('filename.mp4')

@Akaspreet
Copy link

whenever I run the code it work properly but the video I get as Output i.e. saved in my working directory not running as I tried both .avi and .mp4 format. Please help me to do so and run the output video
Screenshot (116)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment