]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/quantize.c
(no commit message)
[imagemagick] / MagickCore / quantize.c
index ace5dbb55560539a9342fff0815b04251e7f31a3..5cba535ff0c1ff23695d8259fa6d63e9e6d35ec3 100644 (file)
 %    MagickCore Methods to Reduce the Number of Unique Colors in an Image     %
 %                                                                             %
 %                           Software Design                                   %
-%                             John Cristy                                     %
+%                                Cristy                                       %
 %                              July 1992                                      %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization      %
 %  dedicated to making software imaging solutions freely available.           %
 %                                                                             %
 %  You may not use this file except in compliance with the License.  You may  %
@@ -61,9 +61,8 @@
 %
 %  The algorithm maps this domain onto a tree in which each node
 %  represents a cube within that domain.  In the following discussion
-%  these cubes are defined by the coordinate of two opposite vertices:
-%  The vertex nearest the origin in RGB space and the vertex farthest from
-%  the origin.
+%  these cubes are defined by the coordinate of two opposite vertices (vertex
+%  nearest the origin in RGB space and the vertex farthest from the origin).
 %
 %  The tree's root node represents the entire domain, (0,0,0) through
 %  (Cmax,Cmax,Cmax).  Each lower level in the tree is generated by
 #include "MagickCore/color-private.h"
 #include "MagickCore/colormap.h"
 #include "MagickCore/colorspace.h"
+#include "MagickCore/colorspace-private.h"
 #include "MagickCore/enhance.h"
 #include "MagickCore/exception.h"
 #include "MagickCore/exception-private.h"
 #include "MagickCore/monitor-private.h"
 #include "MagickCore/option.h"
 #include "MagickCore/pixel-accessor.h"
+#include "MagickCore/pixel-private.h"
 #include "MagickCore/quantize.h"
 #include "MagickCore/quantum.h"
 #include "MagickCore/quantum-private.h"
+#include "MagickCore/resource_.h"
 #include "MagickCore/string_.h"
 #include "MagickCore/thread-private.h"
 \f
 /*
   Typdef declarations.
 */
-typedef struct _RealPixelPacket
+typedef struct _RealPixelInfo
 {
-  MagickRealType
+  double
     red,
     green,
     blue,
     alpha;
-} RealPixelPacket;
+} RealPixelInfo;
 
 typedef struct _NodeInfo
 {
@@ -233,10 +235,10 @@ typedef struct _NodeInfo
   MagickSizeType
     number_unique;
 
-  RealPixelPacket
+  RealPixelInfo
     total_color;
 
-  MagickRealType
+  double
     quantize_error;
 
   size_t
@@ -269,10 +271,10 @@ typedef struct _CubeInfo
   MagickSizeType
     transparent_pixels;
 
-  RealPixelPacket
+  RealPixelInfo
     target;
 
-  MagickRealType
+  double
     distance,
     pruning_threshold,
     next_threshold;
@@ -288,13 +290,16 @@ typedef struct _CubeInfo
   Nodes
     *node_queue;
 
+  MemoryInfo
+    *memory_info;
+
   ssize_t
     *cache;
 
-  RealPixelPacket
+  RealPixelInfo
     error[ErrorQueueLength];
 
-  MagickRealType
+  double
     weights[ErrorQueueLength];
 
   QuantizeInfo
@@ -327,10 +332,10 @@ static NodeInfo
   *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
 
 static MagickBooleanType
-  AssignImageColors(Image *,CubeInfo *),
+  AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
   ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
-  DitherImage(Image *,CubeInfo *),
-  SetGrayscaleImage(Image *);
+  DitherImage(Image *,CubeInfo *,ExceptionInfo *),
+  SetGrayscaleImage(Image *,ExceptionInfo *);
 
 static size_t
   DefineImageColormap(Image *,CubeInfo *,NodeInfo *);
@@ -378,7 +383,8 @@ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
       const char
         *option;
 
-      quantize_info->dither=image_info->dither;
+      quantize_info->dither_method=image_info->dither == MagickFalse ?
+        NoDitherMethod : RiemersmaDitherMethod;
       option=GetImageOption(image_info,"dither");
       if (option != (const char *) NULL)
         quantize_info->dither_method=(DitherMethod) ParseCommandOption(
@@ -429,75 +435,78 @@ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
 */
 
 static inline void AssociateAlphaPixel(const Image *image,
-  const CubeInfo *cube_info,const Quantum *pixel,
-  RealPixelPacket *alpha_pixel)
+  const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
 {
-  MagickRealType
+  double
     alpha;
 
   if ((cube_info->associate_alpha == MagickFalse) ||
       (GetPixelAlpha(image,pixel)== OpaqueAlpha))
     {
-      alpha_pixel->red=(MagickRealType) GetPixelRed(image,pixel);
-      alpha_pixel->green=(MagickRealType) GetPixelGreen(image,pixel);
-      alpha_pixel->blue=(MagickRealType) GetPixelBlue(image,pixel);
-      alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
+      alpha_pixel->red=(double) GetPixelRed(image,pixel);
+      alpha_pixel->green=(double) GetPixelGreen(image,pixel);
+      alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
+      alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
       return;
     }
-  alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,pixel));
+  alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
   alpha_pixel->red=alpha*GetPixelRed(image,pixel);
   alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
   alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
-  alpha_pixel->alpha=(MagickRealType) GetPixelAlpha(image,pixel);
+  alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
 }
 
-static inline void AssociateAlphaPixelPacket(const Image *image,
-  const CubeInfo *cube_info,const PixelPacket *pixel,
-  RealPixelPacket *alpha_pixel)
+static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
+  const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
 {
-  MagickRealType
+  double
     alpha;
 
   if ((cube_info->associate_alpha == MagickFalse) ||
       (pixel->alpha == OpaqueAlpha))
     {
-      alpha_pixel->red=(MagickRealType) pixel->red;
-      alpha_pixel->green=(MagickRealType) pixel->green;
-      alpha_pixel->blue=(MagickRealType) pixel->blue;
-      alpha_pixel->alpha=(MagickRealType) pixel->alpha;
+      alpha_pixel->red=(double) pixel->red;
+      alpha_pixel->green=(double) pixel->green;
+      alpha_pixel->blue=(double) pixel->blue;
+      alpha_pixel->alpha=(double) pixel->alpha;
       return;
     }
-  alpha=(MagickRealType) (QuantumScale*pixel->alpha);
+  alpha=(double) (QuantumScale*pixel->alpha);
   alpha_pixel->red=alpha*pixel->red;
   alpha_pixel->green=alpha*pixel->green;
   alpha_pixel->blue=alpha*pixel->blue;
-  alpha_pixel->alpha=(MagickRealType) pixel->alpha;
+  alpha_pixel->alpha=(double) pixel->alpha;
 }
 
-static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
+static inline Quantum ClampPixel(const MagickRealType value)
 {
-  if (value <= 0.0)
-    return((Quantum) 0);
-  if (value >= QuantumRange)
+  if (value < 0.0f)
+    return(0);
+  if (value >= (MagickRealType) QuantumRange)
     return((Quantum) QuantumRange);
-  return((Quantum) (value+0.5));
+#if !defined(MAGICKCORE_HDRI_SUPPORT)
+  return((Quantum) (value+0.5f));
+#else
+  return(value);
+#endif
 }
 
 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
-  const RealPixelPacket *pixel,size_t index)
+  const RealPixelInfo *pixel,size_t index)
 {
   size_t
     id;
 
-  id=(size_t) (((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red)) >> index) & 0x01) |
-    ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green)) >> index) & 0x01) << 1 |
-    ((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue)) >> index) & 0x01) << 2);
+  id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
+    ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
+    ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
   if (cube_info->associate_alpha != MagickFalse)
-    id|=((ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->alpha)) >> index) & 0x1) << 3;
+    id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
   return(id);
 }
 
-static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
+static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
+  ExceptionInfo *exception)
 {
 #define AssignImageTag  "Assign/Image"
 
@@ -510,13 +519,11 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
       (cube_info->quantize_info->colorspace != CMYKColorspace))
     (void) TransformImageColorspace((Image *) image,
-      cube_info->quantize_info->colorspace);
+      cube_info->quantize_info->colorspace,exception);
   else
