changeset 16990:54b75bed4bc7

imwrite: implement WriteMode option. * imwrite.m: document the new option WriteMode and possibility to write multipage images by passing a 4 dimensional matrix. * private/core_imwrite.m: perform input check for the quality option and the new writemode. Set defaults here and not on __magick_write__(). Give warning about the fact that writing of indexed images is not properly implemented. Change calling to ind2rgb() since it has been there and we no longer need workaround. Remove the different calls to __magick_read__() since we now have a single way to do it. Remove conversion of image types since we want to save what was actually given to us. * __magick_read__.cc (read_file): split from __magick_read__() into a separate function so it can be used by __magick_write__() when appending images to an existing file. (jpg_settings): remove function. It only checks for the quality option, which is now done by core_imwrite(). Plus, other formats support this option so it was moved into __magick_write__(). We should have functions for each option rather than per file format. (encode_map): comment whole function since it is never used and is unfinished work to implement writing of actual indexed images. (write_file): new function from part of previous write_image(). It is now the other side of read_file(). (write_image): remove function. Moved into __magick_write__(), the only function calling it. The part of writing moved into write_file(). (__magick_write__): removed most of input check which should be done by imwrite(). Removed all extra usage types. Options must be passed on a non-optional struct. Implement the Append option.
author Carnë Draug <carandraug@octave.org>
date Tue, 16 Jul 2013 17:29:45 +0100
parents aabe12e5fdc1
children 7a69ab84b8c9
files libinterp/dldfcn/__magick_read__.cc scripts/image/imwrite.m scripts/image/private/core_imwrite.m
diffstat 3 files changed, 259 insertions(+), 249 deletions(-) [+]
line wrap: on
line diff
--- a/libinterp/dldfcn/__magick_read__.cc
+++ b/libinterp/dldfcn/__magick_read__.cc
@@ -361,6 +361,32 @@
   return retval;
 }
 
+void static
+read_file (const std::string filename, std::vector<Magick::Image>& imvec)
+{
+  try
+    {
+      // Read a file into vector of image objects
+      Magick::readImages (&imvec, filename);
+    }
+  catch (Magick::Warning& w)
+    {
+      warning ("Magick++ warning: %s", w.what ());
+    }
+  catch (Magick::ErrorCoder& e)
+    {
+      // FIXME: there's a WarningCoder and ErrorCoder. Shouldn't this
+      // exception cause an error?
+      warning ("Magick++ coder error: %s", e.what ());
+    }
+  catch (Magick::Exception& e)
+    {
+      error ("Magick++ exception: %s", e.what ());
+      error_state = 1;
+    }
+}
+
+
 static void
 maybe_initialize_magick (void)
 {
@@ -368,11 +394,12 @@
 
   if (! initialized)
     {
-      // Save locale as GraphicsMagick might change this (depending on version)
+      // Save locale as GraphicsMagick might change this (fixed in
+      // GraphicsMagick since version 1.3.13 released on December 24, 2011)
       const char *static_locale = setlocale (LC_ALL, NULL);
       const std::string locale (static_locale);
 
-      std::string program_name = octave_env::get_program_invocation_name ();
+      const std::string program_name = octave_env::get_program_invocation_name ();
 
       Magick::InitializeMagick (program_name.c_str ());
 
@@ -413,38 +440,23 @@
       return output;
     }
 
-  octave_map options = args(1).map_value ();
+  const octave_map options = args(1).map_value ();
   if (error_state)
     {
       error ("__magick_read__: OPTIONS must be a struct");
     }
 
   std::vector<Magick::Image> imvec;
-  try
-    {
-      // Read a file into vector of image objects
-      Magick::readImages (&imvec, args(0).string_value ());
-    }
-  catch (Magick::Warning& w)
+  read_file (args(0).string_value (), imvec);
+  if (error_state)
     {
-      warning ("Magick++ warning: %s", w.what ());
-    }
-  catch (Magick::ErrorCoder& e)
-    {
-      // FIXME: there's a WarningCoder and ErrorCoder. Shouldn't this
-      // exception cause an error?
-      warning ("Magick++ coder error: %s", e.what ());
-    }
-  catch (Magick::Exception& e)
-    {
-      error ("Magick++ exception: %s", e.what ());
       return output;
     }
 
   const int nframes = imvec.size ();
   Array<int> frameidx;
 
-  octave_value indexes = options.getfield ("index")(0);
+  const octave_value indexes = options.getfield ("index")(0);
   if (indexes.is_string () && indexes.string_value () == "all")
     {
       frameidx = Array<int> (dim_vector (1, nframes));
@@ -462,7 +474,7 @@
         }
       // Fix indexex from base 1 to base 0, and at the same time, make
       // sure none of the indexes is outside the range of image number.
-      int n = frameidx.nelem ();
+      const int n = frameidx.nelem ();
       for (int i = 0; i < n; i++)
         {
           frameidx(i)--;
@@ -474,7 +486,7 @@
         }
     }
 
