]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/quantize.c
https://github.com/ImageMagick/ImageMagick/issues/1584
[imagemagick] / MagickCore / quantize.c
index 8691fed97f4f5f1dea30807bc6a04a1a54d20d8d..76995a4433ecd15e846703065049de1978f0686f 100644 (file)
 %                              July 1992                                      %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2019 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  %
 %  obtain a copy of the License at                                            %
 %                                                                             %
-%    http://www.imagemagick.org/script/license.php                            %
+%    https://imagemagick.org/script/license.php                               %
 %                                                                             %
 %  Unless required by applicable law or agreed to in writing, software        %
 %  distributed under the License is distributed on an "AS IS" BASIS,          %
 %
 %    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
-%    pixels represented by this node.
+%    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
 %    within a node and the nodes' center.  This represents the
   Include declarations.
 */
 #include "MagickCore/studio.h"
+#include "MagickCore/artifact.h"
 #include "MagickCore/attribute.h"
 #include "MagickCore/cache-view.h"
 #include "MagickCore/color.h"
 #include "MagickCore/image-private.h"
 #include "MagickCore/list.h"
 #include "MagickCore/memory_.h"
+#include "MagickCore/memory-private.h"
 #include "MagickCore/monitor.h"
 #include "MagickCore/monitor-private.h"
 #include "MagickCore/option.h"
 #include "MagickCore/quantum-private.h"
 #include "MagickCore/resource_.h"
 #include "MagickCore/string_.h"
+#include "MagickCore/string-private.h"
 #include "MagickCore/thread-private.h"
 \f
 /*
 /*
   Typdef declarations.
 */
-typedef struct _RealPixelInfo
+typedef struct _DoublePixelPacket
 {
   double
     red,
     green,
     blue,
     alpha;
-} RealPixelInfo;
+} DoublePixelPacket;
 
 typedef struct _NodeInfo
 {
@@ -235,7 +238,7 @@ typedef struct _NodeInfo
   MagickSizeType
     number_unique;
 
-  RealPixelInfo
+  DoublePixelPacket
     total_color;
 
   double
@@ -271,7 +274,7 @@ typedef struct _CubeInfo
   MagickSizeType
     transparent_pixels;
 
-  RealPixelInfo
+  DoublePixelPacket
     target;
 
   double
@@ -296,7 +299,7 @@ typedef struct _CubeInfo
   ssize_t
     *cache;
 
-  RealPixelInfo
+  DoublePixelPacket
     error[ErrorQueueLength];
 
   double
@@ -343,8 +346,8 @@ static size_t
 static void
   ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
   DestroyCubeInfo(CubeInfo *),
-  PruneLevel(const Image *,CubeInfo *,const NodeInfo *),
-  PruneToCubeDepth(const Image *,CubeInfo *,const NodeInfo *),
+  PruneLevel(CubeInfo *,const NodeInfo *),
+  PruneToCubeDepth(CubeInfo *,const NodeInfo *),
   ReduceImageColors(const Image *,CubeInfo *);
 \f
 /*
@@ -374,9 +377,7 @@ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
   QuantizeInfo
     *quantize_info;
 
-  quantize_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*quantize_info));
-  if (quantize_info == (QuantizeInfo *) NULL)
-    ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
+  quantize_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*quantize_info));
   GetQuantizeInfo(quantize_info);
   if (image_info != (ImageInfo *) NULL)
     {
@@ -435,13 +436,13 @@ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
 */
 
 static inline void AssociateAlphaPixel(const Image *image,
-  const CubeInfo *cube_info,const Quantum *pixel,RealPixelInfo *alpha_pixel)
+  const CubeInfo *cube_info,const Quantum *pixel,DoublePixelPacket *alpha_pixel)
 {
   double
     alpha;
 
   if ((cube_info->associate_alpha == MagickFalse) ||
-      (GetPixelAlpha(image,pixel)== OpaqueAlpha))
+      (GetPixelAlpha(image,pixel) == OpaqueAlpha))
     {
       alpha_pixel->red=(double) GetPixelRed(image,pixel);
       alpha_pixel->green=(double) GetPixelGreen(image,pixel);
@@ -457,7 +458,7 @@ static inline void AssociateAlphaPixel(const Image *image,
 }
 
 static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
-  const PixelInfo *pixel,RealPixelInfo *alpha_pixel)
+  const PixelInfo *pixel,DoublePixelPacket *alpha_pixel)
 {
   double
     alpha;
@@ -478,21 +479,8 @@ static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
   alpha_pixel->alpha=(double) pixel->alpha;
 }
 
