# Detecting change in previous and current image frame

Hello again,

abs / absdiff function can find difference in two Mat arrays of two images. But is there any way that we can find change in two images and just detect it as object?

I mean say first image is a table with laptop.

and in another image is a table with laptop and coin.

So as, just a way to find out a "major changed portion" co-ordinates ? so that we can rectangle / circle it as detected object/s by comparing two images?

edit retag close merge delete

Sort by » oldest newest most voted

This is were contours may be of use to you.

The comments in the code should be self-explanatory.

Absolute diff Image

Thresholded Diff

Final Image

Mat first = imread("first.png", IMREAD_GRAYSCALE);

// inorder to perform the absdiff, the images need to be of equal size
// NOTE: I believe this is the reason why you have a big blue box on the edges
// as well of the output image. This can be fixed by using two equal images in the first place
resize(second, second, first.size());

Mat diff;
absdiff(first, second, diff);

// after getting the difference, we binarize it
Mat thresh;
threshold(diff, thresh, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);

vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
// extract the contours in the threshold image
findContours(thresh, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE);

// this matrix will be used for drawing purposes
Mat out;
cvtColor(second, out, COLOR_GRAY2BGR);

// For each detected contour, calculate its bounding rectangle and draw it
// You can also filter out some noise should you wish by checking if the contour is big
// or small enough along with other contour properties.
// Ref: https://docs.opencv.org/trunk/dd/d49/tutorial_py_contour_features.html
// Ref: https://docs.opencv.org/trunk/d1/d32/tutorial_py_contour_properties.html
for(vector<Point> cont: contours)
{
Rect box = boundingRect(cont);
rectangle(out, box, Scalar(255, 0, 0));
}

imshow("FIRST", first);
imshow("SECOND", second);
imshow("ABS-DIFF", diff);
imshow("THRESH", thresh);
imshow("OUTPUT", out);

waitKey();
destroyAllWindows();

more

Official site

GitHub

Wiki

Documentation