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.




/*REXX program converts a  RGB (red─green─blue) image into a  grayscale/greyscale image.*/
  blue= '00 00 ff'x                              /*define the blue color  (hexadecimal).*/
    @.= blue                                     /*set the entire  image  to blue color.*/
 width=  60                                      /* width of the   image  (in pixels).  */
height= 100                                      /*height  "  "      "      "   "       */
 
  do    col=1  for width
     do row=1  for height                        /* [↓]  C2D  convert  char ───► decimal*/
     r= left(@.col.row, 1)      ;     r= c2d(r)  /*extract the component red  & convert.*/
     g= substr(@.col.row, 2, 1) ;     g= c2d(g)  /*   "     "      "    green "    "    */
     b=  right(@.col.row, 1)    ;     b= c2d(b)  /*   "     "      "    blue  "    "    */
     _= d2c( (.2126*r + .7152*g + .0722*b) % 1)  /*convert RGB number  ───►  grayscale. */
     @.col.row= copies(_, 3)                     /*redefine old RGB    ───►  grayscale. */
     end   /*row*/                               /* [↑]  D2C  convert  decimal ───► char*/
  end      /*col*/                               /* [↑]  x%1   is the same as  TRUNC(x) */
                                                 /*stick a fork in it,  we're all done. */