-    if ((image->colorspace != GRAYColorspace) &&
-        (image->colorspace != RGBColorspace) &&
-        (image->colorspace != CMYColorspace))
-      (void) TransformImageColorspace((Image *) image,RGBColorspace);
-  if (AcquireImageColormap(image,cube_info->colors) == MagickFalse)
+    if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
+      (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+  if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
   image->colors=0;
@@ -526,25 +533,22 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
   /*
     Create a reduced color image.
   */
-  if ((cube_info->quantize_info->dither != MagickFalse) &&
+  if ((cube_info->quantize_info->dither_method != NoDitherMethod) &&
       (cube_info->quantize_info->dither_method != NoDitherMethod))
-    (void) DitherImage(image,cube_info);
+    (void) DitherImage(image,cube_info,exception);
   else
     {
       CacheView
         *image_view;
 
-      ExceptionInfo
-        *exception;
-
       MagickBooleanType
         status;
 
       status=MagickTrue;
-      exception=(&image->exception);
-      image_view=AcquireCacheView(image);
+      image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-      #pragma omp parallel for schedule(dynamic,4) shared(status)
+      #pragma omp parallel for schedule(static,4) shared(status) \
+        magick_threads(image,image,image->rows,1)
 #endif
       for (y=0; y < (ssize_t) image->rows; y++)
       {
@@ -564,7 +568,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
           continue;
         q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
           exception);
-        if (q == (const Quantum *) NULL)
+        if (q == (Quantum *) NULL)
           {
             status=MagickFalse;
             continue;
@@ -572,7 +576,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
         cube=(*cube_info);
         for (x=0; x < (ssize_t) image->columns; x+=count)
         {
-          RealPixelPacket
+          RealPixelInfo
             pixel;
 
           register const NodeInfo
@@ -590,10 +594,10 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
           */
           for (count=1; (x+count) < (ssize_t) image->columns; count++)
           {
-            PixelPacket
+            PixelInfo
               packet;
 
-            GetPixelPacket(image,q+count*GetPixelChannels(image),&packet);
+            GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
             if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
               break;
           }
@@ -610,7 +614,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
             Find closest color among siblings and their children.
           */
           cube.target=pixel;
-          cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*
+          cube.distance=(double) (4.0*(QuantumRange+1.0)*
             (QuantumRange+1.0)+1.0);
           ClosestColor(image,&cube,node_info->parent);
           index=cube.color_number;
@@ -620,11 +624,15 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
               SetPixelIndex(image,(Quantum) index,q);
             if (cube.quantize_info->measure_error == MagickFalse)
               {
-                SetPixelRed(image,image->colormap[index].red,q);
-                SetPixelGreen(image,image->colormap[index].green,q);
-                SetPixelBlue(image,image->colormap[index].blue,q);
+                SetPixelRed(image,ClampToQuantum(
+                  image->colormap[index].red),q);
+                SetPixelGreen(image,ClampToQuantum(
+                  image->colormap[index].green),q);
+                SetPixelBlue(image,ClampToQuantum(
+                  image->colormap[index].blue),q);
                 if (cube.associate_alpha != MagickFalse)
-                  SetPixelAlpha(image,image->colormap[index].alpha,q);
+                  SetPixelAlpha(image,ClampToQuantum(
+                    image->colormap[index].alpha),q);
               }
             q+=GetPixelChannels(image);
           }
@@ -648,14 +656,14 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
       image_view=DestroyCacheView(image_view);
     }
   if (cube_info->quantize_info->measure_error != MagickFalse)
-    (void) GetImageQuantizeError(image);
+    (void) GetImageQuantizeError(image,exception);
   if ((cube_info->quantize_info->number_colors == 2) &&
       (cube_info->quantize_info->colorspace == GRAYColorspace))
     {
-      Quantum
+      double
         intensity;
 
-      register PixelPacket
+      register PixelInfo
         *restrict q;
 
       register ssize_t
@@ -667,18 +675,18 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
       q=image->colormap;
       for (i=0; i < (ssize_t) image->colors; i++)
       {
-        intensity=(Quantum) ((MagickRealType) GetPixelPacketIntensity(q) <
-          ((MagickRealType) QuantumRange/2.0) ? 0 : QuantumRange);
+        intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
+          QuantumRange);
         q->red=intensity;
         q->green=intensity;
         q->blue=intensity;
         q++;
       }
     }
-  (void) SyncImage(image);
+  (void) SyncImage(image,exception);
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
       (cube_info->quantize_info->colorspace != CMYKColorspace))
-    (void) TransformImageColorspace((Image *) image,RGBColorspace);
+    (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
   return(MagickTrue);
 }
 \f
@@ -748,9 +756,8 @@ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
   MagickBooleanType
     associate_alpha;
 
-  associate_alpha=image->matte;
-  if (cube_info->quantize_info->colorspace == TransparentColorspace)
-    associate_alpha=MagickFalse;
+  associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
+    MagickFalse;
   if ((cube_info->quantize_info->number_colors == 2) &&
       (cube_info->quantize_info->colorspace == GRAYColorspace))
     associate_alpha=MagickFalse;
@@ -768,13 +775,13 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   MagickBooleanType
     proceed;
 
-  MagickRealType
+  double
     bisect;
 
   NodeInfo
     *node_info;
 
-  RealPixelPacket
+  RealPixelInfo
     error,
     mid,
     midpoint,
@@ -796,18 +803,16 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
       (cube_info->quantize_info->colorspace != CMYKColorspace))
     (void) TransformImageColorspace((Image *) image,
-      cube_info->quantize_info->colorspace);
+      cube_info->quantize_info->colorspace,exception);
   else
-    if ((image->colorspace != GRAYColorspace) &&
-        (image->colorspace != CMYColorspace) &&
-        (image->colorspace != RGBColorspace))
-      (void) TransformImageColorspace((Image *) image,RGBColorspace);
-  midpoint.red=(MagickRealType) QuantumRange/2.0;
-  midpoint.green=(MagickRealType) QuantumRange/2.0;
-  midpoint.blue=(MagickRealType) QuantumRange/2.0;
-  midpoint.alpha=(MagickRealType) QuantumRange/2.0;
+    if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
+      (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+  midpoint.red=(double) QuantumRange/2.0;
+  midpoint.green=(double) QuantumRange/2.0;
+  midpoint.blue=(double) QuantumRange/2.0;
+  midpoint.alpha=(double) QuantumRange/2.0;
   error.alpha=0.0;
-  image_view=AcquireCacheView(image);
+  image_view=AcquireVirtualCacheView(image,exception);
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register const Quantum
@@ -834,16 +839,16 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       */
       for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
       {
-        PixelPacket
+        PixelInfo
           packet;
 
-        GetPixelPacket(image,p+count*GetPixelChannels(image),&packet);
+        GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
         if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
           break;
       }
       AssociateAlphaPixel(image,cube_info,p,&pixel);
       index=MaxTreeDepth-1;
-      bisect=((MagickRealType) QuantumRange+1.0)/2.0;
+      bisect=((double) QuantumRange+1.0)/2.0;
       mid=midpoint;
       node_info=cube_info->root;
       for (level=1; level <= MaxTreeDepth; level++)
@@ -861,9 +866,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
             */
             node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
             if (node_info->child[id] == (NodeInfo *) NULL)
-              (void) ThrowMagickException(exception,GetMagickModule(),
-                ResourceLimitError,"MemoryAllocationFailed","`%s'",
-                image->filename);
+              {
+                (void) ThrowMagickException(exception,GetMagickModule(),
+                  ResourceLimitError,"MemoryAllocationFailed","`%s'",
+                  image->filename);
+                continue;
+              }
             if (level == MaxTreeDepth)
               cube_info->colors++;
           }
@@ -876,9 +884,9 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
         error.blue=QuantumScale*(pixel.blue-mid.blue);
         if (cube_info->associate_alpha != MagickFalse)
           error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
-        node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
-          count*error.green*error.green+count*error.blue*error.blue+
-          count*error.alpha*error.alpha));
+        node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
+          error.green*error.green+error.blue*error.blue+
+          error.alpha*error.alpha));
         cube_info->root->quantize_error+=node_info->quantize_error;
         index--;
       }
@@ -886,11 +894,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
         Sum RGB for this leaf for later derivation of the mean cube color.
       */
       node_info->number_unique+=count;
