Ask Your Question

Revision history [back]

Motion detection

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;
    //capture.open( 0 );
    if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; }

    capture.read(prev_frame);
    capture.read(frame);
    capture.read(next_frame);
    cvtColor(prev_frame, pbwf, cv::COLOR_BGR2GRAY);
    cvtColor(frame, bwf, CV_RGB2GRAY);
    cvtColor(next_frame, nbwf, cv::COLOR_BGR2GRAY);
    while(1)
    {
        imshow("diff",diffImage(pbwf,bwf,nbwf));
        imshow("pnwf",pbwf);
        imshow("bnwf",bwf);
        imshow("nbwf",nbwf);
        //prev_frame=frame;
       //frame=next_frame;
       pbwf=bwf;
       bwf=nbwf;
        capture.read(next_frame);
        cvtColor(next_frame, nbwf, cv::COLOR_BGR2GRAY);
        char c=waitKey(5);
        if((char)c==27)
            break;
    } 
    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(cam.read()[1], cv2.COLOR_RGB2GRAY)
t = cv2.cvtColor(cam.read()[1], cv2.COLOR_RGB2GRAY)
t_plus = cv2.cvtColor(cam.read()[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(cam.read()[1], cv2.COLOR_RGB2GRAY)

  key = cv2.waitKey(10)
  if key == 27:
    cv2.destroyWindow(winName)
    break

print "Goodbye"

Can anyone tell me why this is the case. Thanks