A lot of interesting things may be found in sources of LESS, which has some built-in color-calculating functions, listed here (search for 'rgb', that will be the first one).
Going to implementation, take a look for their one-liner for luma
function, which should return luminance of a color.