Image Processing
****************

Since an image is basically a matrix, Octave is a very powerful environment for processing and analyzing images.  To illustrate how easy it is to do image processing in Octave, the following example will load an image, smooth it by a 5-by-5 averaging filter, and compute the gradient of the smoothed image.

     I = imread ("myimage.jpg");
     S = conv2 (I, ones (5, 5) / 25, "same");
     [Dx, Dy] = gradient (S);

In this example S contains the smoothed image, and Dx and Dy contains the partial spatial derivatives of the image.

Loading and Saving Images
=========================

The first step in most image processing tasks is to load an image into Octave which is done with the imread function. The imwrite function is the corresponding function for writing images to the disk.

In summary, most image processing code will follow the structure of this code

     I = imread ("my_input_image.img");
     J = process_my_image (I);
     imwrite (J, "my_output_image.img");

 -- [IMG, MAP, ALPHA] =: imread (FILENAME)
 -- [...] =: imread (URL)
 -- [...] =: imread (..., EXT)
 -- [...] =: imread (..., IDX)
 -- [...] =: imread (..., PARAM1, VALUE1, ...)
     Read images from various file formats.

     Read an image as a matrix from the file FILENAME or from the online resource URL.  If neither is given, but EXT was specified, look for a file with the extension EXT.

     The size and class of the output depends on the format of the image.  A color image is returned as an MxNx3 matrix.  Grayscale and black-and-white images are of size MxN.  Multipage images will have an additional 4th dimension.

     The bit depth of the image determines the class of the output: "uint8", "uint16", or "single" for grayscale and color, and "logical" for black-and-white.  Note that indexed images always return the indexes for a colormap, independent of whether MAP is a requested output.  To obtain the actual RGB image, use ind2rgb. When more than one indexed image is being read, MAP is obtained from the first.  In some rare cases this may be incorrect and imfinfo can be used to obtain the colormap of each image.

     See the Octave manual for more information in representing images. (see Representing Images)

     Some file formats, such as TIFF and GIF, are able to store multiple images in a single file.  IDX can be a scalar or vector specifying the index of the images to read.  By default, Octave will read only the first page.

     Depending on the file format, it is possible to configure the reading of images with PARAMETER, VALUE pairs.  The following options are supported:

     "Frames" or "Index"
          This is an alternative method to specify IDX.  When specifying it in this way, its value can also be the string "all".

     "Info"
          This option exists for MATLAB compatibility, but has no effect.  For maximum performance when reading multiple images from a single file, use the "Index" option.

     "PixelRegion"
          Controls the image region that is read.  The value must be a cell array with two arrays of 3 elements {[ROWS], [COLS]}.  The elements in the array are the start, increment, and end pixel to be read. If the increment value is omitted it defaults to 1.  For example, the following are all equivalent:

               imread (filename, "PixelRegion", {[200 600], [300 700]});
               imread (filename, "PixelRegion", {[200 1 600], [300 1 700]});
               imread (filename)(200:600, 300:700);

     imwrite, imfinfo, imformats

 -- imwrite: (IMG, FILENAME)
 -- imwrite: (IMG, FILENAME, EXT)
 -- imwrite: (IMG, MAP, FILENAME)
 -- imwrite: (..., PARAM1, VAL1, ...)
     Write images in various file formats.

     The image IMG can be a binary, grayscale, RGB, or multi-dimensional image.  The size and class of IMG should be the same as what should be expected when reading it with imread: the 3rd and 4th dimensions reserved for color space, and multiple pages respectively.  If it's an indexed image, the colormap MAP must also be specified.

     If EXT is not supplied, the file extension of FILENAME is used to determine the format.  The actual supported formats are dependent on options made during the build of Octave.  Use imformats to check the support of the different image formats.

     Depending on the file format, it is possible to configure the writing of images with PARAM, VAL pairs.  The following options are supported:

     Alpha
          Alpha (transparency) channel for the image.  This must be a matrix with same class, and number of rows and columns of IMG.  In case of a multipage image, the size of the 4th dimension must also match and the third dimension must be a singleton.  By default, image will be completely opaque.

     Compression
          Compression to use one the image.  Can be one of the following: "none" (default), "bzip", "fax3", "fax4", "jpeg", "lzw", "rle", or "deflate". Note that not all compression types are available for all image formats in which it defaults to your Magick library.

     DelayTime
          For formats that accept animations (such as GIF), controls for how long a frame is displayed until it moves to the next one.  The value must be scalar (which will applied to all frames in IMG), or a vector of length equal to the number of frames in IM.  The value is in seconds, must be between 0 and 655.35, and defaults to 0.5.

     DisposalMethod
          For formats that accept animations (such as GIF), controls what happens to a frame before drawing the next one.  Its value can be one of the following strings: "doNotSpecify" (default); "leaveInPlace"; "restoreBG"; and "restorePrevious", or a cell array of those string with length equal to the number of frames in IMG.

     LoopCount
          For formats that accept animations (such as GIF), controls how many times the sequence is repeated.  A value of Inf means an infinite loop (default), a value of 0 or 1 that the sequence is played only once (loops zero times), while a value of 2 or above loops that number of times (looping twice means it plays the complete sequence 3 times).  This option is ignored when there is only a single image at the end of writing the file.

     Quality
          Set the quality of the compression.  The value should be an integer between 0 and 100, with larger values indicating higher visual quality and lower compression.  Defaults to 75.

     WriteMode
          Some file formats, such as TIFF and GIF, are able to store multiple images in a single file.  This option specifies if IMG should be appended to the file (if it exists) or if a new file should be created for it (possibly overwriting an existing file).  The value should be the string "Overwrite" (default), or "Append".

          Despite this option, the most efficient method of writing a multipage image is to pass a 4 dimensional IMG to imwrite, the same matrix that could be expected when using imread with the option "Index" set to "all".

     imread, imfinfo, imformats

 -- VAL =: IMAGE_PATH ()
 -- OLD_VAL =: IMAGE_PATH (NEW_VAL)
 -- OLD_VAL =: IMAGE_PATH (NEW_VAL, "local")
     Query or set the internal variable that specifies a colon separated list of directories in which to search for image files.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

     EXEC_PATH, OCTAVE_HOME, OCTAVE_EXEC_HOME