-static inline Quantum ClampPixel(const MagickRealType value)
-{
-  if (value < 0.0f)
-    return(0);
-  if (value >= (MagickRealType) QuantumRange)
-    return((Quantum) QuantumRange);
-#if !defined(MAGICKCORE_HDRI_SUPPORT)
-  return((Quantum) (value+0.5f));
-#else
-  return(value);
-#endif
-}
-
 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
-  const RealPixelInfo *pixel,size_t index)
+  const DoublePixelPacket *pixel,size_t index)
 {
   size_t
     id;
@@ -510,19 +498,19 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
 {
 #define AssignImageTag  "Assign/Image"
 
+  ColorspaceType
+    colorspace;
+
   ssize_t
     y;
 
   /*
     Allocate image colormap.
   */
-  if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
-      (cube_info->quantize_info->colorspace != CMYKColorspace))
-    (void) TransformImageColorspace((Image *) image,
-      cube_info->quantize_info->colorspace,exception);
-  else
-    if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
-      (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+  colorspace=image->colorspace;
+  if (cube_info->quantize_info->colorspace != UndefinedColorspace)
+    (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace,
+      exception);
   if (AcquireImageColormap(image,cube_info->colors,exception) == MagickFalse)
     ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
       image->filename);
@@ -533,8 +521,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
   /*
     Create a reduced color image.
   */
-  if ((cube_info->quantize_info->dither_method != NoDitherMethod) &&
-      (cube_info->quantize_info->dither_method != NoDitherMethod))
+  if (cube_info->quantize_info->dither_method != NoDitherMethod)
     (void) DitherImage(image,cube_info,exception);
   else
     {
@@ -547,8 +534,8 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
       status=MagickTrue;
       image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-      #pragma omp parallel for schedule(static,4) shared(status) \
-        magick_threads(image,image,image->rows,1)
+      #pragma omp parallel for schedule(static) shared(status) \
+        magick_number_threads(image,image,image->rows,1)
 #endif
       for (y=0; y < (ssize_t) image->rows; y++)
       {
@@ -556,7 +543,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
           cube;
 
         register Quantum
-          *restrict q;
+          *magick_restrict q;
 
         register ssize_t
           x;
@@ -576,7 +563,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
         cube=(*cube_info);
         for (x=0; x < (ssize_t) image->columns; x+=count)
         {
-          RealPixelInfo
+          DoublePixelPacket
             pixel;
 
           register const NodeInfo
@@ -614,8 +601,8 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
             Find closest color among siblings and their children.
           */
           cube.target=pixel;
-          cube.distance=(double) (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++)
@@ -644,9 +631,6 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
             MagickBooleanType
               proceed;
 
-#if defined(MAGICKCORE_OPENMP_SUPPORT)
-            #pragma omp critical (MagickCore_AssignImageColors)
-#endif
             proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
               image->rows);
             if (proceed == MagickFalse)
@@ -658,35 +642,34 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
   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))
+      ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) ||
+       (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=intensity;
-        q->blue=intensity;
-        q++;
-      }
+      intensity=0.0;
+      if ((image->colors > 1) &&
+          (GetPixelInfoLuma(image->colormap+0) >
+           GetPixelInfoLuma(image->colormap+1)))
+        intensity=(double) QuantumRange;
+      image->colormap[0].red=intensity;
+      image->colormap[0].green=intensity;
+      image->colormap[0].blue=intensity;
+      if (image->colors > 1)
+        {
+          image->colormap[1].red=(double) QuantumRange-intensity;
+          image->colormap[1].green=(double) QuantumRange-intensity;
+          image->colormap[1].blue=(double) QuantumRange-intensity;
+        }
     }
   (void) SyncImage(image,exception);
   if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
-      (cube_info->quantize_info->colorspace != CMYKColorspace))
-    (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+      (IssRGBCompatibleColorspace(colorspace) == MagickFalse))
+    (void) TransformImageColorspace(image,colorspace,exception);
   return(MagickTrue);
 }
 \f
@@ -731,7 +714,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
@@ -759,7 +742,8 @@ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
   associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
     MagickFalse;
   if ((cube_info->quantize_info->number_colors == 2) &&
-      (cube_info->quantize_info->colorspace == GRAYColorspace))
+      ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) ||
+       (cube_info->quantize_info->colorspace == GRAYColorspace)))
     associate_alpha=MagickFalse;
   cube_info->associate_alpha=associate_alpha;
 }
