Grayscale image

From Rosetta Code
Task
Grayscale image
You are encouraged to solve this task according to the task description, using any language you may know.

Many image processing algorithms are defined for grayscale (or else monochromatic) images. 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.

Ada

<ada> type Grayscale_Image is array (Positive range <>, Positive range <>) of Luminance; </ada> Conversion to a grayscale image: <ada> function Grayscale (Picture : Image) return Grayscale_Image is

  type Extended_Luminance is range 0..10_000_000;
  Result : Grayscale_Image (Picture'Range (1), Picture'Range (2));
  Color  : Pixel;

begin

  for I in Picture'Range (1) loop
     for J in Picture'Range (2) loop
        Color := Picture (I, J);
        Result (I, J) :=
           Luminance
           (  Extended_Luminance'Min
              (  Extended_Luminance (Luminance'Last),
                 (  (  2_126 * Extended_Luminance (Color.R)
                    +  7_152 * Extended_Luminance (Color.G)
                    +    722 * Extended_Luminance (Color.B)
                    )
                 /  10_000
           )  )  );
     end loop;
  end loop;
  return Result;

end Grayscale; </ada> Conversion to a color image: <ada> function Color (Picture : Grayscale_Image) return Image is

  Result : Image (Picture'Range (1), Picture'Range (2));

begin

  for I in Picture'Range (1) loop
     for J in Picture'Range (2) loop
        Result (I, J) := (others => Picture (I, J));
     end loop;
  end loop;
  return Result;

end Color; </ada>