]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/quantize.c
Fixed initialization of array.
[imagemagick] / MagickCore / quantize.c
index c1faafaf8689486e9dd88e010744dcf0cca0f471..324c3be04cf8860058ffe57e884d901045951c3b 100644 (file)
 %    MagickCore Methods to Reduce the Number of Unique Colors in an Image     %
 %                                                                             %
 %                           Software Design                                   %
-%                             John Cristy                                     %
+%                                Cristy                                       %
 %                              July 1992                                      %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2015 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
 %
 %    Sr, Sg, Sb: Sums of the red, green, and blue component values for all
 %    pixels not classified at a lower depth. The combination of these sums
-%    and n2  will ultimately characterize the mean color of a set of
+%    and n2 will ultimately characterize the mean color of a set of
 %    pixels represented by this node.
 %
 %    E: the distance squared in RGB space between each pixel contained
 #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"
 */
 typedef struct _RealPixelInfo
 {
-  MagickRealType
+  double
     red,
     green,
     blue,
@@ -238,7 +238,7 @@ typedef struct _NodeInfo
   RealPixelInfo
     total_color;
 
-  MagickRealType
+  double
     quantize_error;
 
   size_t
@@ -274,7 +274,7 @@ typedef struct _CubeInfo
   RealPixelInfo
     target;
 
-  MagickRealType
+  double
     distance,
     pruning_threshold,
     next_threshold;
@@ -290,13 +290,16 @@ typedef struct _CubeInfo
   Nodes
     *node_queue;
 
+  MemoryInfo
+    *memory_info;
+
   ssize_t
     *cache;
 
   RealPixelInfo
     error[ErrorQueueLength];
 
-  MagickRealType
+  double
     weights[ErrorQueueLength];
 
   QuantizeInfo
@@ -380,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(
@@ -433,55 +437,45 @@ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
 static inline void AssociateAlphaPixel(const Image *image,
   const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
 {
-  MagickRealType
+  double
     alpha;
 
   if ((cube_info->associate_alpha == MagickFalse) ||
-      (GetPixelAlpha(image,pixel)== OpaqueAlpha))
+      (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 AssociateAlphaPixelInfo(const Image *image,
-  const CubeInfo *cube_info,const PixelInfo *pixel,
-  RealPixelInfo *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;
-}
-
-static inline Quantum ClampToUnsignedQuantum(const MagickRealType value)
-{
-  if (value <= 0.0)
-    return((Quantum) 0);
-  if (value >= QuantumRange)
-    return((Quantum) QuantumRange);
-  return((Quantum) (value+0.5));
+  alpha_pixel->alpha=(double) pixel->alpha;
 }
 
 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
@@ -490,22 +484,17 @@ static inline size_t ColorToNodeId(const CubeInfo *cube_info,
   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,
-  ExceptionInfo *exception)
+static inline MagickBooleanType PreAssignImageColors(Image *image,
+  CubeInfo *cube_info,ExceptionInfo *exception)
 {
-#define AssignImageTag  "Assign/Image"
-
-  ssize_t
-    y;
-
   /*
     Allocate image colormap.
   */
@@ -514,22 +503,66 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
     (void) TransformImageColorspace((Image *) image,
       cube_info->quantize_info->colorspace,exception);
   else
-    if ((image->colorspace != GRAYColorspace) &&
-        (IssRGBColorspace(image->colorspace) == MagickFalse) &&
-        (image->colorspace != CMYColorspace))
-      (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+    if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
+      (void) TransformImageColorspace((Image *) image,sRGBColorspace,
+         exception);
   if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
-    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
-      image->filename);
+    return(MagickFalse);
   image->colors=0;
   cube_info->transparent_pixels=0;
   cube_info->transparent_index=(-1);
   (void) DefineImageColormap(image,cube_info,cube_info->root);
+  return(MagickTrue);
+}
+
+static inline void PostAssignImageColors(Image *image,CubeInfo *cube_info,
+  ExceptionInfo *exception)
+{
+  if (cube_info->quantize_info->measure_error != MagickFalse)
+    (void) GetImageQuantizeError(image,exception);
+  if ((cube_info->quantize_info->number_colors == 2) &&
+      (cube_info->quantize_info->colorspace == GRAYColorspace))
+    {
+      double
+        intensity;
+
+      register PixelInfo
+        *restrict q;
+
+      register ssize_t
+        i;
+
+      /*
+        Monochrome image.
+      */
+      q=image->colormap;
+      for (i=0; i < (ssize_t) image->colors; i++)
+      {
+        intensity=(double) (GetPixelInfoLuma(q) < (QuantumRange/2.0) ? 0 :
+          QuantumRange);
+        q->red=intensity;
+        q->green=q->red;
+        q->blue=q->red;
+        q++;
+      }
+    }
+}
+
+static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
+  ExceptionInfo *exception)
+{
+#define AssignImageTag  "Assign/Image"
+
+  ssize_t
+    y;
+
+  if (PreAssignImageColors(image,cube_info,exception) == MagickFalse)
+    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
+      image->filename);
   /*
     Create a reduced color image.
   */
-  if ((cube_info->quantize_info->dither != MagickFalse) &&
-      (cube_info->quantize_info->dither_method != NoDitherMethod))
+  if (cube_info->quantize_info->dither_method != NoDitherMethod)
     (void) DitherImage(image,cube_info,exception);
   else
     {
@@ -543,7 +576,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
       image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
       #pragma omp parallel for schedule(static,4) shared(status) \
-        dynamic_num_threads_dos(image->columns,image->rows)
+        magick_threads(image,image,image->rows,1)
 #endif
       for (y=0; y < (ssize_t) image->rows; y++)
       {
@@ -609,8 +642,8 @@ 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)*
-            (QuantumRange+1.0)+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;
           for (i=0; i < (ssize_t) count; i++)
@@ -650,34 +683,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
       }
       image_view=DestroyCacheView(image_view);
     }
-  if (cube_info->quantize_info->measure_error != MagickFalse)
-    (void) GetImageQuantizeError(image,exception);
-  if ((cube_info->quantize_info->number_colors == 2) &&
-      (cube_info->quantize_info->colorspace == GRAYColorspace))
-    {
-      double
-        intensity;
-
-      register PixelInfo
-        *restrict q;
-
-      register ssize_t
-        i;
-
-      /*
-        Monochrome image.
-      */
-      q=image->colormap;
-      for (i=0; i < (ssize_t) image->colors; i++)
-      {
-        intensity=(double) ((MagickRealType) GetPixelInfoIntensity(q) <
-          ((MagickRealType) QuantumRange/2.0) ? 0 : QuantumRange);
-        q->red=intensity;
-        q->green=intensity;
-        q->blue=intensity;
-        q++;
-      }
-    }
+  PostAssignImageColors(image,cube_info,exception);
   (void) SyncImage(image,exception);
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
       (cube_info->quantize_info->colorspace != CMYKColorspace))
@@ -726,7 +732,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
 %
 %    Sr, Sg, Sb : Sums of the red, green, and blue component values for
 %    all pixels not classified at a lower depth. The combination of
-%    these sums and n2  will ultimately characterize the mean color of a
+%    these sums and n2 will ultimately characterize the mean color of a
 %    set of pixels represented by this node.
 %
 %    E: the distance squared in RGB space between each pixel contained
@@ -751,9 +757,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;
@@ -771,7 +776,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   MagickBooleanType
     proceed;
 
-  MagickRealType
+  double
     bisect;
 
   NodeInfo
@@ -801,14 +806,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
     (void) TransformImageColorspace((Image *) image,
       cube_info->quantize_info->colorspace,exception);
   else
-    if ((image->colorspace != GRAYColorspace) &&
-        (image->colorspace != CMYColorspace) &&
-        (IssRGBColorspace(image->colorspace) == MagickFalse))
+    if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
       (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
-  midpoint.red=(MagickRealType) QuantumRange/2.0;
-  midpoint.green=(MagickRealType) QuantumRange/2.0;
-  midpoint.blue=(MagickRealType) QuantumRange/2.0;
-  midpoint.alpha=(MagickRealType) QuantumRange/2.0;
+  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=AcquireVirtualCacheView(image,exception);
   for (y=0; y < (ssize_t) image->rows; y++)
@@ -846,11 +849,14 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       }
       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++)
       {
+        double
+          distance;
+
         bisect*=0.5;
         id=ColorToNodeId(cube_info,&pixel,index);
         mid.red+=(id & 1) != 0 ? bisect : -bisect;
@@ -864,9 +870,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++;
           }
@@ -879,9 +888,11 @@ 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));
+        distance=(double) (error.red*error.red+error.green*error.green+
+          error.blue*error.blue+error.alpha*error.alpha);
+        if (IsNaN(distance) != MagickFalse)
+          distance=0.0;
+        node_info->quantize_error+=count*sqrt(distance);
         cube_info->root->quantize_error+=node_info->quantize_error;
         index--;
       }
