3

I have two similar BitmapData and I want to compare them and get what percentage are they similar. (I suppose i should use compare() and threshold() method of BitmapData but don't know how) (or maybe simply use getPixel and compare pixel per pixel but I don't know if it is good for performance)

dede
  • 809
  • 3
  • 11
  • 26
  • When I said "similar" I meant that they are different in few pixels, but it doesn't matter it's important that they are different and I want percentage of their difference.(they are same width and height) – dede Sep 01 '12 at 15:39
  • @dede try taking a look at this answer: http://stackoverflow.com/questions/2544330/comparing-bitmap-data-in-as3-pixel-for-pixel – francis Sep 01 '12 at 17:02
  • Thank you but I can't get much help out of it :( – dede Sep 01 '12 at 17:33
  • 1
    One possible approach is to take the result from `compare()` and pass it through the PNGEncoder. If the images are fairly similar, the compressed diff will be small. If the pixels of the images are different in a systematic way (e.g. one is brighter than the other), the file size will still be small. – cleong Sep 02 '12 at 00:03

1 Answers1

5

Here is a simple approach using compare and getVector, assuming the two bitmap data objects are the same width and height :

var percentDifference:Number = getBitmapDifference(bitmapData1, bitmapData2);

private function getBitmapDifference(bitmapData1:BitmapData, bitmapData2:BitmapData):Number 
{
    var bmpDataDif:BitmapData = bitmapData1.compare(bitmapData2) as BitmapData;
    if(!bmpDataDif)
        return 0;
    var differentPixelCount:int = 0;

    var pixelVector:Vector.<uint> =  bmpDataDif.getVector(bmpDataDif.rect);
    var pixelCount:int = pixelVector.length;

    for (var i:int = 0; i < pixelCount; i++) 
    {
        if (pixelVector[i] != 0)
            differentPixelCount ++;
    }

    return (differentPixelCount / pixelCount)*100;
}
Barış Uşaklı
  • 13,440
  • 7
  • 40
  • 66
  • 1
    Nice example +1. I have one small improvement suggestion: the nested for loops can be avoided using the [getVector()](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#getVector()) method. A single loop should be faster. – George Profenza Sep 01 '12 at 18:37
  • Thanks, changed it to use a vector. – Barış Uşaklı Sep 01 '12 at 18:44