It is possible to get information about an image file on disk, without actually reading it into Octave.  This is done using the imfinfo function which provides read access to many of the parameters stored in the header of the image file.

 -- INFO =: imfinfo (FILENAME)
 -- INFO =: imfinfo (URL)
 -- INFO =: imfinfo (..., EXT)
     Read image information from a file.

     imfinfo returns a structure containing information about the image stored in the file FILENAME.  If there is no file FILENAME, and EXT was specified, it will look for a file named FILENAME and extension EXT, i.e., a file named FILENAME.EXT.

     The output structure INFO contains the following fields:

     Filename
          The full name of the image file.

     FileModDate
          Date of last modification to the file.

     FileSize
          Number of bytes of the image on disk

     Format
          Image format (e.g., "jpeg").

     Height
          Image height in pixels.

     Width
          Image Width in pixels.

     BitDepth
          Number of bits per channel per pixel.

     ColorType
          Image type.  Value is "grayscale", "indexed", "truecolor", "CMYK", or "undefined".

     XResolution
          X resolution of the image.

     YResolution
          Y resolution of the image.

     ResolutionUnit
          Units of image resolution.  Value is "Inch", "Centimeter", or "undefined".

     DelayTime
          Time in 1/100ths of a second (0 to 65535) which must expire before displaying the next image in an animated sequence.

     LoopCount
          Number of iterations to loop an animation.

     ByteOrder
          Endian option for formats that support it.  Value is "little-endian", "big-endian", or "undefined".

     Gamma
          Gamma level of the image.  The same color image displayed on two different workstations may look different due to differences in the display monitor.

     Quality
          JPEG/MIFF/PNG compression level.  Value is an integer in the range [0 100].

     DisposalMethod
          Only valid for GIF images, control how successive frames are rendered (how the preceding frame is disposed of) when creating a GIF animation.  Values can be "doNotSpecify", "leaveInPlace", "restoreBG", or "restorePrevious".  For non-GIF files, value is an empty string.

     Chromaticities
          Value is a 1x8 Matrix with the x,y chromaticity values for white, red, green, and blue points, in that order.

     Comment
          Image comment.

     Compression
          Compression type.  Value can be "none", "bzip", "fax3", "fax4", "jpeg", "lzw", "rle", "deflate", "lzma", "jpeg2000", "jbig2", "jbig2", or "undefined".

     Colormap
          Colormap for each image.

     Orientation
          The orientation of the image with respect to the rows and columns.  Value is an integer between 1 and 8 as defined in the TIFF 6 specifications, and for MATLAB compatibility.

     Software
          Name and version of the software or firmware of the camera or image input device used to generate the image.

     Make
          The manufacturer of the recording equipment.  This is the manufacture of the DSC, scanner, video digitizer or other equipment that generated the image.

     Model
          The model name or model number of the recording equipment as mentioned on the field "Make".

     DateTime
          The date and time of image creation as defined by the Exif standard, i.e., it is the date and time the file was changed.

     ImageDescription
          The title of the image as defined by the Exif standard.

     Artist
          Name of the camera owner, photographer or image creator.

     Copyright
          Copyright notice of the person or organization claiming rights to the image.

     DigitalCamera
          A struct with information retrieved from the Exif tag.

     GPSInfo
          A struct with geotagging information retrieved from the Exif tag.

     imread, imwrite, imshow, imformats