@@ -889,11 +900,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)
@@ -941,11 +953,14 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       }
       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++)
       {
+        double
+          distance;
+
         bisect*=0.5;
         id=ColorToNodeId(cube_info,&pixel,index);
         mid.red+=(id & 1) != 0 ? bisect : -bisect;
@@ -959,9 +974,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++;
           }
@@ -974,9 +992,11 @@ 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));
+        distance=(double) (error.red*error.red+error.green*error.green+
+          error.blue*error.blue+error.alpha*error.alpha);
+        if (IsNaN(distance) != MagickFalse)
+          distance=0.0;
+        node_info->quantize_error+=count*sqrt(distance);
         cube_info->root->quantize_error+=node_info->quantize_error;
         index--;
       }
@@ -984,11 +1004,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,
@@ -1000,7 +1021,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
       (cube_info->quantize_info->colorspace != CMYKColorspace))
     (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
-  return(MagickTrue);
+  return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
 }
 \f
 /*
@@ -1042,7 +1063,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;
@@ -1096,10 +1116,10 @@ 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;
@@ -1119,8 +1139,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;
@@ -1180,7 +1200,7 @@ MagickExport MagickBooleanType CompressImageColormap(Image *image,
     quantize_info;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   if (IsPaletteImage(image,exception) == MagickFalse)
@@ -1240,7 +1260,7 @@ 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 PixelInfo
@@ -1250,48 +1270,47 @@ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
         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=(double) ClampToQuantum((MagickRealType)
-            (alpha*QuantumRange*node_info->total_color.red));
-          q->green=(double) ClampToQuantum((MagickRealType)
-            (alpha*QuantumRange*node_info->total_color.green));
-          q->blue=(double) ClampToQuantum((MagickRealType)
-            (alpha*(double) 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);
+          opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
           q->alpha=(double) ClampToQuantum(opacity);
           if (q->alpha == OpaqueAlpha)
             {
-              q->red=(double) ClampToQuantum((MagickRealType)
-                (alpha*QuantumRange*node_info->total_color.red));
-              q->green=(double) ClampToQuantum((MagickRealType)
-                (alpha*QuantumRange*node_info->total_color.green));
-              q->blue=(double) 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=(double) ClampToQuantum((MagickRealType)
-                (alpha*gamma*QuantumRange*node_info->total_color.red));
-              q->green=(double) ClampToQuantum((MagickRealType)
-                (alpha*gamma*QuantumRange*node_info->total_color.green));
-              q->blue=(double) 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;
@@ -1343,8 +1362,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);
 }
@@ -1376,8 +1395,8 @@ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
 {
   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
   assert(quantize_info != (QuantizeInfo *) NULL);
-  assert(quantize_info->signature == MagickSignature);
-  quantize_info->signature=(~MagickSignature);
+  assert(quantize_info->signature == MagickCoreSignature);
+  quantize_info->signature=(~MagickCoreSignature);
   quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
   return(quantize_info);
 }
@@ -1445,8 +1464,7 @@ static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
   (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
   for (i=0; i < (ssize_t) number_threads; i++)
   {
-    pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,
-      2*sizeof(**pixels));
+    pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
     if (pixels[i] == (RealPixelInfo *) NULL)
       return(DestroyPixelThreadSet(pixels));
   }
@@ -1464,13 +1482,11 @@ 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);
 }
 
@@ -1531,7 +1547,6 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
         status=MagickFalse;
         continue;
       }
-    q+=(y & 0x01)*image->columns*GetPixelChannels(image);
     cube=(*cube_info);
     current=pixels[id]+(y & 0x01)*image->columns;
     previous=pixels[id]+((y+1) & 0x01)*image->columns;
@@ -1548,9 +1563,8 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
       ssize_t
         u;
 
-      q-=(y & 0x01)*GetPixelChannels(image);
       u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
-      AssociateAlphaPixel(image,&cube,q,&pixel);
+      AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel);
       if (x > 0)
         {
           pixel.red+=7*current[u-v].red/16;
@@ -1583,11 +1597,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)
         {
@@ -1612,8 +1626,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;
         }
@@ -1622,21 +1636,25 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
       */
       index=(size_t) cube.cache[i];
       if (image->storage_class == PseudoClass)