-  Magick::ClassType klass = imvec[0].classType ();
+  const Magick::ClassType klass = imvec[0].classType ();
 
   // PseudoClass:
   // Image is composed of pixels which specify an index in a color palette.
@@ -531,54 +543,6 @@
 #ifdef HAVE_MAGICK
 
 static void
-jpg_settings (std::vector<Magick::Image>& imvec,
-              const octave_map& options,
-              bool)
-{
-  bool something_set = false;
-
-  // Quality setting
-  octave_value result;
-  octave_map::const_iterator p;
-  bool found_it = false;
-
-  for (p = options.begin (); p != options.end (); p++)
-    {
-      if (options.key (p) == "Quality")
-        {
-          found_it = true;
-          result = options.contents (p).elem (0);
-          break;
-        }
-    }
-
-  if (found_it && (! result.is_empty ()))
-    {
-      something_set = true;
-
-      if (result.is_real_type ())
-        {
-          int qlev = result.int_value ();
-
-          if (qlev < 0 || qlev > 100)
-            warning ("warning: Quality setting invalid--use default of 75");
-          else
-            {
-              for (size_t fnum = 0; fnum < imvec.size (); fnum++)
-                imvec[fnum].quality (static_cast<unsigned int>(qlev));
-            }
-        }
-      else
-        warning ("warning: Quality setting invalid--use default of 75");
-    }
-
-  // Other settings go here
-
-  if (! something_set)
-    warning ("__magick_write__ warning: all write parameters ignored");
-}
-
-static void
 encode_bool_image (std::vector<Magick::Image>& imvec, const octave_value& img)
 {
   unsigned int nframes = 1;
@@ -630,7 +594,7 @@
 static void
 encode_uint_image (std::vector<Magick::Image>& imvec,
                    const octave_value& img,
-                   bool has_map)
+                   const bool has_map)
 {
   unsigned int bitdepth = 0;
   T m;
@@ -648,13 +612,13 @@
   else
     error ("__magick_write__: invalid image class");
 
-  dim_vector dsizes = m.dims ();
+  const dim_vector dsizes = m.dims ();
   unsigned int nframes = 1;
   if (dsizes.length () == 4)
     nframes = dsizes(3);
 
-  bool is_color = ((dsizes.length () > 2) && (dsizes(2) > 2));
-  bool has_alpha = (dsizes.length () > 2 && (dsizes(2) == 2 || dsizes(2) == 4));
+  const bool is_color = ((dsizes.length () > 2) && (dsizes(2) > 2));
+  const bool has_alpha = (dsizes.length () > 2 && (dsizes(2) == 2 || dsizes(2) == 4));
 
   Array<octave_idx_type> idx (dim_vector (dsizes.length (), 1));
   octave_idx_type rows = m.rows ();
@@ -757,92 +721,54 @@
     }
 }
 
