3
$\begingroup$

Given two $n \times m$ images, what's the fastest way to count the number of pixels that are different between the two images?

$\endgroup$
0
3
$\begingroup$

For single channel images like

image1 = Image[ {{0, 50, 100, 150, 255}, {0, 50, 100, 150, 200}}, "Byte"]
image2 = Image[ {{1, 2, 3, 4, 5}, {0, 50, 100, 150, 200}}, "Byte"]

you can get 5 using

Total[Unitize[Subtract @@ (ImageData /@ {image1, image2})], 2]

or

Total[Unitize@ImageData@ImageDifference[image1, image2], 2]

In general, you can use

ClearAll[difCount]
difCount = If[ImageChannels[#] === 1, 
    Total[Unitize @ ImageData @ ImageDifference @ ##, 2], 
    Total[Unitize[Apply[Times, ImageData @ ImageDifference @ ##, {2}]], 2]] &;

difCount[image1, image2]

5

$\endgroup$
3
$\begingroup$

Here is another approach that avoids ImageData:

image1 = Image[RandomInteger[256, {3000, 3000}]];
image2 = Image[RandomInteger[256, {3000, 3000}]];

ImageMeasurements[
    Binarize[
        ImageDifference[image1, image2],
        0
    ],
    "Total"
]
% //Rationalize

8.96489*10^6

8964885

And a timing comparison:

ImageMeasurements[
    Binarize[
        ImageDifference[image1, image2],
        0
    ],
    "Total"
] //Rationalize //AbsoluteTiming

Total[Unitize @ ImageData @ ImageDifference[image1, image2], 2] //AbsoluteTiming

{0.045073, 8964885}

{0.073831, 8964885}

About 40% faster.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.