-      node_info->total_color.red+=count*QuantumScale*pixel.red;
-      node_info->total_color.green+=count*QuantumScale*pixel.green;
-      node_info->total_color.blue+=count*QuantumScale*pixel.blue;
+      node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
+      node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
+      node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
       if (cube_info->associate_alpha != MagickFalse)
-        node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
+        node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
+          pixel.alpha);
       p+=count*GetPixelChannels(image);
     }
     if (cube_info->colors > cube_info->maximum_colors)
@@ -929,16 +938,16 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       */
       for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
       {
-        PixelPacket
+        PixelInfo
           packet;
 
-        GetPixelPacket(image,p+count*GetPixelChannels(image),&packet);
+        GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
         if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
           break;
       }
       AssociateAlphaPixel(image,cube_info,p,&pixel);
       index=MaxTreeDepth-1;
-      bisect=((MagickRealType) QuantumRange+1.0)/2.0;
+      bisect=((double) QuantumRange+1.0)/2.0;
       mid=midpoint;
       node_info=cube_info->root;
       for (level=1; level <= cube_info->depth; level++)
@@ -956,9 +965,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
             */
             node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
             if (node_info->child[id] == (NodeInfo *) NULL)
-              (void) ThrowMagickException(exception,GetMagickModule(),
-                ResourceLimitError,"MemoryAllocationFailed","%s",
-                image->filename);
+              {
+                (void) ThrowMagickException(exception,GetMagickModule(),
+                  ResourceLimitError,"MemoryAllocationFailed","%s",
+                  image->filename);
+                continue;
+              }
             if (level == cube_info->depth)
               cube_info->colors++;
           }
@@ -971,9 +983,9 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
         error.blue=QuantumScale*(pixel.blue-mid.blue);
         if (cube_info->associate_alpha != MagickFalse)
           error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
-        node_info->quantize_error+=sqrt((double) (count*error.red*error.red+
-          count*error.green*error.green+count*error.blue*error.blue+
-          count*error.alpha*error.alpha));
+        node_info->quantize_error+=count*sqrt((double) (error.red*error.red+
+          error.green*error.green+error.blue*error.blue+
+          error.alpha*error.alpha));
         cube_info->root->quantize_error+=node_info->quantize_error;
         index--;
       }
@@ -981,11 +993,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
         Sum RGB for this leaf for later derivation of the mean cube color.
       */
       node_info->number_unique+=count;
-      node_info->total_color.red+=count*QuantumScale*pixel.red;
-      node_info->total_color.green+=count*QuantumScale*pixel.green;
-      node_info->total_color.blue+=count*QuantumScale*pixel.blue;
+      node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
+      node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
+      node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
       if (cube_info->associate_alpha != MagickFalse)
-        node_info->total_color.alpha+=count*QuantumScale*pixel.alpha;
+        node_info->total_color.alpha+=count*QuantumScale*ClampPixel(
+          pixel.alpha);
       p+=count*GetPixelChannels(image);
     }
     proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
@@ -996,8 +1009,8 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   image_view=DestroyCacheView(image_view);
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
       (cube_info->quantize_info->colorspace != CMYKColorspace))
-    (void) TransformImageColorspace((Image *) image,RGBColorspace);
-  return(MagickTrue);
+    (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+  return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
 }
 \f
 /*
@@ -1039,7 +1052,6 @@ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
     return(clone_info);
   clone_info->number_colors=quantize_info->number_colors;
   clone_info->tree_depth=quantize_info->tree_depth;
-  clone_info->dither=quantize_info->dither;
   clone_info->dither_method=quantize_info->dither_method;
   clone_info->colorspace=quantize_info->colorspace;
   clone_info->measure_error=quantize_info->measure_error;
@@ -1093,18 +1105,18 @@ static void ClosestColor(const Image *image,CubeInfo *cube_info,
       ClosestColor(image,cube_info,node_info->child[i]);
   if (node_info->number_unique != 0)
     {
-      MagickRealType
+      double
         pixel;
 
-      register MagickRealType
+      register double
         alpha,
         beta,
         distance;
 
-      register PixelPacket
+      register PixelInfo
         *restrict p;
 
-      register RealPixelPacket
+      register RealPixelInfo
         *restrict q;
 
       /*
@@ -1116,8 +1128,8 @@ static void ClosestColor(const Image *image,CubeInfo *cube_info,
       beta=1.0;
       if (cube_info->associate_alpha != MagickFalse)
         {
-          alpha=(MagickRealType) (QuantumScale*p->alpha);
-          beta=(MagickRealType) (QuantumScale*q->alpha);
+          alpha=(double) (QuantumScale*p->alpha);
+          beta=(double) (QuantumScale*q->alpha);
         }
       pixel=alpha*p->red-beta*q->red;
       distance=pixel*pixel;
@@ -1160,14 +1172,18 @@ static void ClosestColor(const Image *image,CubeInfo *cube_info,
 %
 %  The format of the CompressImageColormap method is:
 %
-%      MagickBooleanType CompressImageColormap(Image *image)
+%      MagickBooleanType CompressImageColormap(Image *image,
+%        ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
 %    o image: the image.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
-MagickExport MagickBooleanType CompressImageColormap(Image *image)
+MagickExport MagickBooleanType CompressImageColormap(Image *image,
+  ExceptionInfo *exception)
 {
   QuantizeInfo
     quantize_info;
@@ -1176,12 +1192,12 @@ MagickExport MagickBooleanType CompressImageColormap(Image *image)
   assert(image->signature == MagickSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
-  if (IsPaletteImage(image,&image->exception) == MagickFalse)
+  if (IsPaletteImage(image,exception) == MagickFalse)
     return(MagickFalse);
   GetQuantizeInfo(&quantize_info);
   quantize_info.number_colors=image->colors;
   quantize_info.tree_depth=MaxTreeDepth;
-  return(QuantizeImage(&quantize_info,image));
+  return(QuantizeImage(&quantize_info,image,exception));
 }
 \f
 /*
@@ -1233,58 +1249,57 @@ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
       (void) DefineImageColormap(image,cube_info,node_info->child[i]);
   if (node_info->number_unique != 0)
     {
-      register MagickRealType
+      register double
         alpha;
 
-      register PixelPacket
+      register PixelInfo
         *restrict q;
 
       /*
         Colormap entry is defined by the mean color in this cube.
       */
       q=image->colormap+image->colors;
-      alpha=(MagickRealType) ((MagickOffsetType) node_info->number_unique);
-      alpha=1.0/(fabs(alpha) <= MagickEpsilon ? 1.0 : alpha);
+      alpha=(double) ((MagickOffsetType) node_info->number_unique);
+      alpha=PerceptibleReciprocal(alpha);
       if (cube_info->associate_alpha == MagickFalse)
         {
-          q->red=ClampToQuantum((MagickRealType)
-            (alpha*QuantumRange*node_info->total_color.red));
-          q->green=ClampToQuantum((MagickRealType)
-            (alpha*QuantumRange*node_info->total_color.green));
-          q->blue=ClampToQuantum((MagickRealType)
-            (alpha*QuantumRange*node_info->total_color.blue));
-          q->alpha=OpaqueAlpha;
+          q->red=(double) ClampToQuantum(alpha*QuantumRange*
+            node_info->total_color.red);
+          q->green=(double) ClampToQuantum(alpha*QuantumRange*
+            node_info->total_color.green);
+          q->blue=(double) ClampToQuantum(alpha*QuantumRange*
+            node_info->total_color.blue);
+          q->alpha=(double) OpaqueAlpha;
         }
       else
         {
-          MagickRealType
+          double
             opacity;
 
-          opacity=(MagickRealType) (alpha*QuantumRange*
-            node_info->total_color.alpha);
-          q->alpha=ClampToQuantum(opacity);
+          opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
+          q->alpha=(double) ClampToQuantum((opacity));
           if (q->alpha == OpaqueAlpha)
             {
-              q->red=ClampToQuantum((MagickRealType)
-                (alpha*QuantumRange*node_info->total_color.red));
-              q->green=ClampToQuantum((MagickRealType)
-                (alpha*QuantumRange*node_info->total_color.green));
-              q->blue=ClampToQuantum((MagickRealType)
-                (alpha*QuantumRange*node_info->total_color.blue));
+              q->red=(double) ClampToQuantum(alpha*QuantumRange*
+                node_info->total_color.red);
+              q->green=(double) ClampToQuantum(alpha*QuantumRange*
+                node_info->total_color.green);
+              q->blue=(double) ClampToQuantum(alpha*QuantumRange*
+                node_info->total_color.blue);
             }
           else
             {
-              MagickRealType
+              double
                 gamma;
 
-              gamma=(MagickRealType) (QuantumScale*q->alpha);
-              gamma=1.0/(fabs(gamma) <= MagickEpsilon ? 1.0 : gamma);
-              q->red=ClampToQuantum((MagickRealType)
-                (alpha*gamma*QuantumRange*node_info->total_color.red));
-              q->green=ClampToQuantum((MagickRealType)
-                (alpha*gamma*QuantumRange*node_info->total_color.green));
-              q->blue=ClampToQuantum((MagickRealType)
-                (alpha*gamma*QuantumRange*node_info->total_color.blue));
+              gamma=(double) (QuantumScale*q->alpha);
+              gamma=PerceptibleReciprocal(gamma);
+              q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
+                node_info->total_color.red);
+              q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
+                node_info->total_color.green);
+              q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
+                node_info->total_color.blue);
               if (node_info->number_unique > cube_info->transparent_pixels)
                 {
                   cube_info->transparent_pixels=node_info->number_unique;
@@ -1336,8 +1351,8 @@ static void DestroyCubeInfo(CubeInfo *cube_info)
       cube_info->node_queue);
     cube_info->node_queue=nodes;
   } while (cube_info->node_queue != (Nodes *) NULL);
