- Home /
Can't compare 2 Texture2D by pixel's color
I need to calculate the differences of 2 screenshots as Texture2D. I have another camera on the scene to take screenshots. First screenshot is: link text And the second screenshot is:link text As you can see these are different but my method always returns 0 like there's no difference.
private int CompareTextures(Texture2D texture1, Texture2D texture2)
{
int correctPixels = 0;
var tex1 = texture1.GetPixels();
var tex2 = texture2.GetPixels();
if (tex1.Length != tex2.Length)
{
return 0;
}
else
{
for (int i = 0; i < tex1.Length; i++)
{
if (tex1[i] != tex2[i])
{
correctPixels++;
}
}
int percentage = 100 * (correctPixels / tex1.Length);
return percentage;
}
}
I don't understand why is that. Can you guys help me?
Answer by revolute · Aug 26, 2020 at 09:36 AM
int division does not work in magic. If you divide two integers you get another integer.
int percentage = (100 *correctPixels) / tex1.Length;
should give a number other than 0. The main problem was that correctPixels/tex1.Length
was calculated first, since tex1.Length
is always larger than or same to correctPixels
, result would be 0 or at best 1.
You're right. The length of array is larger larger than correctPixels
. I have to cast them float. Thank you!
You also should refactor your code since your correctPixels variable does not count correct pixels but those which are different. So name it changedPixels. Though If you wanted to actually calculate the percentage how much the two images are similar, you should replace your !=
with ==
I know. I did it on purpose. Thank you by the way.