By default, Octave's image IO functions (imread, imwrite, and imfinfo) use the GraphicsMagick library for their operations.  This means a vast number of image formats is supported but considering the large amount of image formats in science and its commonly closed nature, it is impossible to have a library capable of reading them all.  Because of this, the function imformats keeps a configurable list of available formats, their extensions, and what functions should the image IO functions use.  This allows one to expand Octave's image IO capabilities by creating functions aimed at acting on specific file formats.

While it would be possible to call the extra functions directly, properly configuring Octave with imformats allows one to keep a consistent code that is abstracted from file formats.

It is important to note that a file format is not actually defined by its file extension and that GraphicsMagick is capable to read and write more file formats than the ones listed by imformats.  What this means is that even with an incorrect or missing extension the image may still be read correctly, and that even unlisted formats are not necessarily unsupported.

 -- imformats: ()
 -- FORMATS =: imformats (EXT)
 -- FORMATS =: imformats (FORMAT)
 -- FORMATS =: imformats ("add", FORMAT)
 -- FORMATS =: imformats ("remove", EXT)
 -- FORMATS =: imformats ("update", EXT, FORMAT)
 -- FORMATS =: imformats ("factory")
     Manage supported image formats.

     FORMATS is a structure with information about each supported file format, or from a specific format EXT, the value displayed on the field EXT.  It contains the following fields:

     ext
          The name of the file format.  This may match the file extension but Octave will automatically detect the file format.

     description
          A long description of the file format.

     isa
          A function handle to confirm if a file is of the specified format.

     write
          A function handle to write if a file is of the specified format.

     read
          A function handle to open files the specified format.

     info
          A function handle to obtain image information of the specified format.

     alpha
          Logical value if format supports alpha channel (transparency or matte).

     multipage
          Logical value if format supports multipage (multiple images per file).

     It is possible to change the way Octave manages file formats with the options "add", "remove", and "update", and supplying a structure FORMAT with the required fields.  The option "factory" resets the configuration to the default.

     This can be used by Octave packages to extend the image reading capabilities Octave, through use of the PKG_ADD and PKG_DEL commands.

     imfinfo, imread, imwrite

Displaying Images
=================

A natural part of image processing is visualization of an image. The most basic function for this is the imshow function that shows the image given in the first input argument.

 -- imshow: (IM)
 -- imshow: (IM, LIMITS)
 -- imshow: (IM, MAP)
 -- imshow: (RGB, ...)
 -- imshow: (FILENAME)
 -- imshow: (..., STRING_PARAM1, VALUE1, ...)
 -- H =: imshow (...)
     Display the image IM, where IM can be a 2-dimensional (grayscale image) or a 3-dimensional (RGB image) matrix.

     If LIMITS is a 2-element vector [LOW, HIGH], the image is shown using a display range between LOW and HIGH.  If an empty matrix is passed for LIMITS, the display range is computed as the range between the minimal and the maximal value in the image.

     If MAP is a valid color map, the image will be shown as an indexed image using the supplied color map.

     If a filename is given instead of an image, the file will be read and shown.

     If given, the parameter STRING_PARAM1 has value VALUE1. STRING_PARAM1 can be any of the following:

     "displayrange"
          VALUE1 is the display range as described above.

     "colormap"
          VALUE1 is the colormap to use when displaying an indexed image.

     "xdata"
          If VALUE1 is a 2-element vector, it must contain horizontal image limits in the form [xfirst, xlast], where xfirst and xlast are the abscissa of the centers of the corner pixels.  Otherwise VALUE1 must be a vector and only the first and last elements will be used for xfirst and xlast respectively.

     "ydata"
          If VALUE1 is a 2-element vector, it must contain vertical image limits in the form [yfirst, ylast], where yfirst and ylast are the ordinates of the center of the corner pixels.  Otherwise VALUE1 must be a vector and only the first and last elements will be used for yfirst and ylast respectively.

     The optional return value H is a graphics handle to the image. image, imagesc, colormap, gray2ind, rgb2ind

 -- image: (IMG)
 -- image: (X, Y, IMG)
 -- image: (..., "PROP", VAL, ...)
 -- image: ("PROP1", VAL1, ...)
 -- H =: image (...)
     Display a matrix as an indexed color image.

     The elements of IMG are indices into the current colormap.

     X and Y are optional 2-element vectors, [min, max], which specify the coordinates of the centers of the corner pixels. If a range is specified as [max, min] then the image will be reversed along that axis.  For convenience, X and Y may be specified as N-element vectors matching the length of the data in IMG. However, only the first and last elements will be used to determine the axis limits.

     Multiple property/value pairs may be specified for the image object, but they must appear in pairs.

     The optional return value H is a graphics handle to the image.

     Implementation Note: The origin (0, 0) for images is located in the upper left.  For ordinary plots, the origin is located in the lower left.  Octave handles this inversion by plotting the data normally, and then reversing the direction of the y-axis by setting the ydir property to "reverse".  This has implications whenever an image and an ordinary plot need to be overlaid.  The recommended solution is to display the image and then plot the reversed ydata using, for example, flipud (ydata).

     Calling Forms: The image function can be called in two forms: High-Level and Low-Level.  When invoked with normal options, the High-Level form is used which first calls newplot to prepare the graphic figure and axes.  When the only inputs to image are property/value pairs the Low-Level form is used which creates a new instance of an image object and inserts it in the current axes.

     Graphic Properties: The full list of properties is documented at Image Properties. imshow, imagesc, colormap

 -- imagesc: (IMG)
 -- imagesc: (X, Y, IMG)
 -- imagesc: (..., CLIMITS)
 -- imagesc: (..., "PROP", VAL, ...)
 -- imagesc: ("PROP1", VAL1, ...)
 -- imagesc: (HAX, ...)
 -- H =: imagesc (...)
     Display a scaled version of the matrix IMG as a color image.

     The colormap is scaled so that the entries of the matrix occupy the entire colormap.  If CLIMITS = [LO, HI] is given, then that range is set to the "clim" of the current axes.

     X and Y are optional 2-element vectors, [min, max], which specify the coordinates of the centers of the corner pixels. If a range is specified as [max, min] then the image will be reversed along that axis.  For convenience, X and Y may be specified as N-element vectors matching the length of the data in IMG. However, only the first and last elements will be used to determine the image limits.

     The optional return value H is a graphics handle to the image.

     Calling Forms: The imagesc function can be called in two forms: High-Level and Low-Level.  When invoked with normal options, the High-Level form is used which first calls newplot to prepare the graphic figure and axes.  When the only inputs to image are property/value pairs the Low-Level form is used which creates a new instance of an image object and inserts it in the current axes.  The full list of properties is documented at Image Properties.

     image, imshow, caxis

