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.




let to_grayscale ~img:(_, r_channel, g_channel, b_channel) =
  let width = Bigarray.Array2.dim1 r_channel
  and height = Bigarray.Array2.dim2 r_channel in
 
  let gray_channel =
    let kind = Bigarray.int8_unsigned
    and layout = Bigarray.c_layout
    in
    (Bigarray.Array2.create kind layout width height)
  in
  for y = 0 to pred height do
    for x = 0 to pred width do
      let r = r_channel.{x,y}
      and g = g_channel.{x,y}
      and b = b_channel.{x,y} in
      let v = (2_126 * r +  7_152 * g + 722 * b) / 10_000 in
      gray_channel.{x,y} <- v;
    done;
  done;
  (gray_channel)