-static void
-encode_map (std::vector<Magick::Image>& imvec, const NDArray& cmap)
-{
-  unsigned int mapsize = cmap.dim1 ();
-
-  for (size_t fnum = 0; fnum < imvec.size (); fnum++)
-    {
-      imvec[fnum].colorMapSize (mapsize);
-      imvec[fnum].type (Magick::PaletteType);
-    }
-
-  for (unsigned int ii = 0; ii < mapsize; ii++)
-    {
-      Magick::ColorRGB c (cmap(ii,0), cmap(ii,1), cmap(ii,2));
-
-      // FIXME -- is this case needed?
-      if (cmap.dim2 () == 4)
-        c.alpha (cmap(ii,3));
+// FIXME: this will be needed to write indexed images
+//static void
+//encode_map (std::vector<Magick::Image>& imvec, const NDArray& cmap)
+//{
+//  unsigned int mapsize = cmap.dim1 ();
 
-      try
-        {
-          for_each (imvec.begin (), imvec.end (),
-                    Magick::colorMapImage (ii, c));
-        }
-      catch (Magick::Warning& w)
-        {
-          warning ("Magick++ warning: %s", w.what ());
-        }
-      catch (Magick::ErrorCoder& e)
-        {
-          warning ("Magick++ coder error: %s", e.what ());
-        }
-      catch (Magick::Exception& e)
-        {
-          error ("Magick++ exception: %s", e.what ());
-        }
-    }
-}
+//  for (size_t fnum = 0; fnum < imvec.size (); fnum++)
+//    {
+//      imvec[fnum].colorMapSize (mapsize);
+//      imvec[fnum].type (Magick::PaletteType);
+//    }
+
+//  for (unsigned int ii = 0; ii < mapsize; ii++)
+//    {
+//      Magick::ColorRGB c (cmap(ii,0), cmap(ii,1), cmap(ii,2));
+
+//      // FIXME -- is this case needed?
+//      if (cmap.dim2 () == 4)
+//        c.alpha (cmap(ii,3));
 