-  if (cube_info->cache != (ssize_t *) NULL)
-    cube_info->cache=(ssize_t *) RelinquishMagickMemory(cube_info->cache);
+  if (cube_info->memory_info != (MemoryInfo *) NULL)
+    cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
   cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
   cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
 }
@@ -1393,7 +1408,8 @@ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
 %
 %  The format of the DitherImage method is:
 %
-%      MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
+%      MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
+%        ExceptionInfo *exception)
 %
 %  A description of each parameter follows.
 %
@@ -1401,24 +1417,26 @@ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
 %
 %    o cube_info: A pointer to the Cube structure.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
 
-static RealPixelPacket **DestroyPixelThreadSet(RealPixelPacket **pixels)
+static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
 {
   register ssize_t
     i;
 
-  assert(pixels != (RealPixelPacket **) NULL);
-  for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
-    if (pixels[i] != (RealPixelPacket *) NULL)
-      pixels[i]=(RealPixelPacket *) RelinquishMagickMemory(pixels[i]);
-  pixels=(RealPixelPacket **) RelinquishMagickMemory(pixels);
+  assert(pixels != (RealPixelInfo **) NULL);
+  for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
+    if (pixels[i] != (RealPixelInfo *) NULL)
+      pixels[i]=(RealPixelInfo *) RelinquishMagickMemory(pixels[i]);
+  pixels=(RealPixelInfo **) RelinquishMagickMemory(pixels);
   return(pixels);
 }
 
-static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
+static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
 {
-  RealPixelPacket
+  RealPixelInfo
     **pixels;
 
   register ssize_t
@@ -1427,24 +1445,23 @@ static RealPixelPacket **AcquirePixelThreadSet(const size_t count)
   size_t
     number_threads;
 
-  number_threads=GetOpenMPMaximumThreads();
-  pixels=(RealPixelPacket **) AcquireQuantumMemory(number_threads,
+  number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
+  pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
     sizeof(*pixels));
-  if (pixels == (RealPixelPacket **) NULL)
-    return((RealPixelPacket **) NULL);
+  if (pixels == (RealPixelInfo **) NULL)
+    return((RealPixelInfo **) NULL);
   (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
   for (i=0; i < (ssize_t) number_threads; i++)
   {
-    pixels[i]=(RealPixelPacket *) AcquireQuantumMemory(count,
-      2*sizeof(**pixels));
-    if (pixels[i] == (RealPixelPacket *) NULL)
+    pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
+    if (pixels[i] == (RealPixelInfo *) NULL)
       return(DestroyPixelThreadSet(pixels));
   }
   return(pixels);
 }
 
 static inline ssize_t CacheOffset(CubeInfo *cube_info,
-  const RealPixelPacket *pixel)
+  const RealPixelInfo *pixel)
 {
 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
@@ -1454,30 +1471,26 @@ static inline ssize_t CacheOffset(CubeInfo *cube_info,
   ssize_t
     offset;
 
-  offset=(ssize_t)
-    (RedShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->red))) |
-    GreenShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->green))) |
-    BlueShift(ScaleQuantumToChar(ClampToUnsignedQuantum(pixel->blue))));
+  offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
+    GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
+    BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
   if (cube_info->associate_alpha != MagickFalse)
-    offset|=AlphaShift(ScaleQuantumToChar(ClampToUnsignedQuantum(
-      pixel->alpha)));
+    offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
   return(offset);
 }
 
-static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
+static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
+  ExceptionInfo *exception)
 {
 #define DitherImageTag  "Dither/Image"
 
   CacheView
     *image_view;
 
-  ExceptionInfo
-    *exception;
-
   MagickBooleanType
     status;
 
-  RealPixelPacket
+  RealPixelInfo
     **pixels;
 
   ssize_t
@@ -1487,11 +1500,10 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
     Distribute quantization error using Floyd-Steinberg.
   */
   pixels=AcquirePixelThreadSet(image->columns);
-  if (pixels == (RealPixelPacket **) NULL)
+  if (pixels == (RealPixelInfo **) NULL)
     return(MagickFalse);
-  exception=(&image->exception);
   status=MagickTrue;
-  image_view=AcquireCacheView(image);
+  image_view=AcquireAuthenticCacheView(image,exception);
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     const int
@@ -1500,7 +1512,7 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
     CubeInfo
       cube;
 
-    RealPixelPacket
+    RealPixelInfo
       *current,
       *previous;
 
@@ -1519,7 +1531,7 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
     if (status == MagickFalse)
       continue;
     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
-    if (q == (const Quantum *) NULL)
+    if (q == (Quantum *) NULL)
       {
         status=MagickFalse;
         continue;
@@ -1531,7 +1543,7 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
     v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      RealPixelPacket
+      RealPixelInfo
         color,
         pixel;
 
@@ -1576,11 +1588,11 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
                 pixel.alpha+=3*previous[u-v].alpha/16;
             }
         }
-      pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
-      pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
-      pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
+      pixel.red=(double) ClampPixel(pixel.red);
+      pixel.green=(double) ClampPixel(pixel.green);
+      pixel.blue=(double) ClampPixel(pixel.blue);
       if (cube.associate_alpha != MagickFalse)
-        pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
+        pixel.alpha=(double) ClampPixel(pixel.alpha);
       i=CacheOffset(&cube,&pixel);
       if (cube.cache[i] < 0)
         {
@@ -1605,8 +1617,8 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
             Find closest color among siblings and their children.
           */
           cube.target=pixel;
-          cube.distance=(MagickRealType) (4.0*(QuantumRange+1.0)*(QuantumRange+
-            1.0)+1.0);
+          cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
+            1.0);
           ClosestColor(image,&cube,node_info->parent);
           cube.cache[i]=(ssize_t) cube.color_number;
         }
@@ -1618,18 +1630,18 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
         SetPixelIndex(image,(Quantum) index,q);
       if (cube.quantize_info->measure_error == MagickFalse)
         {
-          SetPixelRed(image,image->colormap[index].red,q);
-          SetPixelGreen(image,image->colormap[index].green,q);
-          SetPixelBlue(image,image->colormap[index].blue,q);
+          SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
+          SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
+          SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
           if (cube.associate_alpha != MagickFalse)
-            SetPixelAlpha(image,image->colormap[index].alpha,q);
+            SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
         }
       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
         status=MagickFalse;
       /*
         Store the error.
       */
-      AssociateAlphaPixelPacket(image,&cube,image->colormap+index,&color);
+      AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
       current[u].red=pixel.red-color.red;
       current[u].green=pixel.green-color.green;
       current[u].blue=pixel.blue-color.blue;
@@ -1640,9 +1652,6 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
           MagickBooleanType
             proceed;
 
-#if defined(MAGICKCORE_OPENMP_SUPPORT)
-          #pragma omp critical (MagickCore_FloydSteinbergDither)
-#endif
           proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
             image->rows);
           if (proceed == MagickFalse)
