Question

I am trying to loop through a bitmap and determine if each pixel is lighter or darker than gray using getPixel(). Problem is, I am not sure how to tell whether the value returned by getPixel() is darker or lighter than gray.

Neutral gray is about 0x808080 or R:127, G:127, B:127. How would I need to modify the code below to accurately determine this?

for (var dx:int=0; dx < objectWidth; dx++)
{  
    for (var dy:int=0; dy < objectHeight; dy++)
    {
         if (testBmd.getPixel(dx, dy) > GRAY)
         {
             trace("Lighter than gray!");
         } else {
             trace("Darker than gray!");
         }
    }
}
Was it helpful?

Solution

To extend Adam's answer a bit further, you could generate a luminance value using a function like this...

function luminance(myRGB:int):int {
//returns a luminance value between 0 and 255
var R:int = (myRGB / 65536) % 256;
var G:int = (myRGB / 256) % 256;
var B:int = myRGB % 256;
return ((0.3*R)+(0.59*G)+(0.11*B));
}

Then you can test for your 50% grey threshold like this:

if (luminance(testBmd.getPixel(dx, dy)) > 127)

OTHER TIPS

Luminance is the answer - Math needed and explanation here:

http://www.scantips.com/lumin.html

you know how to continue :)

Edit:

on livedocs (livedocs - BitmapData - getPixel32()), you can see in example, how they get r,g,b, values from getPixel32() return value. Maybe you can use i:]

Also, Richard's answer looks like it already does what you need, although if you combine it with example from above - voilla - you've got yourself an luminance comparison :]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top