Many image processing algorithms are defined for grayscale (or else monochromatic) images.



Task

Extend the data storage type defined on this page to support grayscale images.

Define two operations, one to convert a color image to a grayscale image and one for the backward conversion.

To get luminance of a color use the formula recommended by CIE:

 L  =  0.2126 × R   +   0.7152 × G   +   0.0722 × B 

When using floating-point arithmetic make sure that rounding errors would not cause run-time problems or else distorted results when calculated luminance is stored as an unsigned integer.




function ConvertToGrayscaleImage( bitmap )
    local size_x, size_y = #bitmap, #bitmap[1]
    local gray_im = {}
 
    for i = 1, size_x do
        gray_im[i] = {}
        for j = 1, size_y do 
            gray_im[i][j] = math.floor( 0.2126*bitmap[i][j][1] + 0.7152*bitmap[i][j][2] + 0.0722*bitmap[i][j][3] )
        end
    end
 
    return gray_im
end
 
function ConvertToColorImage( gray_im )
    local size_x, size_y = #gray_im, #gray_im[1]    
    local bitmap = Allocate_Bitmap( size_x, size_y )         -- this function is defined at http://rosettacode.org/wiki/Basic_bitmap_storage#Lua
 
    for i = 1, size_x do
        for j = 1, size_y do 
            bitmap[i][j] = { gray_im[i][j], gray_im[i][j], gray_im[i][j] }
        end
    end
 
    return bitmap
end