@@ -772,6 +756,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   CacheView
     *image_view;
 
+  DoublePixelPacket
+    error,
+    mid,
+    midpoint,
+    pixel;
+
   MagickBooleanType
     proceed;
 
@@ -781,12 +771,6 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   NodeInfo
     *node_info;
 
-  RealPixelInfo
-    error,
-    mid,
-    midpoint,
-    pixel;
-
   size_t
     count,
     id,
@@ -816,7 +800,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register const Quantum
-      *restrict p;
+      *magick_restrict p;
 
     register ssize_t
       x;
@@ -829,7 +813,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
         /*
           Prune one level if the color tree is too large.
         */
-        PruneLevel(image,cube_info,cube_info->root);
+        PruneLevel(cube_info,cube_info->root);
         cube_info->depth--;
       }
     for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
@@ -853,6 +837,9 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       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;
@@ -884,9 +871,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+=count*sqrt((double) (error.red*error.red+
-          error.green*error.green+error.blue*error.blue+
-          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))
+          distance=0.0;
+        node_info->quantize_error+=count*sqrt(distance);
         cube_info->root->quantize_error+=node_info->quantize_error;
         index--;
       }
@@ -898,13 +887,16 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       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*ClampPixel(
-          pixel.alpha);
+        node_info->total_color.alpha+=count*QuantumScale*
+          ClampPixel(pixel.alpha);
+      else
+        node_info->total_color.alpha+=count*QuantumScale*
+          ClampPixel((MagickRealType) OpaqueAlpha);
       p+=count*GetPixelChannels(image);
     }
     if (cube_info->colors > cube_info->maximum_colors)
       {
-        PruneToCubeDepth(image,cube_info,cube_info->root);
+        PruneToCubeDepth(cube_info,cube_info->root);
         break;
       }
     proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
@@ -915,7 +907,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   for (y++; y < (ssize_t) image->rows; y++)
   {
     register const Quantum
-      *restrict p;
+      *magick_restrict p;
 
     register ssize_t
       x;
@@ -928,7 +920,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
         /*
           Prune one level if the color tree is too large.
         */
-        PruneLevel(image,cube_info,cube_info->root);
+        PruneLevel(cube_info,cube_info->root);
         cube_info->depth--;
       }
     for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
@@ -952,6 +944,9 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       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;
@@ -983,9 +978,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+=count*sqrt((double) (error.red*error.red+
-          error.green*error.green+error.blue*error.blue+
-          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--;
       }
@@ -997,8 +994,11 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
       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*ClampPixel(
-          pixel.alpha);
+        node_info->total_color.alpha+=count*QuantumScale*
+          ClampPixel(pixel.alpha);
+      else
+        node_info->total_color.alpha+=count*QuantumScale*
+          ClampPixel((MagickRealType) OpaqueAlpha);
       p+=count*GetPixelChannels(image);
     }
     proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
@@ -1044,9 +1044,7 @@ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
   QuantizeInfo
     *clone_info;
 
-  clone_info=(QuantizeInfo *) AcquireMagickMemory(sizeof(*clone_info));
-  if (clone_info == (QuantizeInfo *) NULL)
-    ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
+  clone_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*clone_info));
   GetQuantizeInfo(clone_info);
   if (quantize_info == (QuantizeInfo *) NULL)
     return(clone_info);
