Motion detection

asked 2015-05-03 11:45:21 -0500

shashank1234 gravatar image

Hi..I am very new to opencv. I am using opencv 2.4.10 C++ to detect motion using difference between successive frames. The code I used is given below. The problem with it is it shows no motion even if there is motion happening. That is diff window is always black.

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;
Mat diffImage(Mat t0,Mat t1,Mat t2)
  Mat d1,d2,motion;
  absdiff(t2, t1, d1);
  absdiff(t1, t0, d2);
  bitwise_and(d1, d2, motion);
  return motion;
int main()
    VideoCapture capture(0);
    Mat frame,prev_frame,next_frame,pbwf,bwf,nbwf;
    // 0 );
    if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; };;;
    cvtColor(prev_frame, pbwf, cv::COLOR_BGR2GRAY);
    cvtColor(frame, bwf, CV_RGB2GRAY);
    cvtColor(next_frame, nbwf, cv::COLOR_BGR2GRAY);
        cvtColor(next_frame, nbwf, cv::COLOR_BGR2GRAY);
        char c=waitKey(5);
    return 0;

Similar python script works well and as expected.

import cv2

def diffImg(t0, t1, t2):
  d1 = cv2.absdiff(t2, t1)
  d2 = cv2.absdiff(t1, t0)
  return cv2.bitwise_and(d1, d2)

cam = cv2.VideoCapture(0)

winName = "Movement Indicator"
cv2.namedWindow(winName, cv2.CV_WINDOW_AUTOSIZE)

# Read three images first:
t_minus = cv2.cvtColor([1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor([1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor([1], cv2.COLOR_RGB2GRAY)

while True:
  cv2.imshow( winName, diffImg(t_minus, t, t_plus) )

  # Read next image
  t_minus = t
  t = t_plus
  t_plus = cv2.cvtColor([1], cv2.COLOR_RGB2GRAY)

  key = cv2.waitKey(10)
  if key == 27:

print "Goodbye"

Can anyone tell me why this is the case. Thanks

edit retag flag offensive close merge delete


Your difference window should always be black, because that indicates your difference pixels are 0 and no movement is happening. If movement occurs you will get white pixels!

StevenPuttemans gravatar imageStevenPuttemans ( 2015-05-04 03:40:14 -0500 )edit

yeah...but i am trying to move my hand in front of the webcam...python script shows some white pixels...while the cpp the window remains black...thats the main issue!!

shashank1234 gravatar imageshashank1234 ( 2015-05-04 03:56:30 -0500 )edit

You are making it uterly complex to start with. Why not simply do something like

Grab frame 1
Grab frame 2
Take the difference between 2 and 1 by subtracting 1 from 2.
Binarize the image.

Seems way more logical than what you are doing.

StevenPuttemans gravatar imageStevenPuttemans ( 2015-05-04 06:06:40 -0500 )edit