1## Copyright (C) 2000, 2001 Kai Habel <kai.habel@gmx.de>
2## Copyright (C) 2012 Carnë Draug <carandraug+dev@gmail.com>
3##
4## This program is free software; you can redistribute it and/or modify it under
5## the terms of the GNU General Public License as published by the Free Software
6## Foundation; either version 3 of the License, or (at your option) any later
7## version.
8##
9## This program is distributed in the hope that it will be useful, but WITHOUT
10## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12## details.
13##
14## You should have received a copy of the GNU General Public License along with
15## this program; if not, see <http://www.gnu.org/licenses/>.
16
17## -*- texinfo -*-
18## @deftypefn {Function File} @var{gray}= rgb2gray (@var{rgb})
19## Convert RGB image or colormap to grayscale.
20##
21## If @var{rgb} is an RGB image, the conversion to grayscale is weighted based
22## on the luminance values (see @code{rgb2ntsc}).  Supported classes are single,
23## double,  uint8 and uint16.
24##
25## If @var{rgb} is a colormap it is converted into the YIQ space of ntsc.  The
26## luminance value (Y) is taken to create a gray colormap.
27##
28## @seealso{mat2gray, ntsc2rgb, rgb2ind, rgb2ntsc, rgb2ycbcr}
29## @end deftypefn
30
31function gray = rgb2gray (rgb)
32
33  if (nargin != 1)
34    print_usage();
35  endif
36
37  if (iscolormap (rgb))
38    gray = rgb2ntsc (rgb) (:, 1) * ones (1, 3);
39
40  elseif (isimage (rgb) && ndims (rgb) == 3)
41    cls = class (rgb);
42    if (! isfloat (rgb))
43      rgb = im2double (rgb);
44    endif
45
46    ## multiply each color by the luminance factor (this is also matlab compatible)
47    ##      0.29894 * red + 0.58704 * green + 0.11402 * blue
48    gray = rgb .* permute ([0.29894, 0.58704, 0.11402], [1, 3, 2]);
49    gray = sum (gray, 3);
50    gray = imcast (gray, cls);
51  else
52    error ("rgb2gray: the input must either be an RGB image or a colormap");
53  endif
54endfunction
55
56# simplest test, double image, each channel on its own and then all maxed
57%!shared img
58%! img = zeros (2, 2, 3);
59%! img(:,:,1) = [1 0; 0 1];
60%! img(:,:,2) = [0 1; 0 1];
61%! img(:,:,3) = [0 0; 1 1];
62%! img = rgb2gray (img);
63%!assert ([img(1,1) img(1,2) img(2,1) img(2,2)], [0.29894 0.58704 0.11402 1]);
64
65%!assert (class (rgb2gray (single (ones (5, 5, 3)))), "single")
66%!assert (class (rgb2gray (uint8 (ones (5, 5, 3)))), "uint8")
67