@@ -1113,11 +1111,11 @@ static void ClosestColor(const Image *image,CubeInfo *cube_info,
         beta,
         distance;
 
-      register PixelInfo
-        *restrict p;
+      register DoublePixelPacket
+        *magick_restrict q;
 
-      register RealPixelInfo
-        *restrict q;
+      register PixelInfo
+        *magick_restrict p;
 
       /*
         Determine if this color is "closest".
@@ -1143,8 +1141,11 @@ static void ClosestColor(const Image *image,CubeInfo *cube_info,
               distance+=pixel*pixel;
               if (distance <= cube_info->distance)
                 {
-                  pixel=alpha-beta;
-                  distance+=pixel*pixel;
+                  if (cube_info->associate_alpha != MagickFalse)
+                    {
+                      pixel=p->alpha-q->alpha;
+                      distance+=pixel*pixel;
+                    }
                   if (distance <= cube_info->distance)
                     {
                       cube_info->distance=distance;
@@ -1189,10 +1190,10 @@ 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)
+  if (IsPaletteImage(image) == MagickFalse)
     return(MagickFalse);
   GetQuantizeInfo(&quantize_info);
   quantize_info.number_colors=image->colors;
@@ -1253,7 +1254,7 @@ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
         alpha;
 
       register PixelInfo
-        *restrict q;
+        *magick_restrict q;
 
       /*
         Colormap entry is defined by the mean color in this cube.
@@ -1277,7 +1278,7 @@ static size_t DefineImageColormap(Image *image,CubeInfo *cube_info,
             opacity;
 
           opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
-          q->alpha=(double) ClampToQuantum((opacity));
+          q->alpha=(double) ClampToQuantum(opacity);
           if (q->alpha == OpaqueAlpha)
             {
               q->red=(double) ClampToQuantum(alpha*QuantumRange*
@@ -1384,8 +1385,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);
 }
@@ -1421,22 +1422,22 @@ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
 %
 */
 
-static RealPixelInfo **DestroyPixelThreadSet(RealPixelInfo **pixels)
+static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels)
 {
   register ssize_t
     i;
 
-  assert(pixels != (RealPixelInfo **) NULL);
+  assert(pixels != (DoublePixelPacket **) 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);
+    if (pixels[i] != (DoublePixelPacket *) NULL)
+      pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]);
+  pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels);
   return(pixels);
 }
 
-static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
+static DoublePixelPacket **AcquirePixelThreadSet(const size_t count)
 {
-  RealPixelInfo
+  DoublePixelPacket
     **pixels;
 
   register ssize_t
@@ -1446,22 +1447,23 @@ static RealPixelInfo **AcquirePixelThreadSet(const size_t count)
     number_threads;
 
   number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
-  pixels=(RealPixelInfo **) AcquireQuantumMemory(number_threads,
+  pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads,
     sizeof(*pixels));
-  if (pixels == (RealPixelInfo **) NULL)
-    return((RealPixelInfo **) NULL);
-  (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
+  if (pixels == (DoublePixelPacket **) NULL)
+    return((DoublePixelPacket **) NULL);
+  (void) memset(pixels,0,number_threads*sizeof(*pixels));
   for (i=0; i < (ssize_t) number_threads; i++)
   {
-    pixels[i]=(RealPixelInfo *) AcquireQuantumMemory(count,2*sizeof(**pixels));
-    if (pixels[i] == (RealPixelInfo *) NULL)
+    pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count,2*
+      sizeof(**pixels));
+    if (pixels[i] == (DoublePixelPacket *) NULL)
       return(DestroyPixelThreadSet(pixels));
   }
   return(pixels);
 }
 
 static inline ssize_t CacheOffset(CubeInfo *cube_info,
-  const RealPixelInfo *pixel)
+  const DoublePixelPacket *pixel)
 {
 #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
 #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
@@ -1487,12 +1489,18 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
   CacheView
     *image_view;
 
-  MagickBooleanType
-    status;
+  const char
+    *artifact;
 
-  RealPixelInfo
+  double
+    amount;
+
+  DoublePixelPacket
     **pixels;
 
+  MagickBooleanType
+    status;
+
   ssize_t
     y;
 
@@ -1500,9 +1508,13 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
     Distribute quantization error using Floyd-Steinberg.
   */
   pixels=AcquirePixelThreadSet(image->columns);
-  if (pixels == (RealPixelInfo **) NULL)
+  if (pixels == (DoublePixelPacket **) NULL)
     return(MagickFalse);
   status=MagickTrue;
+  amount=1.0;
+  artifact=GetImageArtifact(image,"dither:diffusion-amount");
+  if (artifact != (const char *) NULL)
+    amount=StringToDoubleInterval(artifact,1.0);
   image_view=AcquireAuthenticCacheView(image,exception);
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1512,12 +1524,12 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
     CubeInfo
       cube;
 
-    RealPixelInfo
+    DoublePixelPacket
       *current,
       *previous;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
       x;
@@ -1536,14 +1548,13 @@ 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;
     v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      RealPixelInfo
+      DoublePixelPacket
         color,
         pixel;
 
@@ -1553,16 +1564,15 @@ 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;
-          pixel.green+=7*current[u-v].green/16;
-          pixel.blue+=7*current[u-v].blue/16;
+          pixel.red+=7.0*amount*current[u-v].red/16;
+          pixel.green+=7.0*amount*current[u-v].green/16;
+          pixel.blue+=7.0*amount*current[u-v].blue/16;
           if (cube.associate_alpha != MagickFalse)
-            pixel.alpha+=7*current[u-v].alpha/16;
+            pixel.alpha+=7.0*amount*current[u-v].alpha/16;
         }
       if (y > 0)
         {
@@ -1574,18 +1584,18 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
               if (cube.associate_alpha != MagickFalse)
                 pixel.alpha+=previous[u+v].alpha/16;
             }