Representing Images
===================

In general Octave supports four different kinds of images, grayscale images, RGB images, binary images, and indexed images.  A grayscale image is represented with an M-by-N matrix in which each element corresponds to the intensity of a pixel.  An RGB image is represented with an M-by-N-by-3 array where each 3-vector corresponds to the red, green, and blue intensities of each pixel.

The actual meaning of the value of a pixel in a grayscale or RGB image depends on the class of the matrix.  If the matrix is of class double pixel intensities are between 0 and 1, if it is of class uint8 intensities are between 0 and 255, and if it is of class uint16 intensities are between 0 and 65535.

A binary image is an M-by-N matrix of class logical. A pixel in a binary image is black if it is false and white if it is true.

An indexed image consists of an M-by-N matrix of integers and a C-by-3 color map.  Each integer corresponds to an index in the color map, and each row in the color map corresponds to an RGB color.  The color map must be of class double with values between 0 and 1.

The following convenience functions are available for conversion between image formats.

 -- DIMG =: im2double (IMG)
 -- DIMG =: im2double (IMG, "indexed")
     Convert image to double precision.

     The conversion of IMG to double precision, is dependent on the type of input image.  The following input classes are supported:

     uint8, uint16, and int16
          The range of values from the class is scaled to the interval [0 1].

     logical
          True and false values are assigned a value of 1 and 0 respectively.

     single
          Values are cast to double.

     double
          Returns the same image.

     If IMG is an indexed image, then the second argument should be the string "indexed".  If so, then IMG must either be of floating point class, or unsigned integer class and it will simply be cast to double. If it is an integer class, an offset of +1 is applied.

     double

 -- IMG =: gray2ind (I)
 -- IMG =: gray2ind (I, N)
 -- IMG =: gray2ind (BW)
 -- IMG =: gray2ind (BW, N)
 -- [IMG, MAP] =: gray2ind (...)
     Convert a grayscale or binary intensity image to an indexed image.

     The indexed image will consist of N different intensity values. If not given N defaults to 64 for grayscale images or 2 for binary black and white images.

     The output IMG is of class uint8 if N is less than or equal to 256; Otherwise the return class is uint16. ind2gray, rgb2ind

 -- I =: ind2gray (X, MAP)
     Convert a color indexed image to a grayscale intensity image.

     The image X must be an indexed image which will be converted using the colormap MAP.  If MAP does not contain enough colors for the image, pixels in X outside the range are mapped to the last color in the map before conversion to grayscale.

     The output I is of the same class as the input X and may be one of uint8, uint16, single, or double.

     Implementation Note: There are several ways of converting colors to grayscale intensities.  This functions uses the luminance value obtained from rgb2gray which is I = 0.299*R + 0.587*G + 0.114*B. Other possibilities include the value component from rgb2hsv or using a single color channel from ind2rgb. gray2ind, ind2rgb

 -- [X, MAP] =: rgb2ind (RGB)
 -- [X, MAP] =: rgb2ind (R, G, B)
     Convert an image in red-green-blue (RGB) color space to an indexed image.

     The input image RGB can be specified as a single matrix of size MxNx3, or as three separate variables, R, G, and B, its three color channels, red, green, and blue.

     It outputs an indexed image X and a colormap MAP to interpret an image exactly the same as the input.  No dithering or other form of color quantization is performed.  The output class of the indexed image X can be uint8, uint16 or double, whichever is required to specify the number of unique colors in the image (which will be equal to the number of rows in MAP) in order.

     Multi-dimensional indexed images (of size MxNx3xK) are also supported, both via a single input (RGB) or its three color channels as separate variables.

     ind2rgb, rgb2hsv, rgb2gray

 -- RGB =: ind2rgb (X, MAP)
 -- [R, G, B] =: ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.

     The image X must be an indexed image which will be converted using the colormap MAP.  If MAP does not contain enough colors for the image, pixels in X outside the range are mapped to the last color in the map.

     The output may be a single RGB image (MxNx3 matrix where M and N are the original image X dimensions, one for each of the red, green and blue channels).  Alternatively, the individual red, green, and blue color matrices of size MxN may be returned.

     Multi-dimensional indexed images (of size MxNx1xK) are also supported.

     rgb2ind, ind2gray, hsv2rgb