@@ -1657,40 +1666,53 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info)
 }
 
 static MagickBooleanType
-  RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int);
+  RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
+    ExceptionInfo *exception);
 
 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
-  const size_t level,const unsigned int direction)
+  const size_t level,const unsigned int direction,ExceptionInfo *exception)
 {
   if (level == 1)
     switch (direction)
     {
       case WestGravity:
       {
-        (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
+        (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
+          exception);
         break;
       }
       case EastGravity:
       {
-        (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
+        (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
+          exception);
         break;
       }
       case NorthGravity:
       {
-        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
+        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
+          exception);
         break;
       }
       case SouthGravity:
       {
-        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
+        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
+          exception);
         break;
       }
       default:
@@ -1701,46 +1723,74 @@ static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
     {
       case WestGravity:
       {
-        Riemersma(image,image_view,cube_info,level-1,NorthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
-        Riemersma(image,image_view,cube_info,level-1,WestGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
-        Riemersma(image,image_view,cube_info,level-1,WestGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
-        Riemersma(image,image_view,cube_info,level-1,SouthGravity);
+        Riemersma(image,image_view,cube_info,level-1,NorthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,WestGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,WestGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,SouthGravity,
+          exception);
         break;
       }
       case EastGravity:
       {
-        Riemersma(image,image_view,cube_info,level-1,SouthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
-        Riemersma(image,image_view,cube_info,level-1,EastGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
-        Riemersma(image,image_view,cube_info,level-1,EastGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
-        Riemersma(image,image_view,cube_info,level-1,NorthGravity);
+        Riemersma(image,image_view,cube_info,level-1,SouthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,EastGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,EastGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,NorthGravity,
+          exception);
         break;
       }
       case NorthGravity:
       {
-        Riemersma(image,image_view,cube_info,level-1,WestGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
-        Riemersma(image,image_view,cube_info,level-1,NorthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,EastGravity);
-        Riemersma(image,image_view,cube_info,level-1,NorthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
-        Riemersma(image,image_view,cube_info,level-1,EastGravity);
+        Riemersma(image,image_view,cube_info,level-1,WestGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,NorthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,EastGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,NorthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,EastGravity,
+          exception);
         break;
       }
       case SouthGravity:
       {
-        Riemersma(image,image_view,cube_info,level-1,EastGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity);
-        Riemersma(image,image_view,cube_info,level-1,SouthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,WestGravity);
-        Riemersma(image,image_view,cube_info,level-1,SouthGravity);
-        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity);
-        Riemersma(image,image_view,cube_info,level-1,WestGravity);
+        Riemersma(image,image_view,cube_info,level-1,EastGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,SouthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,WestGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,SouthGravity,
+          exception);
+        (void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
+          exception);
+        Riemersma(image,image_view,cube_info,level-1,WestGravity,
+          exception);
         break;
       }
       default:
@@ -1749,14 +1799,14 @@ static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
 }
 
 static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
-  CubeInfo *cube_info,const unsigned int direction)
+  CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
 {
 #define DitherImageTag  "Dither/Image"
 
   MagickBooleanType
     proceed;
 
-  RealPixelPacket
+  RealPixelInfo
     color,
     pixel;
 
@@ -1770,9 +1820,6 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
   if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
       (p->y >= 0) && (p->y < (ssize_t) image->rows))
     {
-      ExceptionInfo
-        *exception;
-
       register Quantum
         *restrict q;
 
@@ -1782,9 +1829,8 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
       /*
         Distribute error.
       */
-      exception=(&image->exception);
       q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
-      if (q == (const Quantum *) NULL)
+      if (q == (Quantum *) NULL)
         return(MagickFalse);
       AssociateAlphaPixel(image,cube_info,q,&pixel);
       for (i=0; i < ErrorQueueLength; i++)
@@ -1795,11 +1841,11 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
         if (cube_info->associate_alpha != MagickFalse)
           pixel.alpha+=p->weights[i]*p->error[i].alpha;
       }
-      pixel.red=(MagickRealType) ClampToUnsignedQuantum(pixel.red);
-      pixel.green=(MagickRealType) ClampToUnsignedQuantum(pixel.green);
-      pixel.blue=(MagickRealType) ClampToUnsignedQuantum(pixel.blue);
+      pixel.red=(double) ClampPixel(pixel.red);
+      pixel.green=(double) ClampPixel(pixel.green);
+      pixel.blue=(double) ClampPixel(pixel.blue);
       if (cube_info->associate_alpha != MagickFalse)
-        pixel.alpha=(MagickRealType) ClampToUnsignedQuantum(pixel.alpha);
+        pixel.alpha=(double) ClampPixel(pixel.alpha);
       i=CacheOffset(cube_info,&pixel);
       if (p->cache[i] < 0)
         {
@@ -1820,12 +1866,11 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
               break;
             node_info=node_info->child[id];
           }
-          node_info=node_info->parent;
           /*
             Find closest color among siblings and their children.
           */
           p->target=pixel;
-          p->distance=(MagickRealType) (4.0*(QuantumRange+1.0)*((MagickRealType)
+          p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
             QuantumRange+1.0)+1.0);
           ClosestColor(image,p,node_info->parent);
           p->cache[i]=(ssize_t) p->color_number;
@@ -1838,11 +1883,11 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
         SetPixelIndex(image,(Quantum) index,q);
       if (cube_info->quantize_info->measure_error == MagickFalse)
         {
-          SetPixelRed(image,image->colormap[index].red,q);
-          SetPixelGreen(image,image->colormap[index].green,q);
-          SetPixelBlue(image,image->colormap[index].blue,q);
+          SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
+          SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
+          SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
           if (cube_info->associate_alpha != MagickFalse)
-            SetPixelAlpha(image,image->colormap[index].alpha,q);
+            SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
         }
       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
         return(MagickFalse);
@@ -1851,7 +1896,7 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
       */
       (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
         sizeof(p->error[0]));
-      AssociateAlphaPixelPacket(image,cube_info,image->colormap+index,&color);
+      AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
       p->error[ErrorQueueLength-1].red=pixel.red-color.red;
       p->error[ErrorQueueLength-1].green=pixel.green-color.green;
       p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
@@ -1886,7 +1931,8 @@ static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
   return(y);
 }
 
-static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
+static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
+  ExceptionInfo *exception)
 {
   CacheView
     *image_view;
@@ -1901,7 +1947,7 @@ static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
     depth;
 
   if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
-    return(FloydSteinbergDither(image,cube_info));
+    return(FloydSteinbergDither(image,cube_info,exception));
   /*
     Distribute quantization error along a Hilbert curve.
   */
@@ -1916,10 +1962,10 @@ static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info)
     depth++;
   cube_info->offset=0;
   cube_info->span=(MagickSizeType) image->columns*image->rows;
-  image_view=AcquireCacheView(image);
+  image_view=AcquireAuthenticCacheView(image,exception);
   if (depth > 1)
-    Riemersma(image,image_view,cube_info,depth-1,NorthGravity);
-  status=RiemersmaDither(image,image_view,cube_info,ForgetGravity);
+    Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
+  status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
   image_view=DestroyCacheView(image_view);
   return(status);
 }
@@ -1964,7 +2010,7 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
   CubeInfo
     *cube_info;
 
-  MagickRealType
+  double
     sum,
     weight;
 
@@ -1995,16 +2041,16 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
     return((CubeInfo *) NULL);
   cube_info->root->parent=cube_info->root;
   cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
-  if (cube_info->quantize_info->dither == MagickFalse)
+  if (cube_info->quantize_info->dither_method == NoDitherMethod)
     return(cube_info);
   /*
     Initialize dither resources.
   */
   length=(size_t) (1UL << (4*(8-CacheShift)));
-  cube_info->cache=(ssize_t *) AcquireQuantumMemory(length,
-    sizeof(*cube_info->cache));
-  if (cube_info->cache == (ssize_t *) NULL)
+  cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
+  if (cube_info->memory_info == (MemoryInfo *) NULL)
     return((CubeInfo *) NULL);
+  cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
   /*
     Initialize color cache.
   */
@@ -2016,7 +2062,7 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
   weight=1.0;
   for (i=0; i < ErrorQueueLength; i++)
   {
-    cube_info->weights[ErrorQueueLength-i-1]=1.0/weight;
+    cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
     weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
   }
   /*
@@ -2131,22 +2177,23 @@ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
 %
 %  The format of the GetImageQuantizeError method is:
 %
-%      MagickBooleanType GetImageQuantizeError(Image *image)
+%      MagickBooleanType GetImageQuantizeError(Image *image,
+%        ExceptionInfo *exception)
 %
 %  A description of each parameter follows.
 %
 %    o image: the image.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
-MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
+MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
+  ExceptionInfo *exception)
 {
   CacheView
     *image_view;
 
-  ExceptionInfo
-    *exception;
-
-  MagickRealType
+  double
     alpha,
     area,
     beta,
@@ -2165,7 +2212,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
   assert(image->signature == MagickSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
-  image->total_colors=GetNumberColors(image,(FILE *) NULL,&image->exception);
+  image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
   (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
   if (image->storage_class == DirectClass)
     return(MagickTrue);
@@ -2175,8 +2222,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
   maximum_error=0.0;
   mean_error_per_pixel=0.0;
   mean_error=0.0;
-  exception=(&image->exception);
-  image_view=AcquireCacheView(image);
+  image_view=AcquireVirtualCacheView(image,exception);
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register const Quantum
@@ -2191,10 +2237,10 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image)
     for (x=0; x < (ssize_t) image->columns; x++)
     {
       index=1UL*GetPixelIndex(image,p);
-      if (image->matte != MagickFalse)
+      if (image->alpha_trait == BlendPixelTrait)
         {
-          alpha=(MagickRealType) (QuantumScale*GetPixelAlpha(image,p));
-          beta=(MagickRealType) (QuantumScale*image->colormap[index].alpha);
+          alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
+          beta=(double) (QuantumScale*image->colormap[index].alpha);
         }
       distance=fabs(alpha*GetPixelRed(image,p)-beta*
         image->colormap[index].red);
@@ -2253,7 +2299,6 @@ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
   assert(quantize_info != (QuantizeInfo *) NULL);
   (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
   quantize_info->number_colors=256;
-  quantize_info->dither=MagickTrue;
   quantize_info->dither_method=RiemersmaDitherMethod;
   quantize_info->colorspace=UndefinedColorspace;
   quantize_info->measure_error=MagickFalse;
@@ -2265,7 +2310,7 @@ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
 %                                                                             %
 %                                                                             %
 %                                                                             %
-%     P o s t e r i z e I m a g e C h a n n e l                               %
+%     P o s t e r i z e I m a g e                                             %
 %                                                                             %
 %                                                                             %
 %                                                                             %
@@ -2277,10 +2322,7 @@ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
 %  The format of the PosterizeImage method is:
 %
 %      MagickBooleanType PosterizeImage(Image *image,const size_t levels,
-%        const MagickBooleanType dither)
-%      MagickBooleanType PosterizeImageChannel(Image *image,
-%        const ChannelType channel,const size_t levels,
-%        const MagickBooleanType dither)
+%        const DitherMethod dither_method,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -2289,33 +2331,25 @@ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
 %    o levels: Number of color levels allowed in each channel.  Very low values
 %      (2, 3, or 4) have the most visible effect.
 %
-%    o dither: Set this integer value to something other than zero to dither
-%      the mapped image.
+%    o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
+%      RiemersmaDitherMethod, FloydSteinbergDitherMethod.
+%
+%    o exception: return any errors or warnings in this structure.
 %
 */
 
-static inline ssize_t MagickRound(MagickRealType x)
+static inline double MagickRound(double x)
 {
   /*
     Round the fraction to nearest integer.
   */
-  if (x >= 0.0)
-    return((ssize_t) (x+0.5));
-  return((ssize_t) (x-0.5));
+  if ((x-floor(x)) < (ceil(x)-x))
+    return(floor(x));
+  return(ceil(x));
 }
 
 MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
-  const MagickBooleanType dither)
-{
-  MagickBooleanType
-    status;
-
-  status=PosterizeImageChannel(image,DefaultChannels,levels,dither);
-  return(status);
-}
-
-MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
-  const ChannelType channel,const size_t levels,const MagickBooleanType dither)
+  const DitherMethod dither_method,ExceptionInfo *exception)
 {
 #define PosterizeImageTag  "Posterize/Image"
 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
@@ -2324,9 +2358,6 @@ MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
   CacheView
     *image_view;
 
-  ExceptionInfo
-    *exception;
-
   MagickBooleanType
     status;
 
@@ -2348,31 +2379,36 @@ MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   if (image->storage_class == PseudoClass)
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-    #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
+    #pragma omp parallel for schedule(static,4) shared(progress,status) \
+      magick_threads(image,image,1,1)
 #endif
     for (i=0; i < (ssize_t) image->colors; i++)
     {
       /*
         Posterize colormap.
       */
-      if ((GetPixelRedTraits(image) & ActivePixelTrait) != 0)
-        image->colormap[i].red=PosterizePixel(image->colormap[i].red);
-      if ((GetPixelGreenTraits(image) & ActivePixelTrait) != 0)
-        image->colormap[i].green=PosterizePixel(image->colormap[i].green);
-      if ((GetPixelBlueTraits(image) & ActivePixelTrait) != 0)
-        image->colormap[i].blue=PosterizePixel(image->colormap[i].blue);
-      if ((GetPixelAlphaTraits(image) & ActivePixelTrait) != 0)
-        image->colormap[i].alpha=PosterizePixel(image->colormap[i].alpha);
+      if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
+        image->colormap[i].red=(double)
+          PosterizePixel(image->colormap[i].red);
+      if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
+        image->colormap[i].green=(double)
+          PosterizePixel(image->colormap[i].green);
+      if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
+        image->colormap[i].blue=(double)
+          PosterizePixel(image->colormap[i].blue);
+      if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
+        image->colormap[i].alpha=(double)
+          PosterizePixel(image->colormap[i].alpha);
     }
   /*
     Posterize image.
   */
   status=MagickTrue;
   progress=0;
-  exception=(&image->exception);
-  image_view=AcquireCacheView(image);
+  image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -2385,24 +2421,24 @@ MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
     if (status == MagickFalse)
       continue;
     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
-    if (q == (const Quantum *) NULL)
+    if (q == (Quantum *) NULL)
       {
         status=MagickFalse;
         continue;
       }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      if ((GetPixelRedTraits(image) & ActivePixelTrait) != 0)
+      if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
         SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
-      if ((GetPixelGreenTraits(image) & ActivePixelTrait) != 0)
+      if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
         SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
-      if ((GetPixelBlueTraits(image) & ActivePixelTrait) != 0)
+      if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
         SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
-      if (((GetPixelBlackTraits(image) & ActivePixelTrait) != 0) &&
+      if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
           (image->colorspace == CMYKColorspace))
         SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
-      if (((GetPixelAlphaTraits(image) & ActivePixelTrait) != 0) &&
-          (image->matte == MagickTrue))
+      if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
+          (image->alpha_trait == BlendPixelTrait))
         SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
       q+=GetPixelChannels(image);
     }
@@ -2414,7 +2450,7 @@ MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
           proceed;
 
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-        #pragma omp critical (MagickCore_PosterizeImageChannel)
+        #pragma omp critical (MagickCore_PosterizeImage)
 #endif
         proceed=SetImageProgress(image,PosterizeImageTag,progress++,
           image->rows);
@@ -2426,9 +2462,9 @@ MagickExport MagickBooleanType PosterizeImageChannel(Image *image,
   quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
   quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
     levels,MaxColormapSize+1);
-  quantize_info->dither=dither;
+  quantize_info->dither_method=dither_method;
   quantize_info->tree_depth=MaxTreeDepth;
-  status=QuantizeImage(quantize_info,image);
+  status=QuantizeImage(quantize_info,image,exception);
   quantize_info=DestroyQuantizeInfo(quantize_info);
   return(status);
 }