-          pixel.red+=5*previous[u].red/16;
-          pixel.green+=5*previous[u].green/16;
-          pixel.blue+=5*previous[u].blue/16;
+          pixel.red+=5.0*amount*previous[u].red/16;
+          pixel.green+=5.0*amount*previous[u].green/16;
+          pixel.blue+=5.0*amount*previous[u].blue/16;
           if (cube.associate_alpha != MagickFalse)
-            pixel.alpha+=5*previous[u].alpha/16;
+            pixel.alpha+=5.0*amount*previous[u].alpha/16;
           if (x > 0)
             {
-              pixel.red+=3*previous[u-v].red/16;
-              pixel.green+=3*previous[u-v].green/16;
-              pixel.blue+=3*previous[u-v].blue/16;
+              pixel.red+=3.0*amount*previous[u-v].red/16;
+              pixel.green+=3.0*amount*previous[u-v].green/16;
+              pixel.blue+=3.0*amount*previous[u-v].blue/16;
               if (cube.associate_alpha != MagickFalse)
-                pixel.alpha+=3*previous[u-v].alpha/16;
+                pixel.alpha+=3.0*amount*previous[u-v].alpha/16;
             }
         }
       pixel.red=(double) ClampPixel(pixel.red);
@@ -1600,7 +1610,7 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
             *node_info;
 
           register size_t
-            id;
+            node_id;
 
           /*
             Identify the deepest node containing the pixel's color.
@@ -1608,10 +1618,10 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
           node_info=cube.root;
           for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
           {
-            id=ColorToNodeId(&cube,&pixel,index);
-            if (node_info->child[id] == (NodeInfo *) NULL)
+            node_id=ColorToNodeId(&cube,&pixel,index);
+            if (node_info->child[node_id] == (NodeInfo *) NULL)
               break;
-            node_info=node_info->child[id];
+            node_info=node_info->child[node_id];
           }
           /*
             Find closest color among siblings and their children.
@@ -1627,14 +1637,18 @@ 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;
@@ -1657,7 +1671,6 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
           if (proceed == MagickFalse)
             status=MagickFalse;
         }
-      q+=((y+1) & 0x01)*GetPixelChannels(image);
     }
   }
   image_view=DestroyCacheView(image_view);
@@ -1667,7 +1680,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)
@@ -1803,13 +1816,13 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
 {
 #define DitherImageTag  "Dither/Image"
 
-  MagickBooleanType
-    proceed;
-
-  RealPixelInfo
+  DoublePixelPacket
     color,
     pixel;
 
+  MagickBooleanType
+    proceed;
+
   register CubeInfo
     *p;
 
@@ -1821,7 +1834,7 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
       (p->y >= 0) && (p->y < (ssize_t) image->rows))
     {
       register Quantum
-        *restrict q;
+        *magick_restrict q;
 
       register ssize_t
         i;
@@ -1894,7 +1907,7 @@ static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
       /*
         Propagate the error as the last entry of the error queue.
       */
