OpenCV Android absdiff not working

asked 2016-09-28 08:44:57 -0600

marcosbontempo gravatar image

updated 2016-09-28 09:01:40 -0600


I want to create a motion detector in a OpenCV Android app.

First I accumulate the background with this class:

private Mat                    mRgba;
private Mat                    mGray;
private Mat                    mBackground;
private Mat                    mDifference;

public Mat accumulateImageBG(Mat img, int type){
    if (accuImg==null){//code snipit from berak's answer
        accuImg = Mat.zeros(img.size(), type);

    if (mDifference==null){//code snipit from berak's answer
        mDifference = Mat.zeros(img.size(), CvType.CV_8UC1);

    img.convertTo(img, type);
    Imgproc.accumulateWeighted(img, accuImg, 0.1);
    Core.convertScaleAbs(accuImg, img);
    return img;

And then I want to calculate the difference between the background and the camera frame. I tried this code:

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

    mRgba = inputFrame.rgba();//in:CV_8UC4 out:CV_32FC4
    mGray = inputFrame.gray();//in:CV_8UC1 out:CV_32F

    //be sure to specify conversion type with matching # of channels as input image!
    mBackground = accumulateImageBG(mGray, CvType.CV_32F);

    // Subtract the work image frame from the scaled image average
    Core.absdiff(mBackground, mGray, mDifference);

    return mDifference;

But it's always returning a blank frame. I think there is a problem with my absdiff code. Does anybody know if I did something wrong? I already tested with 3.1.0, 3.0.0 and 2.4.11 versions.

Any tip will be very helpful,


edit retag flag offensive close merge delete


what is mGray ? how do you initialize it ?

berak gravatar imageberak ( 2016-09-28 08:57:56 -0600 )edit

@berak Sorry, I copied the wrong code. It's already edited.

marcosbontempo gravatar imagemarcosbontempo ( 2016-09-28 09:01:05 -0600 )edit

Core.convertScaleAbs(accuImg, img); <-- this looks wrong. accuImg has to stay float type , else the conversion will round it to zero any time.

you have to change something in your flow there. i guess, you have to convert mBackground, not accuImg

berak gravatar imageberak ( 2016-09-28 09:10:40 -0600 )edit

@berak Did this function changes accuImg type? I thought it would dump the result to img.

marcosbontempo gravatar imagemarcosbontempo ( 2016-09-28 09:29:04 -0600 )edit

I have exactly the same problem. Although I simply subtract (absdiff) the current image from the previous image. The destination simply seems to be untouched. If set to zeros its remains as zeros. If it contains an image the image remains unchanged. Also using the same version 3.1.0

mikeb gravatar imagemikeb ( 2017-01-18 13:54:00 -0600 )edit