@@ -2607,7 +2643,7 @@ static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
 %  The format of the QuantizeImage method is:
 %
 %      MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
-%        Image *image)
+%        Image *image,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -2615,9 +2651,74 @@ static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
 %
 %    o image: the image.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
+
+static MagickBooleanType DirectToColormapImage(Image *image,
+  ExceptionInfo *exception)
+{
+  CacheView
+    *image_view;
+
+  MagickBooleanType
+    status;
+
+  register ssize_t
+    i;
+
+  size_t
+    number_colors;
+
+  ssize_t
+    y;
+
+  status=MagickTrue;
+  number_colors=(size_t) (image->columns*image->rows);
+  if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
+    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
+      image->filename);
+  if (image->colors != number_colors)
+    return(MagickFalse);
+  i=0;
+  image_view=AcquireAuthenticCacheView(image,exception);
+  for (y=0; y < (ssize_t) image->rows; y++)
+  {
+    MagickBooleanType
+      proceed;
+
+    register Quantum
+      *restrict q;
+
+    register ssize_t
+      x;
+
+    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
+    if (q == (Quantum *) NULL)
+      break;
+    for (x=0; x < (ssize_t) image->columns; x++)
+    {
+      image->colormap[i].red=(double) GetPixelRed(image,q);
+      image->colormap[i].green=(double) GetPixelGreen(image,q);
+      image->colormap[i].blue=(double) GetPixelBlue(image,q);
+      image->colormap[i].alpha=(double) GetPixelAlpha(image,q);
+      SetPixelIndex(image,(Quantum) i,q);
+      i++;
+      q+=GetPixelChannels(image);
+    }
+    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
+      break;
+    proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
+      image->rows);
+    if (proceed == MagickFalse)
+      status=MagickFalse;
+  }
+  image_view=DestroyCacheView(image_view);
+  return(status);
+}
+
 MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