-      (void) CopyMagickMemory(p->error,p->error+1,(ErrorQueueLength-1)*
+      (void) memmove(p->error,p->error+1,(ErrorQueueLength-1)*
         sizeof(p->error[0]));
       AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
       p->error[ErrorQueueLength-1].red=pixel.red-color.red;
@@ -1917,20 +1930,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)
 {
@@ -1951,8 +1950,7 @@ static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
   /*
     Distribute quantization error along a Hilbert curve.
   */
-  (void) ResetMagickMemory(cube_info->error,0,ErrorQueueLength*
-    sizeof(*cube_info->error));
+  (void) memset(cube_info->error,0,ErrorQueueLength*sizeof(*cube_info->error));
   cube_info->x=0;
   cube_info->y=0;
   i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
@@ -2026,7 +2024,7 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
   cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
   if (cube_info == (CubeInfo *) NULL)
     return((CubeInfo *) NULL);
-  (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
+  (void) memset(cube_info,0,sizeof(*cube_info));
   cube_info->depth=depth;
   if (cube_info->depth > MaxTreeDepth)
     cube_info->depth=MaxTreeDepth;
@@ -2054,8 +2052,7 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
   /*
     Initialize color cache.
   */
-  for (i=0; i < (ssize_t) length; i++)
-    cube_info->cache[i]=(-1);
+  (void) memset(cube_info->cache,(-1),sizeof(*cube_info->cache)*length);
   /*
     Distribute weights along a curve of exponential decay.
   */
@@ -2138,7 +2135,7 @@ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
   cube_info->nodes++;
   cube_info->free_nodes--;
   node_info=cube_info->next_node++;
-  (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
+  (void) memset(node_info,0,sizeof(*node_info));
   node_info->parent=parent;
   node_info->id=id;
   node_info->level=level;
@@ -2202,18 +2199,16 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
     mean_error,
     mean_error_per_pixel;
 
-  size_t
-    index;
-
   ssize_t
+    index,
     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);
-  (void) ResetMagickMemory(&image->error,0,sizeof(image->error));
+  (void) memset(&image->error,0,sizeof(image->error));
   if (image->storage_class == DirectClass)
     return(MagickTrue);
   alpha=1.0;
@@ -2226,7 +2221,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register const Quantum
-      *restrict p;
+      *magick_restrict p;
 
     register ssize_t
       x;
@@ -2236,26 +2231,26 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
       break;
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      index=1UL*GetPixelIndex(image,p);
+      index=(ssize_t) GetPixelIndex(image,p);
       if (image->alpha_trait == BlendPixelTrait)
         {
           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)
@@ -2297,12 +2292,12 @@ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
 {
   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
   assert(quantize_info != (QuantizeInfo *) NULL);
-  (void) ResetMagickMemory(quantize_info,0,sizeof(*quantize_info));
+  (void) memset(quantize_info,0,sizeof(*quantize_info));
   quantize_info->number_colors=256;
   quantize_info->dither_method=RiemersmaDitherMethod;
   quantize_info->colorspace=UndefinedColorspace;
   quantize_info->measure_error=MagickFalse;
-  quantize_info->signature=MagickSignature;
+  quantize_info->signature=MagickCoreSignature;
 }
 \f
 /*
@@ -2352,8 +2347,8 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
   const DitherMethod dither_method,ExceptionInfo *exception)
 {
 #define PosterizeImageTag  "Posterize/Image"
-#define PosterizePixel(pixel) (Quantum) (QuantumRange*(MagickRound( \
-  QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
+#define PosterizePixel(pixel) ClampToQuantum((MagickRealType) QuantumRange*( \
+  MagickRound(QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
 
   CacheView
     *image_view;
@@ -2374,13 +2369,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) \
-      magick_threads(image,image,1,1)
+    #pragma omp parallel for schedule(static) shared(progress,status) \
+      magick_number_threads(image,image,image->colors,1)
 #endif
     for (i=0; i < (ssize_t) image->colors; i++)
     {
@@ -2407,13 +2404,13 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
   progress=0;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,4) shared(progress,status) \
-    magick_threads(image,image,image->rows,1)
+  #pragma omp parallel for schedule(static) shared(progress,status) \
+    magick_number_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
       x;
@@ -2450,10 +2447,10 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
           proceed;
 
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-        #pragma omp critical (MagickCore_PosterizeImage)
+        #pragma omp atomic
 #endif
-        proceed=SetImageProgress(image,PosterizeImageTag,progress++,
-          image->rows);
+        progress++;
+        proceed=SetImageProgress(image,PosterizeImageTag,progress,image->rows);
         if (proceed == MagickFalse)
           status=MagickFalse;
       }
@@ -2485,20 +2482,16 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
 %
 %  The format of the PruneSubtree method is:
 %
-%      PruneChild(const Image *image,CubeInfo *cube_info,
-%        const NodeInfo *node_info)
+%      PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
 %
 %  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 to be pruned.
 %
 */
-static void PruneChild(const Image *image,CubeInfo *cube_info,
-  const NodeInfo *node_info)
+static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
 {
   NodeInfo
     *parent;
@@ -2515,7 +2508,7 @@ static void PruneChild(const Image *image,CubeInfo *cube_info,
   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)
-      PruneChild(image,cube_info,node_info->child[i]);
+      PruneChild(cube_info,node_info->child[i]);
   /*
     Merge color statistics into parent.
   */
@@ -2545,20 +2538,16 @@ static void PruneChild(const Image *image,CubeInfo *cube_info,
 %
 %  The format of the PruneLevel method is:
 %
-%      PruneLevel(const Image *image,CubeInfo *cube_info,
-%        const NodeInfo *node_info)
+%      PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
 %
 %  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 to be pruned.
 %
 */
-static void PruneLevel(const Image *image,CubeInfo *cube_info,
-  const NodeInfo *node_info)
+static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
 {
   register ssize_t
     i;
@@ -2572,9 +2561,9 @@ static void PruneLevel(const Image *image,CubeInfo *cube_info,
   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)
-      PruneLevel(image,cube_info,node_info->child[i]);
+      PruneLevel(cube_info,node_info->child[i]);
   if (node_info->level == cube_info->depth)
-    PruneChild(image,cube_info,node_info);
+    PruneChild(cube_info,node_info);
 }
 \f
 /*
@@ -2594,8 +2583,7 @@ static void PruneLevel(const Image *image,CubeInfo *cube_info,
 %
 %  The format of the PruneToCubeDepth method is:
 %
-%      PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
-%        const NodeInfo *node_info)
+%      PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
 %
 %  A description of each parameter follows.
 %
@@ -2604,8 +2592,7 @@ static void PruneLevel(const Image *image,CubeInfo *cube_info,
 %    o node_info: pointer to node in color cube tree that is to be pruned.
 %
 */
-static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
-  const NodeInfo *node_info)
+static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
 {
   register ssize_t
     i;
@@ -2619,9 +2606,9 @@ static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
   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)
-      PruneToCubeDepth(image,cube_info,node_info->child[i]);
+      PruneToCubeDepth(cube_info,node_info->child[i]);
   if (node_info->level > cube_info->depth)
-    PruneChild(image,cube_info,node_info);
+    PruneChild(cube_info,node_info);
 }
 \f
 /*
@@ -2654,69 +2641,6 @@ static void PruneToCubeDepth(const Image *image,CubeInfo *cube_info,
 %    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,ExceptionInfo *exception)
 {
@@ -2731,11 +2655,13 @@ 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;
@@ -2743,14 +2669,19 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
     maximum_colors=MaxColormapSize;
   if (image->alpha_trait != BlendPixelTrait)
     {
-      if ((image->columns*image->rows) <= maximum_colors)
-        (void) DirectToColormapImage(image,exception);
-      if (IsImageGray(image,exception) != MagickFalse)
+      if (SetImageGray(image,exception) != MagickFalse)
         (void) SetGrayscaleImage(image,exception);
     }
-  if ((image->storage_class == PseudoClass) &&
+  if ((quantize_info->dither_method == NoDitherMethod) &&
+      (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)
     {
@@ -2767,6 +2698,8 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
         depth--;
       if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
         depth--;
+      if (SetImageGray(image,exception) != MagickFalse)
+        depth=MaxTreeDepth;
     }
   /*
     Initialize color cube.
@@ -2781,7 +2714,8 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
       /*
         Reduce the number of colors in the image.
       */
-      ReduceImageColors(image,cube_info);
+      if (cube_info->colors > cube_info->maximum_colors)
+        ReduceImageColors(image,cube_info);
       status=AssignImageColors(image,cube_info,exception);
     }
   DestroyCubeInfo(cube_info);
@@ -2843,11 +2777,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)
     {
       /*
@@ -2946,16 +2882,14 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
 %
 %  Contributed by Yoya.
 %
-%  The format of the QuantizeImages method is:
+%  The format of the QuantizeErrorFlatten method is:
 %
-%      size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
+%      size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
 %        const NodeInfo *node_info,const ssize_t offset,
-%        MagickRealType *quantize_error)
+%        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.
@@ -2965,8 +2899,8 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
 %    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)
+static size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
+  const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
 {
   register ssize_t
     i;
@@ -2982,7 +2916,7 @@ static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
   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,
+      n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n,
         quantize_error);
   return(n);
 }
@@ -3003,19 +2937,16 @@ static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
 %
 %  The format of the Reduce method is:
 %
-%      Reduce(const Image *image,CubeInfo *cube_info,const NodeInfo *node_info)
+%      Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
 %
 %  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 to be pruned.
 %
 */
-static void Reduce(const Image *image,CubeInfo *cube_info,
-  const NodeInfo *node_info)
+static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
 {
   register ssize_t
     i;
@@ -3029,9 +2960,9 @@ static void Reduce(const Image *image,CubeInfo *cube_info,
   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)
-      Reduce(image,cube_info,node_info->child[i]);
+      Reduce(cube_info,node_info->child[i]);
   if (node_info->quantize_error <= cube_info->pruning_threshold)
-    PruneChild(image,cube_info,node_info);
+    PruneChild(cube_info,node_info);
   else
     {
       /*
@@ -3099,17 +3030,17 @@ static void Reduce(const Image *image,CubeInfo *cube_info,
 %
 */
 
-static int MagickRealTypeCompare(const void *error_p,const void *error_q)
+static int QuantizeErrorCompare(const void *error_p,const void *error_q)
 {
-  MagickRealType
+  double
     *p,
     *q;
 
-  p=(MagickRealType *) error_p;
-  q=(MagickRealType *) error_q;
+  p=(double *) error_p;
+  q=(double *) error_q;
   if (*p > *q)
     return(1);
-  if (fabs((double) (*q-*p)) <= MagickEpsilon)
+  if (fabs(*q-*p) <= MagickEpsilon)
     return(0);
   return(-1);
 }
@@ -3130,24 +3061,24 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
   cube_info->next_threshold=0.0;
   if (cube_info->colors > cube_info->maximum_colors)
     {
-      MagickRealType
+      double
         *quantize_error;
 
       /*
         Enable rapid reduction of the number of unique colors.
       */
-      quantize_error=(MagickRealType *) AcquireQuantumMemory(cube_info->nodes,
+      quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
         sizeof(*quantize_error));
-      if (quantize_error != (MagickRealType *) NULL)
+      if (quantize_error != (double *) 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/100,0)];
-          quantize_error=(MagickRealType *) RelinquishMagickMemory(
+          (void) QuantizeErrorFlatten(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; )
@@ -3155,7 +3086,7 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
     cube_info->pruning_threshold=cube_info->next_threshold;
     cube_info->next_threshold=cube_info->root->quantize_error-1;
     cube_info->colors=0;
-    Reduce(image,cube_info,cube_info->root);
+    Reduce(cube_info,cube_info->root);
     offset=(MagickOffsetType) span-cube_info->colors;
     proceed=SetImageProgress(image,ReduceImageTag,offset,span-
       cube_info->maximum_colors+1);
@@ -3175,8 +3106,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:
 %
@@ -3207,11 +3138,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)
@@ -3273,9 +3206,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)
     {
@@ -3327,7 +3262,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:
 %
@@ -3343,17 +3279,21 @@ 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=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
-    GetPixelInfoIntensity(color_2));
+  intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
+    GetPixelInfoIntensity((const Image *) NULL,color_2);
+  if (intensity > (double) INT_MAX)
+    intensity=(double) INT_MAX;
+  if (intensity < (double) INT_MIN)
+    intensity=(double) INT_MIN;
   return((int) intensity);
 }
 
@@ -3376,38 +3316,44 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
   register ssize_t
     i;
 
+  size_t
+    extent;
+
   ssize_t
     *colormap_index,
     j,
     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,
+  extent=MagickMax(image->colors+1,MagickMax(MaxColormapSize,MaxMap+1));
+  colormap_index=(ssize_t *) AcquireQuantumMemory(extent,
     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)
-        ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
-          image->filename);
+      (void) memset(colormap_index,(-1),extent*sizeof(*colormap_index));
+      if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
+        {
+          colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
+          ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
+            image->filename);
+        }
       image->colors=0;
       status=MagickTrue;
       image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-      #pragma omp parallel for schedule(static,4) shared(status) \
-        magick_threads(image,image,image->rows,1)
+      #pragma omp parallel for schedule(static) shared(status) \
+        magick_number_threads(image,image,image->rows,1)
 #endif
       for (y=0; y < (ssize_t) image->rows; y++)
       {
         register Quantum
-          *restrict q;
+          *magick_restrict q;
 
         register ssize_t
           x;
@@ -3452,14 +3398,18 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
       }
       image_view=DestroyCacheView(image_view);
     }
+  (void) memset(colormap_index,0,extent*sizeof(*colormap_index));
   for (i=0; i < (ssize_t) image->colors; i++)
     image->colormap[i].alpha=(double) i;
   qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
     IntensityCompare);
   colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
   if (colormap == (PixelInfo *) NULL)
-    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
-      image->filename);
+    {
+      colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
+      ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
+        image->filename);
+    }
   j=0;
   colormap[j]=image->colormap[0];
   for (i=0; i < (ssize_t) image->colors; i++)
@@ -3477,13 +3427,13 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
   status=MagickTrue;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,4) shared(status) \
-    magick_threads(image,image,image->rows,1)
+  #pragma omp parallel for schedule(static) shared(status) \
+    magick_number_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
       x;
@@ -3508,7 +3458,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);
 }