-static void
-write_image (const std::string& filename, const std::string& fmt,
-             const octave_value& img,
-             const octave_value& map = octave_value (),
-             const octave_value& params = octave_value ())
-{
-  std::vector<Magick::Image> imvec;
-
-  bool has_map = map.is_defined ();
-
-  if (has_map)
-    {
-      error ("__magick_write__: direct saving of indexed images not currently supported; use ind2rgb and save converted image");
-      return;
-    }
+//      try
+//        {
+//          for_each (imvec.begin (), imvec.end (),
+//                    Magick::colorMapImage (ii, c));
+//        }
+//      catch (Magick::Warning& w)
+//        {
+//          warning ("Magick++ warning: %s", w.what ());
+//        }
+//      catch (Magick::ErrorCoder& e)
+//        {
+//          warning ("Magick++ coder error: %s", e.what ());
+//        }
+//      catch (Magick::Exception& e)
+//        {
+//          error ("Magick++ exception: %s", e.what ());
+//        }
+//    }
+//}
 
-  if (img.is_bool_type ())
-    encode_bool_image (imvec, img);
-  else if (img.is_uint8_type ())
-    encode_uint_image<uint8NDArray> (imvec, img, has_map);
-  else if (img.is_uint16_type ())
-    encode_uint_image<uint16NDArray> (imvec, img, has_map);
-  else
-    error ("__magick_write__: image type not supported");
-
-  if (! error_state && has_map)
-    {
-      NDArray cmap = map.array_value ();
-
-      if (! error_state)
-        encode_map (imvec, cmap);
-    }
-
-  if (! error_state && params.is_defined ())
-    {
-      octave_map options = params.map_value ();
-
-      // Insert calls here to handle parameters for various image formats
-      if (fmt == "jpg" || fmt == "jpeg")
-        jpg_settings (imvec, options, has_map);
-      else
-        warning ("warning: your parameter(s) currently not supported");
-    }
-
+void static
+write_file (const std::string filename,
+            const std::string ext,
+            std::vector<Magick::Image>& imvec)
+{
   try
     {
-      Magick::writeImages (imvec.begin (), imvec.end (), fmt + ":" + filename);
+      Magick::writeImages (imvec.begin (), imvec.end (), ext + ":" + filename);
     }
   catch (Magick::Warning& w)
     {
@@ -855,6 +781,7 @@
   catch (Magick::Exception& e)
     {
       error ("Magick++ exception: %s", e.what ());
+      error_state = 1;
     }
 }
 
@@ -862,8 +789,7 @@
 
 DEFUN_DLD (__magick_write__, args, ,
   "-*- texinfo -*-\n\
-@deftypefn  {Loadable Function} {} __magick_write__ (@var{fname}, @var{fmt}, @var{img})\n\
-@deftypefnx {Loadable Function} {} __magick_write__ (@var{fname}, @var{fmt}, @var{img}, @var{map})\n\
+@deftypefn {Loadable Function} {} __magick_write__ (@var{fname}, @var{fmt}, @var{img}, @var{map}, @var{options})\n\
 Write image with GraphicsMagick or ImageMagick.\n\
 \n\
 This is a private internal function not intended for direct use.  Instead\n\
@@ -880,36 +806,99 @@
 
   maybe_initialize_magick ();
 
-  int nargin = args.length ();
-
-  if (nargin > 2)
+  if (args.length () != 5 || ! args(0).is_string () || ! args(1).is_string ())
     {
-      std::string filename = args(0).string_value ();
+      print_usage ();
+      return retval;
+    }
+  const std::string filename = args(0).string_value ();
+  const std::string ext      = args(1).string_value ();
 
-      if (! error_state)
-        {
-          std::string fmt = args(1).string_value ();
+  const octave_map options   = args(4).map_value ();
+  if (error_state)
+    {
+      error ("__magick_write__: OPTIONS must be a struct");
+    }
 
-          if (! error_state)
-            {
-              if (nargin > 4)
-                write_image (filename, fmt, args(2), args(3), args(4));
-              else if (nargin > 3)
-                if (args(3).is_real_type ())
-                  write_image (filename, fmt, args(2), args(3));
-                else
-                  write_image (filename, fmt, args(2), octave_value (), args(3));
-              else
-                write_image (filename, fmt, args(2));
-            }
-          else
-            error ("__magick_write__: FMT must be string");
-        }
-      else
-        error ("__magick_write__: FNAME must be a string");
+  const octave_value img  = args(2);
+  const Matrix       cmap = args(3).matrix_value ();
+  if (error_state)
+    {
+      error ("__magick_write__: invalid IMG or MAP");
+    }
+  const bool is_indexed = ! cmap.is_empty ();
+
+  // Create vector with the images to write
+  std::vector<Magick::Image> imvec;
+  if (img.is_bool_type ())
+    {
+      encode_bool_image (imvec, img);
+    }
+  else if (img.is_uint8_type ())
+    {
+      encode_uint_image<uint8NDArray> (imvec, img, is_indexed);
+    }
+  else if (img.is_uint16_type ())
+    {
+      encode_uint_image<uint16NDArray> (imvec, img, is_indexed);
     }
   else
-    print_usage ();
+    {
+      error ("__magick_write__: image type not supported");
+      return retval;
+    }
+  const int nframes = imvec.size ();
+
+  // Add colormap to image
+  if (is_indexed)
+    {
+    // FIXME: this should be implemented. At the moment, imwrite is doing the
+    //        conversion in case of indexed images.
+      error ("__magick_write__: direct saving of indexed images not currently supported; use ind2rgb and save converted image");
+//      encode_map (imvec, cmap);
+      return retval;
+    }
+
+  // Set quality.
+  // FIXME What happens when we try to set with formats that do not support it?
+  const unsigned int quality = options.getfield ("quality")(0).int_value ();
+  for (int i = 0; i < nframes; i++)
+    {
+      imvec[i].quality (quality);
+    }
+
+  // Finally, save the file.
+  // If writemode is set to append, read the image first, append to it,
+  // and then save it. But even if set to append, make sure anything was
+  // read at all.
+  const std::string writemode = options.getfield ("writemode")(0).string_value ();
+  std::vector<Magick::Image> ini_imvec;
+  if (writemode == "append")
+    {
+      read_file (filename, ini_imvec);
+      if (error_state)
+        {
+          return retval;
+        }
+    }
+
+  if (ini_imvec.size () > 0)
+    {
+      ini_imvec.insert (ini_imvec.end (), imvec.begin (), imvec.end ());
+      write_file (filename, ext, ini_imvec);
+      if (error_state)
+        {
+          return retval;
+        }
+    }
+  else
+    {
+      write_file (filename, ext, imvec);
+      if (error_state)
+        {
+          return retval;
+        }
+    }
 
 #endif
   return retval;
--- a/scripts/image/imwrite.m
+++ b/scripts/image/imwrite.m
@@ -20,23 +20,43 @@
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {} imwrite (@var{img}, @var{filename})
 ## @deftypefnx {Function File} {} imwrite (@var{img}, @var{filename}, @var{ext})
-## @deftypefnx {Function File} {} imwrite (@var{img}, @var{filename}, @var{ext}, @var{p1}, @var{v1}, @dots{})
-## @deftypefnx {Function File} {} imwrite (@var{img}, @var{map}, @var{filename}, @dots{})
+## @deftypefnx {Function File} {} imwrite (@var{img}, @var{map}, @var{filename})
+## @deftypefnx {Function File} {} imwrite (@dots{}, @var{param1}, @var{val1}, @dots{})
 ## Write images in various file formats.
 ##
+## The image @var{img} can be a binary, grayscale, RGB, or multidimensional
+## image.  The size and class of @var{img} should be the same as what should
+## be expected when reading it with @code{imread}: the 3rd and 4th dimensions
+## reserved for colorspace, and multiple pages respectively.  If it's an
+## indexed image, the colormap @var{map} must also be specified.
+##
 ## If @var{ext} is not supplied, the file extension of @var{filename} is used
 ## to determine the format.  The actual supported formats are dependent on
 ## options made during the build of Octave.  Use @code{imformats} to check
 ## the support of the different image formats.
 ##
-## The parameter-value pairs (@var{p1}, @var{v1}, @dots{}) are optional.
-## Currently the following options are supported for @t{JPEG} images:
+## Depending on the file format, it is possible to configure the writing
+## of images with @var{param}, @var{val} pairs.  The following options
+## are supported:
 ##
 ## @table @samp
 ## @item 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.
+## quality and lower compression. Defaults to 75.
+##
+## @item WriteMode
+## Some file formats, such as TIFF and GIF, are able to store multiple
+## images in a single file.  This option specifies if @var{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 @var{img} to @code{imwrite}, the
+## same matrix that could be expected when using @code{imread} with the
+## option "Index" set to "all".
+##
 ## @end table
 ##
 ## @seealso{imread, imfinfo, imformats}
--- a/scripts/image/private/core_imwrite.m
+++ b/scripts/image/private/core_imwrite.m
@@ -1,4 +1,5 @@
 ## Copyright (C) 2008-2012 John W. Eaton
+## Copyright (C) 2013 Carnë Draug
 ##
 ## This file is part of Octave.
 ##
@@ -29,76 +30,76 @@
 
   [filename, ext, map, param_list] = imwrite_filename (varargin{:});
 
-  options        = struct ();
-  has_param_list = false;
-  if (! isempty (param_list))
-    has_param_list = true;
-    for ii = 1:2:(length (param_list))
-      options.(param_list{ii}) = param_list{ii + 1};
-    endfor
+  if (rem (numel (param_list), 2) != 0)
+    error ("imwrite: no pair for all arguments (even number left)");
   endif
 
+  ## set default for options
+  options        = struct ("writemode", "overwrite",
+                           "quality",   75);
+
+  for idx = 1:2:numel (param_list)
+
+    switch (tolower (param_list{idx}))
+
+      case "writemode",
+        options.writemode = param_list{idx+1};
+        if (! ischar (options.writemode) ||
+            ! any (strcmpi (options.writemode, {"append", "overwrite"})))
+          error ("imwrite: value for %s option must be \"append\" or \"overwrite\"",
+                 param_list{idx});
+        endif
+        options.writemode = tolower (options.writemode);
+
+      case "quality",
+        options.quality = param_list{idx+1};
+        if (! isnumeric (options.quality) || ! isscalar (options.quality) ||
+            options.quality < 0 || options.quality > 100)
+          error ("imwrite: value for %s option must be a scalar between 0 and 100",
+                 param_list{idx});
+        endif
+        options.quality = round (options.quality);
+
+      otherwise
+        error ("imwrite: invalid PARAMETER `%s'", varargin{idx});
+
+    endswitch
+  endfor
+
   if (isempty (img))
     error ("imwrite: invalid empty image");
-  endif
-
-  if (issparse (img) || issparse (map))
+  elseif (issparse (img) || issparse (map))
     error ("imwrite: sparse images not supported");
   endif
 
-  img_class = class (img);
-  map_class = class (map);
-  nd = ndims (img);
-
-  if (isempty (map))
-    if (any (strcmp (img_class, {"logical", "uint8", "uint16", "double"})))
-      if ((nd == 2 || nd == 3) && strcmp (img_class, "double"))
-        img = uint8 (img * 255);
-      endif
-      ## FIXME: should we handle color images with alpha channel here?
-      if (nd == 3 && size (img, 3) < 3)
-        error ("imwrite: invalid dimensions for truecolor image");
-      endif
-      ## FIXME: why nd>5? Shouldn't it be nd>4? What's the 5th dimension for?
-      if (nd > 5)
-        error ("imwrite: invalid %d-dimensional image data", nd);
-      endif
-    else
-      error ("imwrite: %s: invalid class for truecolor image", img_class);
-    endif
-    if (has_param_list)
-      __magick_write__ (filename, ext, img, options);
-    else
-      __magick_write__ (filename, ext, img);
+  if (! isempty (map))
+    if (! iscolormap (map))
+      error ("imwrite: invalid MAP for indexed image");
+    elseif (ndims (img) != 2 && ndims (img) != 4)
+      error ("imwrite: indexed image must have 2 or 4 dimensions (found %i)", ndims (img));
     endif
-  else
-    if (any (strcmp (img_class, {"uint8", "uint16", "double"})))
-      if (strcmp (img_class, "double"))
-        img = uint8 (img - 1);
-      endif
-      if (nd != 2 && nd != 4)
-        error ("imwrite: invalid size for indexed image");
-      endif
-    else
-      error ("imwrite: %s: invalid class for indexed image data", img_class);
-    endif
-    if (! iscolormap (map))
-      error ("imwrite: invalid indexed image colormap");
+    ## FIXME: we should really be writing indexed images but that needs
+    ##        to be implemented in  __magick_write__(). So we convert
+    ##        them to RGB and write them "normally".
+    warned = false;
+    if (! warned)
+      warning ("imwrite: saving of indexed images is not yet implemented. Will save a RGB image.");
+      warned = true;
     endif
-
-    ## FIXME: we should really be writing indexed images here but
-    ##        __magick_write__ needs to be fixed to handle them.
-
-    [r, g, b] = ind2rgb (img, map);
-    tmp = uint8 (cat (3, r, g, b) * 255);
-
-    if (has_param_list)
-      __magick_write__ (filename, ext, tmp, options);
-      ## __magick_write__ (filename, ext, img, map, options);
-    else
-      __magick_write__ (filename, ext, tmp);
-      ## __magick_write__ (filename, ext, img, map);
-    endif
+    img = ind2rgb (img, map);
+    map = [];
   endif
 
+  if (ndims (img) > 4)
+    error ("imwrite: invalid %d-dimensional image data", ndims (img));
+  elseif (all (size (img, 3) != [1 3]))
+    ## This test needs to be adjusted if one day we implement alternative
+    ## colorspaces. In the mean time, we only have grayscale and RGB images,
+    ## but CMYK means length 4 in the 3rd dimension.
+    error ("imwrite: IMG 3rd dimension must be 1 or 3");
+  endif
+
+  ## FIXME: do we need to convert the image class?
+  __magick_write__ (filename, ext, img, map, options);
+
 endfunction