-        SetPixelIndex(image,(Quantum) index,q);
+        SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image));
       if (cube.quantize_info->measure_error == MagickFalse)
         {
-          SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
-          SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
-          SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
+          SetPixelRed(image,ClampToQuantum(image->colormap[index].red),
+            q+u*GetPixelChannels(image));
+          SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),
+            q+u*GetPixelChannels(image));
+          SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),
+            q+u*GetPixelChannels(image));
           if (cube.associate_alpha != MagickFalse)
-            SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
+            SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),
+              q+u*GetPixelChannels(image));
         }
       if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
         status=MagickFalse;
       /*
         Store the error.
       */
-      AssociateAlphaPixelInfo(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;
@@ -1647,15 +1665,11 @@ 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)
             status=MagickFalse;
         }
-      q+=((y+1) & 0x01)*GetPixelChannels(image);
     }
   }
   image_view=DestroyCacheView(image_view);
@@ -1665,7 +1679,7 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
 
 static MagickBooleanType
   RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
-    ExceptionInfo *exception);
+    ExceptionInfo *);
 
 static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
   const size_t level,const unsigned int direction,ExceptionInfo *exception)
@@ -1839,11 +1853,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)
         {
@@ -1864,12 +1878,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;
@@ -1895,7 +1908,7 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
       */
       (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
         sizeof(p->error[0]));
-      AssociateAlphaPixelInfo(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;
@@ -1916,20 +1929,6 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
   return(MagickTrue);
 }
 
-static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
-{
-  if (x > y)
-    return(x);
-  return(y);
-}
-
-static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
-{
-  if (x < y)
-    return(x);
-  return(y);
-}
-
 static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
   ExceptionInfo *exception)
 {
@@ -2009,7 +2008,7 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
   CubeInfo
     *cube_info;
 
-  MagickRealType
+  double
     sum,
     weight;
 
@@ -2040,28 +2039,28 @@ 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.
   */
-  for (i=0; i < (ssize_t) length; i++)
-    cube_info->cache[i]=(-1);
+  (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)*
+    length);
   /*
     Distribute weights along a curve of exponential decay.
   */
   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));
   }
   /*
@@ -2192,7 +2191,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
   CacheView
     *image_view;
 
-  MagickRealType
+  double
     alpha,
     area,
     beta,
@@ -2208,7 +2207,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
@@ -2235,26 +2234,26 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
       break;
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      index=1UL*GetPixelIndex(image,p);
-      if (image->matte != MagickFalse)
+      index=GetPixelIndex(image,p);
+      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);
+      distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
+        image->colormap[index].red));
       mean_error_per_pixel+=distance;
       mean_error+=distance*distance;
       if (distance > maximum_error)
         maximum_error=distance;
-      distance=fabs(alpha*GetPixelGreen(image,p)-beta*
-        image->colormap[index].green);
+      distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
+        image->colormap[index].green));
       mean_error_per_pixel+=distance;
       mean_error+=distance*distance;
       if (distance > maximum_error)
         maximum_error=distance;
-      distance=fabs(alpha*GetPixelBlue(image,p)-beta*
-        image->colormap[index].blue);
+      distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta*
+        image->colormap[index].blue));
       mean_error_per_pixel+=distance;
       mean_error+=distance*distance;
       if (distance > maximum_error)
@@ -2298,11 +2297,10 @@ 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;
-  quantize_info->signature=MagickSignature;
+  quantize_info->signature=MagickCoreSignature;
 }
 \f
 /*
@@ -2322,7 +2320,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,ExceptionInfo *exception)
+%        const DitherMethod dither_method,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -2331,25 +2329,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,ExceptionInfo *exception)
+  const DitherMethod dither_method,ExceptionInfo *exception)
 {
 #define PosterizeImageTag  "Posterize/Image"
 #define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
@@ -2374,13 +2372,15 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
   if (image->storage_class == PseudoClass)
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
     #pragma omp parallel for schedule(static,4) shared(progress,status) \
-      dynamic_num_threads_uno(image->colors)
+      magick_threads(image,image,1,1)
 #endif
     for (i=0; i < (ssize_t) image->colors; i++)
     {
@@ -2408,7 +2408,7 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
   #pragma omp parallel for schedule(static,4) shared(progress,status) \
-    dynamic_num_threads_dos(image->columns,image->rows)
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -2438,7 +2438,7 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
           (image->colorspace == CMYKColorspace))
         SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
       if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
-          (image->matte == MagickTrue))
+          (image->alpha_trait == BlendPixelTrait))
         SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
       q+=GetPixelChannels(image);
     }
@@ -2462,7 +2462,7 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
   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,exception);
   quantize_info=DestroyQuantizeInfo(quantize_info);
@@ -2655,6 +2655,63 @@ static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
 %
 */
 
