OCR: Difference between two frames

那年仲夏 提交于 2019-12-01 17:45:06

After loading your images:

img1

img2

you can apply XOR operation to get the differences. The result has the same number of channels of the input images:

XOR

You can then create a binary mask OR-ing all channels:

mask

The you can copy the values of img2 that correspond to non-zero elements in the mask to a white image:

diff


UPDATE

If you have multiple areas where pixel changed, like this:

You'll find a difference mask (after binarization all non-zero pixels are set to 255) like:

You can then extract connected components and draw each connected component on a new black-initialized mask:

Then, as before, you can copy the values of img2 that correspond to non-zero elements in each mask to a white image.

The complete code for reference. Note that this is the code for the updated version of the answer. You can find the original code in the revision history.

#include <opencv2\opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;

int main()
{
    // Load the images
    Mat img1 = imread("path_to_img1");
    Mat img2 = imread("path_to_img2");

    imshow("Img1", img1);
    imshow("Img2", img2);

    // Apply XOR operation, results in a N = img1.channels() image
    Mat maskNch = (img1 ^ img2);

    imshow("XOR", maskNch);

    // Create a binary mask

    // Split each channel
    vector<Mat1b> masks;
    split(maskNch, masks);

    // Create a black mask
    Mat1b mask(maskNch.rows, maskNch.cols, uchar(0));

    // OR with each channel of the N channels mask
    for (int i = 0; i < masks.size(); ++i)
    {
        mask |= masks[i];
    }

    // Binarize mask
    mask = mask > 0;

    imshow("Mask", mask);

    // Find connected components
    vector<vector<Point>> contours;
    findContours(mask.clone(), contours, RETR_LIST, CHAIN_APPROX_SIMPLE);

    for (int i = 0; i < contours.size(); ++i)
    {
        // Create a black mask
        Mat1b mask_i(mask.rows, mask.cols, uchar(0));
        // Draw the i-th connected component
        drawContours(mask_i, contours, i, Scalar(255), CV_FILLED);

        // Create a black image
        Mat diff_i(img2.rows, img2.cols, img2.type());
        diff_i.setTo(255);

        // Copy into diff only different pixels
        img2.copyTo(diff_i, mask_i);

        imshow("Mask " + to_string(i), mask_i);
        imshow("Diff " + to_string(i), diff_i);
    }

    waitKey();
    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!