-  Image *image)
+  Image *image,ExceptionInfo *exception)
 {
   CubeInfo
     *cube_info;
@@ -2640,9 +2741,13 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
     maximum_colors=MaxColormapSize;
   if (maximum_colors > MaxColormapSize)
     maximum_colors=MaxColormapSize;
-  if ((IsImageGray(image,&image->exception) != MagickFalse) &&
-      (image->matte == MagickFalse))
-    (void) SetGrayscaleImage(image);
+  if (image->alpha_trait != BlendPixelTrait)
+    {
+      if ((image->columns*image->rows) <= maximum_colors)
+        (void) DirectToColormapImage(image,exception);
+      if (IsImageGray(image,exception) != MagickFalse)
+        (void) SetGrayscaleImage(image,exception);
+    }
   if ((image->storage_class == PseudoClass) &&
       (image->colors <= maximum_colors))
     return(MagickTrue);
@@ -2658,10 +2763,12 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
       colors=maximum_colors;
       for (depth=1; colors != 0; depth++)
         colors>>=2;
-      if ((quantize_info->dither != MagickFalse) && (depth > 2))
+      if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
         depth--;
-      if ((image->matte != MagickFalse) && (depth > 5))
+      if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
         depth--;
+      if (IsImageGray(image,exception) != MagickFalse)
+        depth=MaxTreeDepth;
     }
   /*
     Initialize color cube.
@@ -2670,14 +2777,14 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
   if (cube_info == (CubeInfo *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
-  status=ClassifyImageColors(cube_info,image,&image->exception);
+  status=ClassifyImageColors(cube_info,image,exception);
   if (status != MagickFalse)
     {
       /*
         Reduce the number of colors in the image.
       */
       ReduceImageColors(image,cube_info);
-      status=AssignImageColors(image,cube_info);
+      status=AssignImageColors(image,cube_info,exception);
     }
   DestroyCubeInfo(cube_info);
   return(status);
@@ -2702,7 +2809,7 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
 %  The format of the QuantizeImages method is:
 %
 %      MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
-%        Image *images)
+%        Image *images,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -2710,9 +2817,11 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
 %
 %    o images: Specifies a pointer to a list of Image structures.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
 MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
-  Image *images)
+  Image *images,ExceptionInfo *exception)
 {
   CubeInfo
     *cube_info;
@@ -2746,7 +2855,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
       /*
         Handle a single image with QuantizeImage.
       */
-      status=QuantizeImage(quantize_info,images);
+      status=QuantizeImage(quantize_info,images,exception);
       return(status);
     }
   status=MagickFalse;
@@ -2767,7 +2876,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
       colors=maximum_colors;
       for (depth=1; colors != 0; depth++)
         colors>>=2;
-      if (quantize_info->dither != MagickFalse)
+      if (quantize_info->dither_method != NoDitherMethod)
         depth--;
     }
   /*
@@ -2776,7 +2885,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
   cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
   if (cube_info == (CubeInfo *) NULL)
     {
-      (void) ThrowMagickException(&images->exception,GetMagickModule(),
+      (void) ThrowMagickException(exception,GetMagickModule(),
         ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
       return(MagickFalse);
     }
@@ -2786,7 +2895,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
   {
     progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
       image->client_data);
-    status=ClassifyImageColors(cube_info,image,&image->exception);
+    status=ClassifyImageColors(cube_info,image,exception);
     if (status == MagickFalse)
       break;
     (void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
@@ -2807,7 +2916,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
       {
         progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
           NULL,image->client_data);
-        status=AssignImageColors(image,cube_info);
+        status=AssignImageColors(image,cube_info,exception);
         if (status == MagickFalse)
           break;
         (void) SetImageProgressMonitor(image,progress_monitor,
@@ -2828,6 +2937,63 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
 %                                                                             %
 %                                                                             %
 %                                                                             %
++   Q u a n t i z e E r r o r F l a t t e n                                   %
+%                                                                             %
+%                                                                             %
+%                                                                             %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%  QuantizeErrorFlatten() traverses the color cube and flattens the quantization
+%  error into a sorted 1D array.  This accelerates the color reduction process.
+%
+%  Contributed by Yoya.
+%
+%  The format of the QuantizeImages method is:
+%
+%      size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
+%        const NodeInfo *node_info,const ssize_t offset,
+%        MagickRealType *quantize_error)
+%
+%  A description of each parameter follows.
+%
+%    o image: the image.
+%
+%    o cube_info: A pointer to the Cube structure.
+%
+%    o node_info: pointer to node in color cube tree that is current pointer.
+%
+%    o offset: quantize error offset.
+%
+%    o quantize_error: the quantization error vector.
+%
+*/
+static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
+  const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
+{
+  register ssize_t
+    i;
+
+  size_t
+    n,
+    number_children;
+
+  if (offset >= (ssize_t) cube_info->nodes)
+    return(0);
+  quantize_error[offset]=node_info->quantize_error;
+  n=1;
+  number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
+  for (i=0; i < (ssize_t) number_children ; i++)
+    if (node_info->child[i] != (NodeInfo *) NULL)
+      n+=QuantizeErrorFlatten(image,cube_info,node_info->child[i],offset+n,
+        quantize_error);
+  return(n);
+}
+\f
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%                                                                             %
+%                                                                             %
+%                                                                             %
 +   R e d u c e                                                               %
 %                                                                             %
 %                                                                             %