+static MagickBooleanType DirectToPseudoClassImage(Image *image,
+  CubeInfo *cube_info,ExceptionInfo *exception)
+{
+  MagickBooleanType
+    status;
+
+  ssize_t
+    y;
+
+  if (cube_info->colors > cube_info->maximum_colors)
+    return(MagickFalse);
+  if (PreAssignImageColors(image,cube_info,exception) == MagickFalse)
+    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
+      image->filename);
+  status=MagickTrue;
+#if defined(MAGICKCORE_OPENMP_SUPPORT)
+  #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++)
+  {
+    register Quantum
+      *restrict q;
+
+    register ssize_t
+      x;
+
+    if (status == MagickFalse)
+      continue;
+    q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
+    if (q == (Quantum *) NULL)
+      {
+        status=MagickFalse;
+        continue;
+      }
+    for (x=0; x < (ssize_t) image->columns; x++)
+    {
+      register ssize_t
+        i;
+
+      for (i=0; i < (ssize_t) image->colors; i++)
+      {
+        if (IsPixelEquivalent(image,q,&image->colormap[i]) == MagickFalse)
+          continue;
+        SetPixelIndex(image,(Quantum) i,q);
+        break;
+      }
+      q+=GetPixelChannels(image);
+    }
+    if (SyncAuthenticPixels(image,exception) == MagickFalse)
+      status=MagickFalse;
+  }
+  image->storage_class=PseudoClass;
+  PostAssignImageColors(image,cube_info,exception);
+  return(status);
+}
+
 static MagickBooleanType DirectToColormapImage(Image *image,
   ExceptionInfo *exception)
 {
@@ -2731,24 +2788,34 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
     maximum_colors;
 
   assert(quantize_info != (const QuantizeInfo *) NULL);
-  assert(quantize_info->signature == MagickSignature);
+  assert(quantize_info->signature == MagickCoreSignature);
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
   maximum_colors=quantize_info->number_colors;
   if (maximum_colors == 0)
     maximum_colors=MaxColormapSize;
   if (maximum_colors > MaxColormapSize)
     maximum_colors=MaxColormapSize;
-  if ((image->columns*image->rows) <= maximum_colors)
-    (void) DirectToColormapImage(image,exception);
-  if ((IsImageGray(image,exception) != MagickFalse) &&
-      (image->matte == MagickFalse))
-    (void) SetGrayscaleImage(image,exception);
+  if (image->alpha_trait != BlendPixelTrait)
+    {
+      if ((image->columns*image->rows) <= maximum_colors)
+        (void) DirectToColormapImage(image,exception);
+      if (SetImageGray(image,exception) != MagickFalse)
+        (void) SetGrayscaleImage(image,exception);
+    }
   if ((image->storage_class == PseudoClass) &&
       (image->colors <= maximum_colors))
-    return(MagickTrue);
+    {
+      if ((quantize_info->colorspace != UndefinedColorspace) &&
+          (quantize_info->colorspace != CMYKColorspace))
+        (void) TransformImageColorspace(image,quantize_info->colorspace,
+          exception);
+      return(MagickTrue);
+    }
   depth=quantize_info->tree_depth;
   if (depth == 0)
     {
@@ -2761,10 +2828,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 (SetImageGray(image,exception) != MagickFalse)
+        depth=MaxTreeDepth;
     }
   /*
     Initialize color cube.
@@ -2779,8 +2848,12 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
       /*
         Reduce the number of colors in the image.
       */
-      ReduceImageColors(image,cube_info);
-      status=AssignImageColors(image,cube_info,exception);
+      status=DirectToPseudoClassImage(image,cube_info,exception);
+      if (status == MagickFalse)
+      {
+        ReduceImageColors(image,cube_info);
+        status=AssignImageColors(image,cube_info,exception);
+      }
     }
   DestroyCubeInfo(cube_info);
   return(status);
