3

i am working on frames of a video and i want to subtract one frame from other to find out the difference but i dont know how to proceed. i tried converting my bitmap frames into mat and then subtracting them but its not working. i am using opencv 2.4.3 for mat function. can anybody tell me how to do that. if possible explain with code snippets.

i tried something like this

     Bitmap myBitmap1 = BitmapFactory.decodeFile("/mnt/sdcard/Frames/mpgFrames/image001.jpg");  
    Bitmap myBitmap2 = BitmapFactory.decodeFile("/mnt/sdcard/Frames/mpgFrames/image002.jpg");  

    int width = myBitmap1.getWidth();
    int height = myBitmap1.getHeight();

    Mat  imgToProcess1 = new Mat(height, width, CvType.CV_8UC4);
    Mat  imgToProcess2 = new Mat(height, width, CvType.CV_8UC4);
    Mat  imgToProcess = new Mat(height, width, CvType.CV_8UC4);

    Utils.bitmapToMat(myBitmap1, imgToProcess1); 
    Utils.bitmapToMat(myBitmap2, imgToProcess1);        
    imgToProcess = imgToProcess1-imgToProcess2;
AnShU
  • 239
  • 1
  • 4
  • 11
  • Are you running into [this problem](http://stackoverflow.com/questions/9044909/android-bitmapfactory-decodefile-opencv-does-return-invaild-bitmap)? Can you just read the files directly with `imread`? – mrh Feb 27 '13 at 18:45
  • 2
    While I'm here, I should suggest that you may want to use `absdiff`, rather than just subtracting the matrices. – mrh Feb 27 '13 at 21:19
  • thanks mrh.. i tried absdiff() and its working now... +1 for this :) – AnShU Feb 28 '13 at 05:57
  • Great! I'll put an answer in just in case somebody else runs into this problem. – mrh Feb 28 '13 at 14:57

1 Answers1

4

If you just subtract one frame from the other, you are going to end up with an image that only contains the areas where the second frame has higher values than the first frame.

To get differences, you need to use absdiff:

absdiff(imgToProcess1, imgToProcess2, imgToProcess);

This will give you a matrix of the actual differences, but if you want a mask of the areas of difference, you can apply a threshold to the result:

Mat mask(imgToProcess.rows, imgToProcess.cols, CV_8U);
cvtColor(imgToProcess, mask, CV_RGB2GRAY, 1); //your conversion specifier may vary
threshold(mask, mask, 0, 255, CV_THRESH_BINARY);

The minimum threshold value (0 above) can be adjusted. If you are using JPEG images, then you may need to increase it a bit to account for encoding noise.

mrh
  • 151
  • 7
  • Just as a pointer re. noise and masking: filtering with blur() or GaussianBlur() will likely improve your results more than only increasing the threshold. There are also more involved approaches to be found in other questions and current research. – FvD Apr 23 '13 at 05:29