Octave also provides tools to produce and work with movie frame structures. Those structures encapsulate the image data ("cdata" field) together with the corresponding colormap ("colormap" field).

 -- FRAME =: getframe ()
 -- FRAME =: getframe (HAX)
 -- FRAME =: getframe (HFIG)
 -- FRAME =: getframe (..., RECT)

     Capture a figure or axes as a movie frame structure.

     Without an argument, capture the current axes excluding ticklabels, title, and x/y/zlabels.  The returned structure FRAME has a field cdata, which contains the actual image data in the form of an NxMx3 (RGB) uint8 matrix in physical screen pixels, and a field colormap which is provided for MATLAB compatibility but is always empty.

     If the first argument HAX is an axes handle, then capture this axes, rather than the current axes returned by gca.

     If the first argument HFIG is a figure handle then the entire corresponding figure canvas is captured.

     Finally, if a second argument RECT is provided it must be a four-element vector ([left bottom width height]) defining the region inside the figure to be captured.  Regardless of the figure "units" property, RECT must be defined in pixels.

     im2frame, frame2im, movie

 -- movie: (MOV)
 -- movie: (MOV, N)
 -- movie: (MOV, N, FPS)
 -- movie: (H, ...)
     Play a movie defined by an array of frame structures.

     The movie MOV must be a struct array of frames with fields "cdata" and "colormap", as returned by the getframe function.  By default all images are displayed once, at 12 fps, in the current axes.

     The optional argument N is a scalar or vector of integers that controls the number of times the movie is displayed and which particular frames are shown:

     First element:

          N(1) > 0
               Play the movie N(1) times.

          N(1) < 0
               Play the movie abs (N(1) times alternatively in forward and backward order.

     Other elements (if any):
          Indices of the frames in MOV that will be displayed.

     If the first argument is a handle to a figure or axes H, the movie is played in that figure or axes instead of the current axes.

     getframe, im2frame, frame2im

 -- [X, MAP] =: frame2im (FRAME)
     Convert movie frame to indexed image.

     A movie frame is simply a struct with the fields "cdata" and "colormap".

     Support for N-dimensional images or movies is given when FRAME is a struct array.  In such cases, X will be a MxNx1xK or MxNx3xK for indexed and RGB movies respectively, with each frame concatenated along the 4th dimension.

     im2frame, getframe

 -- FRAME =: im2frame (RGB)
 -- FRAME =: im2frame (X, MAP)
     Convert image to movie frame.

     A movie frame is simply a struct with the fields "cdata" and "colormap".

     Support for N-dimensional images is given when each image projection, matrix sizes of MxN and MxNx3 for RGB images, is concatenated along the fourth dimension.  In such cases, the returned value is a struct array.

     frame2im

The colormap function is used to change the colormap of the current axes or figure.

 -- CMAP =: colormap ()
 -- CMAP =: colormap (MAP)
 -- CMAP =: colormap ("default")
 -- CMAP =: colormap (MAP_NAME)
 -- CMAP =: colormap (HAX, ...)
 -- colormap: MAP_NAME
     Query or set the current colormap.

     With no input arguments, colormap returns the current color map.

     colormap (MAP) sets the current colormap to MAP.  The colormap should be an N row by 3 column matrix.  The columns contain red, green, and blue intensities respectively.  All entries must be between 0 and 1 inclusive.  The new colormap is returned.

     colormap ("default") restores the default colormap (the viridis map with 64 entries).  The default colormap is returned.

     The map may also be specified by a string, MAP_NAME, which is the name of a function that returns a colormap.

     If the first argument HAX is an axes handle, then the colormap for those axes is queried or set.

     For convenience, it is also possible to use this function with the command form, colormap MAP_NAME.

     The list of built-in colormaps is:

     Map   Description
     viridis   default
     turbo   colormap traversing blue, cyan, green, yellow, red; modern replacement for jet.
     jet   colormap traversing blue, cyan, green, yellow, red.
     cubehelix   colormap traversing black, blue, green, red, white with increasing intensity.
     hsv   cyclic colormap traversing Hue, Saturation, Value space.
     rainbow   colormap traversing red, yellow, blue, green, violet.
     -------------   ---------------------------------------------------------------------------------------------
     hot   colormap traversing black, red, orange, yellow, white.
     cool   colormap traversing cyan, purple, magenta.
     spring   colormap traversing magenta to yellow.
     summer   colormap traversing green to yellow.
     autumn   colormap traversing red, orange, yellow.
     winter   colormap traversing blue to green.
     -------------   ---------------------------------------------------------------------------------------------
     gray   colormap traversing black to white in shades of gray.
     bone   colormap traversing black, gray-blue, white.
     copper   colormap traversing black to light copper.
     pink   colormap traversing black, gray-pink, white.
     ocean   colormap traversing black, dark-blue, white.
     -------------   ---------------------------------------------------------------------------------------------
     colorcube   equally spaced colors in RGB color space.
     flag   cyclic 4-color map of red, white, blue, black.
     lines   cyclic colormap with colors from axes "ColorOrder" property.
     prism   cyclic 6-color map of red, orange, yellow, green, blue, violet.
     -------------   ---------------------------------------------------------------------------------------------
     white   all white colormap (no colors).

     viridis, turbo, jet, cubehelix, hsv, rainbow, hot, cool, spring, summer, autumn, winter, gray, bone, copper, pink, ocean, colorcube, flag, lines, prism, white

 -- TF =: iscolormap (CMAP)
     Return true if CMAP is a colormap.

     A colormap is a real matrix, of class single or double, with 3 columns. Each row represents a single color.  The 3 columns contain red, green, and blue intensities respectively.

     All values in a colormap should be in the [0 1] range but this is not enforced.  Each function must decide what to do for values outside this range.

     colormap, rgbplot

The following functions return predefined colormaps, the same that can be requested by name using the colormap function.

 -- rgbplot: (CMAP)
 -- rgbplot: (CMAP, STYLE)
 -- H =: rgbplot (...)
     Plot the components of a colormap.

     Two different STYLEs are available for displaying the CMAP:

     profile (default)
          Plot the RGB line profile of the colormap for each of the channels (red, green and blue) with the plot lines colored appropriately.  Each line represents the intensity of an RGB component across the colormap.

     composite
          Draw the colormap across the X-axis so that the actual index colors are visible rather than the individual color components.

     The optional return value H is a graphics handle to the created plot.

     Run demo rgbplot to see an example of rgbplot and each style option. colormap

 -- MAP =: autumn ()
 -- MAP =: autumn (N)
     Create color colormap. This colormap ranges from red through orange to yellow.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: bone ()
 -- MAP =: bone (N)
     Create color colormap.  This colormap varies from black to white with gray-blue shades.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: colorcube ()
 -- MAP =: colorcube (N)
     Create color colormap.  This colormap is composed of as many equally spaced colors (not grays) in the RGB color space as possible.

     If there are not a perfect number N of regularly spaced colors then the remaining entries in the colormap are gradients of pure red, green, blue, and gray.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: cool ()
 -- MAP =: cool (N)
     Create color colormap.  The colormap varies from cyan to magenta.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: copper ()
 -- MAP =: copper (N)
     Create color colormap.  This colormap varies from black to a light copper tone.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: cubehelix ()
 -- MAP =: cubehelix (N)
 -- MAP =: cubehelix (N, START, ROTS, HUE, GAMMA)
     Create cubehelix colormap.

     This colormap varies from black to white going though blue, green, and red tones while maintaining a monotonically increasing perception of intensity. This is achieved by traversing a color cube from black to white through a helix, hence the name cubehelix, while taking into account the perceived brightness of each channel according to the NTSC specifications from 1953.

          rgbplot (cubehelix (256))

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used.

     Reference: Green, D. A., 2011, A colour scheme for the display of astronomical intensity images, Bulletin of the Astronomical Society of India, 39, 289.

     colormap

 -- MAP =: flag ()
 -- MAP =: flag (N)
     Create color colormap.  This colormap cycles through red, white, blue, and black with each index change.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: gray ()
 -- MAP =: gray (N)
     Create gray colormap.  This colormap varies from black to white with shades of gray.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: hot ()
 -- MAP =: hot (N)
     Create color colormap.  This colormap ranges from black through dark red, red, orange, yellow, to white.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: hsv ()
 -- MAP =: hsv (N)
     Create color colormap.  This colormap begins with red, changes through yellow, green, cyan, blue, and magenta, before returning to red.

     It is useful for displaying periodic functions.  The map is obtained by linearly varying the hue through all possible values while keeping constant maximum saturation and value.  The equivalent code is hsv2rgb ([(0:N-1)'/N, ones(N,2)]).

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: jet ()
 -- MAP =: jet (N)
     Create color colormap.  This colormap ranges from dark blue through blue, cyan, green, yellow, red, to dark red.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used.

     Programming Note: The jet colormap is not perceptually uniform. Try the viridis colormap if that is important.  For a drop-in replacement for jet with better perceptual characteristics try the turbo colormap. colormap, turbo

 -- MAP =: lines ()
 -- MAP =: lines (N)
     Create color colormap.  This colormap is composed of the list of colors in the current axes "ColorOrder" property.  The default is blue, orange, yellow, purple, green, light blue, and dark red.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: ocean ()
 -- MAP =: ocean (N)
     Create color colormap.  This colormap varies from black to white with shades of blue.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: pink ()
 -- MAP =: pink (N)
     Create color colormap.  This colormap varies from black to white with shades of gray-pink.

     This colormap gives a sepia tone when used on grayscale images.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: prism ()
 -- MAP =: prism (N)
     Create color colormap.  This colormap cycles through red, orange, yellow, green, blue and violet with each index change.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: rainbow ()
 -- MAP =: rainbow (N)
     Create color colormap.  This colormap ranges from red through orange, yellow, green, blue, to violet.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: spring ()
 -- MAP =: spring (N)
     Create color colormap.  This colormap varies from magenta to yellow.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: summer ()
 -- MAP =: summer (N)
     Create color colormap.  This colormap varies from green to yellow.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: turbo ()
 -- MAP =: turbo (N)
     Create color colormap.  This colormap ranges from dark blue through green to dark red; similar to the outdated jet colormap but perceptually uniform.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: viridis ()
 -- MAP =: viridis (N)
     Create color colormap.  This colormap ranges from dark purplish-blue through blue, green, to yellow.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: white ()
 -- MAP =: white (N)
     Create color colormap.  This colormap is completely white.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- MAP =: winter ()
 -- MAP =: winter (N)
     Create color colormap.  This colormap varies from blue to green.

     The argument N must be a scalar. If unspecified, the length of the current colormap, or 64, is used. colormap

 -- CMAP =: contrast (X)
 -- CMAP =: contrast (X, N)
     Return a gray colormap that maximizes the contrast in an image.

     The returned colormap will have N rows.  If N is not defined then the size of the current colormap is used. colormap, brighten

The following three functions modify the existing colormap rather than replace it.

 -- MAP_OUT =: brighten (BETA)
 -- MAP_OUT =: brighten (MAP, BETA)
 -- MAP_OUT =: brighten (H, BETA)
 -- brighten: (...)
     Brighten or darken a colormap.

     The argument BETA must be a scalar between -1 and 1, where a negative value darkens and a positive value brightens the colormap.

     If the MAP argument is omitted, the function is applied to the current colormap.

     The first argument can also be a valid graphics handle H, in which case brighten is applied to the colormap associated with this handle.

     If no output is specified then the result is written to the current colormap. colormap, contrast

 -- spinmap: ()
 -- spinmap: (T)
 -- spinmap: (T, INC)
 -- spinmap: ("inf")
     Cycle the colormap for T seconds with a color increment of INC.

     Both parameters are optional.  The default cycle time is 5 seconds and the default increment is 2.  If the option "inf" is given then cycle continuously until Control-C is pressed.

     When rotating, the original color 1 becomes color 2, color 2 becomes color 3, etc.  A positive or negative increment is allowed and a higher value of INC will cause faster cycling through the colormap. colormap

 -- whitebg: ()
 -- whitebg: (COLOR)
 -- whitebg: ("none")
 -- whitebg: (HFIG)
 -- whitebg: (HFIG, COLOR)
 -- whitebg: (HFIG, "none")
     Invert the colors in the current color scheme.

     The root properties are also inverted such that all subsequent plots will use the new color scheme.

     If the optional argument COLOR is present then the background color is set to COLOR rather than inverted.  COLOR may be a string representing one of the eight known colors or an RGB triplet.  The special string argument "none" restores the plot to the factory default colors.

     If the first argument HFIG is a figure handle or list of figure handles, then operate on these figures rather than the current figure returned by gcf.  The root properties will not be changed unless 0 is in the list of figures.

     Programming Note: whitebg operates by changing the color properties of the children of the specified figures.  Only objects with a single color are affected.  For example, a patch with a single "FaceColor" will be changed, but a patch with shading ("interp") will not be modified.  For inversion, the new color is simply the inversion in RGB space: CNEW = [1-R 1-G 1-B].  When a color is specified, the axes and figure are set to the new color, and the color of child objects are then adjusted to have some contrast (visibility) against the new background. reset, get, set

The following functions can be used to manipulate colormaps.

 -- [Y, NEWMAP] =: cmunique (X, MAP)
 -- [Y, NEWMAP] =: cmunique (RGB)
 -- [Y, NEWMAP] =: cmunique (I)
     Convert an input image X to an output indexed image Y which uses the smallest colormap possible NEWMAP.

     When the input is an indexed image (X with colormap MAP) the output is a colormap NEWMAP from which any repeated rows have been eliminated.  The output image, Y, is the original input image with the indices adjusted to match the new, possibly smaller, colormap.

     When the input is an RGB image (an MxNx3 array), the output colormap will contain one entry for every unique color in the original image.  In the worst case the new map could have as many rows as the number of pixels in the original image.

     When the input is a grayscale image I, the output colormap will contain one entry for every unique intensity value in the original image. In the worst case the new map could have as many rows as the number of pixels in the original image.

     Implementation Details:

     NEWMAP is always an Mx3 matrix, even if the input image is an intensity grayscale image I (all three RGB planes are assigned the same value).

     The output image is of class uint8 if the size of the new colormap is less than or equal to 256.  Otherwise, the output image is of class double.

     rgb2ind, gray2ind

 -- [Y, NEWMAP] =: cmpermute (X, MAP)
 -- [Y, NEWMAP] =: cmpermute (X, MAP, INDEX)
     Reorder colors in a colormap.

     When called with only two arguments, cmpermute randomly rearranges the colormap MAP and returns a new colormap NEWMAP.  It also returns the indexed image Y which is the equivalent of the original input image X when displayed using NEWMAP.

     When called with an optional third argument the order of colors in the new colormap is defined by INDEX.

     Caution: INDEX should not have repeated elements or the function will fail.

Plotting on top of Images
=========================

If gnuplot is being used to display images it is possible to plot on top of images.  Since an image is a matrix it is indexed by row and column values.  The plotting system is, however, based on the traditional (x, y) system.  To minimize the difference between the two systems Octave places the origin of the coordinate system in the point corresponding to the pixel at (1, 1).  So, to plot points given by row and column values on top of an image, one should simply call plot with the column values as the first argument and the row values as the second.  As an example the following code generates an image with random intensities between 0 and 1, and shows the image with red circles over pixels with an intensity above 0.99.

     I = rand (100, 100);
     [row, col] = find (I > 0.99);
     hold ("on");
     imshow (I);
     plot (col, row, "ro");
     hold ("off");

Color Conversion
================

Octave supports conversion from the RGB color system to the HSV color system and vice versa.  It is also possible to convert from a color RGB image to a grayscale image.

 -- HSV_MAP =: rgb2hsv (RGB_MAP)
 -- HSV_IMG =: rgb2hsv (RGB_IMG)
     Transform a colormap or image from RGB to HSV color space.

     A color in the RGB space consists of red, green, and blue intensities.

     A color in HSV space is represented by hue, saturation and value (brightness) levels in a cylindrical coordinate system.  Hue is the azimuth and describes the dominant color.  Saturation is the radial distance and gives the amount of hue mixed into the color.  Value is the height and is the amount of light in the color.

     Output class and size will be the same as input.

     hsv2rgb, rgb2ind, rgb2gray

 -- RGB_MAP =: hsv2rgb (HSV_MAP)
 -- RGB_IMG =: hsv2rgb (HSV_IMG)
     Transform a colormap or image from HSV to RGB color space.

     A color in HSV space is represented by hue, saturation and value (brightness) levels in a cylindrical coordinate system.  Hue is the azimuth and describes the dominant color.  Saturation is the radial distance and gives the amount of hue mixed into the color.  Value is the height and is the amount of light in the color.

     The input can be both a colormap or RGB image.  In the case of floating point input, values are expected to be on the [0 1] range.  In the case of hue (azimuth), since the value corresponds to an angle, mod (h, 1) is used.

          >> hsv2rgb ([0.5 1 1])
          => ans = 0 1 1

          >> hsv2rgb ([2.5 1 1])
          => ans = 0 1 1

          >> hsv2rgb ([3.5 1 1])
          => ans = 0 1 1

     Output class and size will be the same as input.

     rgb2hsv, ind2rgb

 -- I =: rgb2gray (RGB_IMG)
 -- GRAY_MAP =: rgb2gray (RGB_MAP)
     Transform an image or colormap from red-green-blue (RGB) color space to a grayscale intensity image.

     The input may be of class uint8, int8, uint16, int16, single, or double. The output is of the same class as the input.

     Implementation Note: The grayscale intensity is calculated as

          I = 0.298936*R + 0.587043*G + 0.114021*B

     which corresponds to the luminance channel when RGB is translated to YIQ as documented in https://en.wikipedia.org/wiki/YIQ. rgb2hsv, rgb2ind