@@ -2841,11 +2914,13 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
     number_images;
 
   assert(quantize_info != (const QuantizeInfo *) NULL);
-  assert(quantize_info->signature == MagickSignature);
+  assert(quantize_info->signature == MagickCoreSignature);
   assert(images != (Image *) NULL);
-  assert(images->signature == MagickSignature);
+  assert(images->signature == MagickCoreSignature);
   if (images->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
   if (GetNextImageInList(images) == (Image *) NULL)
     {
       /*
@@ -2872,7 +2947,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--;
     }
   /*
@@ -2882,7 +2957,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
   if (cube_info == (CubeInfo *) NULL)
     {
       (void) ThrowMagickException(exception,GetMagickModule(),
-        ResourceLimitError,"MemoryAllocationFailed","'%s'",images->filename);
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
       return(MagickFalse);
     }
   number_images=GetImageListLength(images);
@@ -2933,6 +3008,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 QuantizeErrorFlatten method is:
+%
+%      size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
+%        const NodeInfo *node_info,const ssize_t offset,
+%        double *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,double *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                                                               %
 %                                                                             %
 %                                                                             %
@@ -3039,6 +3171,22 @@ static void Reduce(const Image *image,CubeInfo *cube_info,
 %    o cube_info: A pointer to the Cube structure.
 %
 */
+
+static int QuantizeErrorCompare(const void *error_p,const void *error_q)
+{
+  double
+    *p,
+    *q;
+
+  p=(double *) error_p;
+  q=(double *) error_q;
+  if (*p > *q)
+    return(1);
+  if (fabs(*q-*p) <= MagickEpsilon)
+    return(0);
+  return(-1);
+}
+
 static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
 {
 #define ReduceImageTag  "Reduce/Image"
@@ -3053,6 +3201,28 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
     span;
 
   cube_info->next_threshold=0.0;
+  if (cube_info->colors > cube_info->maximum_colors)
+    {
+      double
+        *quantize_error;
+
+      /*
+        Enable rapid reduction of the number of unique colors.
+      */
+      quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
+        sizeof(*quantize_error));
+      if (quantize_error != (double *) NULL)
+        {
+          (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
+            quantize_error);
+          qsort(quantize_error,cube_info->nodes,sizeof(double),
+            QuantizeErrorCompare);
+          if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
+            cube_info->next_threshold=quantize_error[cube_info->nodes-110*
+              (cube_info->maximum_colors+1)/100];
+          quantize_error=(double *) RelinquishMagickMemory(quantize_error);
+        }
+  }
   for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
   {
     cube_info->pruning_threshold=cube_info->next_threshold;
@@ -3078,8 +3248,8 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  RemapImage() replaces the colors of an image with a dither of the colors
-%  provided.
+%  RemapImage() replaces the colors of an image with the closest of the colors
+%  from the reference image.
 %
 %  The format of the RemapImage method is:
 %
@@ -3110,11 +3280,13 @@ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
     Initialize color cube.
   */
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(remap_image != (Image *) NULL);
-  assert(remap_image->signature == MagickSignature);
+  assert(remap_image->signature == MagickCoreSignature);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
   cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
     quantize_info->number_colors);
   if (cube_info == (CubeInfo *) NULL)
@@ -3176,9 +3348,11 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
     status;
 
   assert(images != (Image *) NULL);
-  assert(images->signature == MagickSignature);
+  assert(images->signature == MagickCoreSignature);
   if (images->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickCoreSignature);
   image=images;
   if (remap_image == (Image *) NULL)
     {
@@ -3230,7 +3404,8 @@ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
 %
 %  The format of the SetGrayscaleImage method is:
 %
-%      MagickBooleanType SetGrayscaleImage(Image *image,ExceptionInfo *exeption)
+%      MagickBooleanType SetGrayscaleImage(Image *image,
+%        ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
 %
@@ -3246,17 +3421,17 @@ extern "C" {
 
 static int IntensityCompare(const void *x,const void *y)
 {
+  double
+    intensity;
+
   PixelInfo
     *color_1,
     *color_2;
 
-  ssize_t
-    intensity;
-
   color_1=(PixelInfo *) x;
   color_2=(PixelInfo *) y;
-  intensity=GetPixelInfoIntensity(color_1)-(ssize_t)
-    GetPixelInfoIntensity(color_2);
+  intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
+    GetPixelInfoIntensity((const Image *) NULL,color_2);
   return((int) intensity);
 }
 
@@ -3285,19 +3460,19 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->type != GrayscaleType)
     (void) TransformImageColorspace(image,GRAYColorspace,exception);
-  colormap_index=(ssize_t *) AcquireQuantumMemory(MaxMap+1,
+  colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
     sizeof(*colormap_index));
   if (colormap_index == (ssize_t *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
   if (image->storage_class != PseudoClass)
     {
-      for (i=0; i <= (ssize_t) MaxMap; i++)
-        colormap_index[i]=(-1);
-      if (AcquireImageColormap(image,MaxMap+1,exception) == MagickFalse)
+      (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
+        sizeof(*colormap_index));
+      if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
         ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
           image->filename);
       image->colors=0;
@@ -3305,7 +3480,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
       image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
       #pragma omp parallel for schedule(static,4) shared(status) \
-        dynamic_num_threads_dos(image->columns,image->rows)
+        magick_threads(image,image,image->rows,1)
 #endif
       for (y=0; y < (ssize_t) image->rows; y++)
       {
@@ -3347,8 +3522,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
                   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)
@@ -3360,8 +3534,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
     image->colormap[i].alpha=(double) i;
   qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
     IntensityCompare);
-  colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,
-    sizeof(*colormap));
+  colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
   if (colormap == (PixelInfo *) NULL)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
@@ -3383,7 +3556,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
   #pragma omp parallel for schedule(static,4) shared(status) \
-    dynamic_num_threads_dos(image->columns,image->rows)
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -3413,7 +3586,7 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
   image_view=DestroyCacheView(image_view);
   colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
   image->type=GrayscaleType;
-  if (IsImageMonochrome(image,exception) != MagickFalse)
+  if (SetImageMonochrome(image,exception) != MagickFalse)
     image->type=BilevelType;
   return(status);
 }