@@ -2934,6 +3100,22 @@ static void Reduce(const Image *image,CubeInfo *cube_info,
 %    o cube_info: A pointer to the Cube structure.
 %
 */
+
+static int MagickRealTypeCompare(const void *error_p,const void *error_q)
+{
+  MagickRealType
+    *p,
+    *q;
+
+  p=(MagickRealType *) error_p;
+  q=(MagickRealType *) error_q;
+  if (*p > *q)
+    return(1);
+  if (fabs((double) (*q-*p)) <= MagickEpsilon)
+    return(0);
+  return(-1);
+}
+
 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
 {
 #define ReduceImageTag  "Reduce/Image"
@@ -2948,6 +3130,29 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
     span;
 
   cube_info->next_threshold=0.0;
+  if ((cube_info->colors > cube_info->maximum_colors) && 
+      (cube_info->nodes > 128))
+    {
+      MagickRealType
+        *quantize_error;
+
+      /*
+        Enable rapid reduction of the number of unique colors.
+      */
+      quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
+        sizeof(*quantize_error));
+      if (quantize_error != (MagickRealType *) NULL)
+        {
+          (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
+            quantize_error);
+          qsort(quantize_error,cube_info->nodes,sizeof(MagickRealType),
+            MagickRealTypeCompare);
+          cube_info->next_threshold=quantize_error[MagickMax(cube_info->nodes-
+            110*(cube_info->maximum_colors+1)/100,0)];
+          quantize_error=(MagickRealType *) RelinquishMagickMemory(
+            quantize_error);
+        }
+  }
   for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
   {
     cube_info->pruning_threshold=cube_info->next_threshold;
@@ -2973,13 +3178,13 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  RemapImage() replaces the colors of an image with the closest color from
-%  a reference image.
+%  RemapImage() replaces the colors of an image with a dither of the colors
+%  provided.
 %
 %  The format of the RemapImage method is:
 %
 %      MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
-%        Image *image,const Image *remap_image)
+%        Image *image,const Image *remap_image,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -2989,9 +3194,11 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
 %
 %    o remap_image: the reference image.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
 MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
-  Image *image,const Image *remap_image)
+  Image *image,const Image *remap_image,ExceptionInfo *exception)
 {
   CubeInfo
     *cube_info;
@@ -3013,14 +3220,14 @@ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
   if (cube_info == (CubeInfo *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
-  status=ClassifyImageColors(cube_info,remap_image,&image->exception);
+  status=ClassifyImageColors(cube_info,remap_image,exception);
   if (status != MagickFalse)
     {
       /*
         Classify image colors from the reference image.
       */
       cube_info->quantize_info->number_colors=cube_info->colors;
-      status=AssignImageColors(image,cube_info);
+      status=AssignImageColors(image,cube_info,exception);
     }
   DestroyCubeInfo(cube_info);
   return(status);
@@ -3043,7 +3250,7 @@ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
 %  The format of the RemapImage method is:
 %
 %      MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
-%        Image *images,Image *remap_image)
+%        Image *images,Image *remap_image,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -3053,9 +3260,11 @@ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
 %
 %    o remap_image: the reference image.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
 MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
-  Image *images,const Image *remap_image)
+  Image *images,const Image *remap_image,ExceptionInfo *exception)
 {
   CubeInfo
     *cube_info;
@@ -3076,7 +3285,7 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
       /*
         Create a global colormap for an image sequence.
       */
-      status=QuantizeImages(quantize_info,images);
+      status=QuantizeImages(quantize_info,images,exception);
       return(status);
     }
   /*
@@ -3087,7 +3296,7 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
   if (cube_info == (CubeInfo *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
-  status=ClassifyImageColors(cube_info,remap_image,&image->exception);
+  status=ClassifyImageColors(cube_info,remap_image,exception);
   if (status != MagickFalse)
     {
       /*
@@ -3097,7 +3306,7 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
       image=images;
       for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
       {
-        status=AssignImageColors(image,cube_info);
+        status=AssignImageColors(image,cube_info,exception);
         if (status == MagickFalse)
           break;
       }
@@ -3121,12 +3330,14 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
 %
 %  The format of the SetGrayscaleImage method is:
 %
-%      MagickBooleanType SetGrayscaleImage(Image *image)
+%      MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
 %
 %  A description of each parameter follows:
 %
 %    o image: The image.
 %
+%    o exception: return any errors or warnings in this structure.
+%
 */
 
 #if defined(__cplusplus) || defined(c_plusplus)
@@ -3135,17 +3346,17 @@ extern "C" {
 
 static int IntensityCompare(const void *x,const void *y)
 {
-  PixelPacket
+  PixelInfo
     *color_1,
     *color_2;
 
   ssize_t
     intensity;
 
-  color_1=(PixelPacket *) x;
-  color_2=(PixelPacket *) y;
-  intensity=GetPixelPacketIntensity(color_1)-(ssize_t)
-    GetPixelPacketIntensity(color_2);
+  color_1=(PixelInfo *) x;
+  color_2=(PixelInfo *) y;
+  intensity=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
+    GetPixelInfoIntensity(color_2));
   return((int) intensity);
 }
 
@@ -3153,18 +3364,16 @@ static int IntensityCompare(const void *x,const void *y)
 }
 #endif
 
-static MagickBooleanType SetGrayscaleImage(Image *image)
+static MagickBooleanType SetGrayscaleImage(Image *image,
+  ExceptionInfo *exception)
 {
   CacheView
     *image_view;
 
-  ExceptionInfo
-    *exception;
-
   MagickBooleanType
     status;
 
-  PixelPacket
+  PixelInfo
     *colormap;
 
   register ssize_t
@@ -3178,7 +3387,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
   assert(image != (Image *) NULL);
   assert(image->signature == MagickSignature);
   if (image->type != GrayscaleType)
-    (void) TransformImageColorspace(image,GRAYColorspace);
+    (void) TransformImageColorspace(image,GRAYColorspace,exception);
   colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
     sizeof(*colormap_index));
   if (colormap_index == (ssize_t *) NULL)
@@ -3186,20 +3395,17 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
       image->filename);
   if (image->storage_class != PseudoClass)
     {
-      ExceptionInfo
-        *exception;
-
       for (i=0; i <= (ssize_t) MaxMap; i++)
         colormap_index[i]=(-1);
-      if (AcquireImageColormap(image,MaxMap+1) == MagickFalse)
+      if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
         ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
           image->filename);
       image->colors=0;
       status=MagickTrue;
-      exception=(&image->exception);
-      image_view=AcquireCacheView(image);
+      image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-      #pragma omp parallel for schedule(dynamic,4) shared(status)
+      #pragma omp parallel for schedule(static,4) shared(status) \
+        magick_threads(image,image,image->rows,1)
 #endif
       for (y=0; y < (ssize_t) image->rows; y++)
       {
@@ -3213,7 +3419,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
           continue;
         q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
           exception);
-        if (q == (const Quantum *) NULL)
+        if (q == (Quantum *) NULL)
           {
             status=MagickFalse;
             continue;
@@ -3227,19 +3433,21 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
           if (colormap_index[intensity] < 0)
             {
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-    #pragma omp critical (MagickCore_SetGrayscaleImage)
+              #pragma omp critical (MagickCore_SetGrayscaleImage)
 #endif
               if (colormap_index[intensity] < 0)
                 {
                   colormap_index[intensity]=(ssize_t) image->colors;
-                  image->colormap[image->colors].red=GetPixelRed(image,q);
-                  image->colormap[image->colors].green=GetPixelGreen(image,q);
-                  image->colormap[image->colors].blue=GetPixelBlue(image,q);
+                  image->colormap[image->colors].red=(double)
+                    GetPixelRed(image,q);
+                  image->colormap[image->colors].green=(double)
+                    GetPixelGreen(image,q);
+                  image->colormap[image->colors].blue=(double)
+                    GetPixelBlue(image,q);
                   image->colors++;
                }
             }
-          SetPixelIndex(image,(Quantum) 
-            colormap_index[intensity],q);
+          SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
           q+=GetPixelChannels(image);
         }
         if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
@@ -3248,19 +3456,18 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
       image_view=DestroyCacheView(image_view);
     }
   for (i=0; i < (ssize_t) image->colors; i++)
-    image->colormap[i].alpha=(unsigned short) i;
-  qsort((void *) image->colormap,image->colors,sizeof(PixelPacket),
+    image->colormap[i].alpha=(double) i;
+  qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
     IntensityCompare);
-  colormap=(PixelPacket *) AcquireQuantumMemory(image->colors,
-    sizeof(*colormap));
-  if (colormap == (PixelPacket *) NULL)
+  colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
+  if (colormap == (PixelInfo *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
   j=0;
   colormap[j]=image->colormap[0];
   for (i=0; i < (ssize_t) image->colors; i++)
   {
-    if (IsPixelPacketEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
+    if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
       {
         j++;
         colormap[j]=image->colormap[i];
@@ -3268,13 +3475,13 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
     colormap_index[(ssize_t) image->colormap[i].alpha]=j;
   }
   image->colors=(size_t) (j+1);
-  image->colormap=(PixelPacket *) RelinquishMagickMemory(image->colormap);
+  image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
   image->colormap=colormap;
   status=MagickTrue;
-  exception=(&image->exception);
-  image_view=AcquireCacheView(image);
+  image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic,4) shared(status)
+  #pragma omp parallel for schedule(static,4) shared(status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -3287,7 +3494,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
     if (status == MagickFalse)
       continue;
     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
-    if (q == (const Quantum *) NULL)
+    if (q == (Quantum *) NULL)
       {
         status=MagickFalse;
         continue;
@@ -3304,7 +3511,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image)
   image_view=DestroyCacheView(image_view);
   colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
   image->type=GrayscaleType;
-  if (IsImageMonochrome(image,&image->exception) != MagickFalse)
+  if (IsImageMonochrome(image,exception) != MagickFalse)
     image->type=BilevelType;
   return(status);
 }