in addition to code_couturier - try this formula to calculate gray-value (luminance) in his "more exact" way:
$gray = round(.299*$red + .587*$green + .114*$blue);
in addition to code_couturier - try this formula to calculate gray-value (luminance) in his "more exact" way:
$gray = round(.299*$red + .587*$green + .114*$blue);