]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/quantize.c
Fixed initialization of array.
[imagemagick] / MagickCore / quantize.c
index 5de7bcf22c05117aa6bdb4e9a5622e11e8503045..324c3be04cf8860058ffe57e884d901045951c3b 100644 (file)
 %
 %    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
@@ -441,7 +441,7 @@ static inline void AssociateAlphaPixel(const Image *image,
     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);
@@ -478,19 +478,6 @@ 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)
 {
@@ -505,14 +492,9 @@ static inline size_t ColorToNodeId(const CubeInfo *cube_info,
   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.
   */
@@ -522,14 +504,61 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
       cube_info->quantize_info->colorspace,exception);
   else
     if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
-      (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
+      (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.
   */
@@ -613,8 +642,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++)
@@ -654,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) (GetPixelInfoLuma(q) < (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))
@@ -730,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
@@ -755,7 +757,7 @@ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
   MagickBooleanType
     associate_alpha;
 
-  associate_alpha=image->alpha_trait != UndefinedPixelTrait ? MagickTrue :
+  associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
     MagickFalse;
   if ((cube_info->quantize_info->number_colors == 2) &&
       (cube_info->quantize_info->colorspace == GRAYColorspace))
@@ -1198,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)
@@ -1286,7 +1288,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*
@@ -1393,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);
 }
@@ -1545,7 +1547,6 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
         status=MagickFalse;
         continue;
       }
-    q+=(y & 0x01)*GetPixelChannels(image)*image->columns;
     cube=(*cube_info);
     current=pixels[id]+(y & 0x01)*image->columns;
     previous=pixels[id]+((y+1) & 0x01)*image->columns;
@@ -1562,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;
@@ -1636,14 +1636,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;
@@ -1666,7 +1670,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);
@@ -1676,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)
@@ -1926,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)
 {
@@ -2063,8 +2052,8 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_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.
   */
@@ -2218,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);
@@ -2245,8 +2234,8 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
       break;
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      index=1UL*GetPixelIndex(image,p);
-      if (image->alpha_trait != UndefinedPixelTrait)
+      index=GetPixelIndex(image,p);
+      if (image->alpha_trait == BlendPixelTrait)
         {
           alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
           beta=(double) (QuantumScale*image->colormap[index].alpha);
@@ -2311,7 +2300,7 @@ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
   quantize_info->dither_method=RiemersmaDitherMethod;
   quantize_info->colorspace=UndefinedColorspace;
   quantize_info->measure_error=MagickFalse;
-  quantize_info->signature=MagickSignature;
+  quantize_info->signature=MagickCoreSignature;
 }
 \f
 /*
@@ -2383,9 +2372,11 @@ 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) \
@@ -2447,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->alpha_trait != UndefinedPixelTrait))
+          (image->alpha_trait == BlendPixelTrait))
         SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
       q+=GetPixelChannels(image);
     }
@@ -2664,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)
 {
@@ -2740,26 +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->alpha_trait == UndefinedPixelTrait)
+  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) &&
       (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)
     {
@@ -2774,9 +2830,9 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
         colors>>=2;
       if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
         depth--;
-      if ((image->alpha_trait != UndefinedPixelTrait) && (depth > 5))
+      if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
         depth--;
-      if (IsImageGray(image,exception) != MagickFalse)
+      if (SetImageGray(image,exception) != MagickFalse)
         depth=MaxTreeDepth;
     }
   /*
@@ -2792,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);
@@ -2854,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)
     {
       /*
@@ -2957,11 +3019,11 @@ 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,
 %        const NodeInfo *node_info,const ssize_t offset,
-%        MagickRealType *quantize_error)
+%        double *quantize_error)
 %
 %  A description of each parameter follows.
 %
@@ -2977,7 +3039,7 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
 %
 */
 static size_t QuantizeErrorFlatten(const Image *image,const CubeInfo *cube_info,
-  const NodeInfo *node_info,const ssize_t offset,MagickRealType *quantize_error)
+  const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
 {
   register ssize_t
     i;
@@ -3110,17 +3172,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);
 }
@@ -3139,27 +3201,26 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
     span;
 
   cube_info->next_threshold=0.0;
-  if ((cube_info->colors > cube_info->maximum_colors) && 
-      (cube_info->nodes > 128))
+  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((ssize_t)
-            cube_info->nodes-110*(cube_info->maximum_colors+1)/100,0)];
-          quantize_error=(MagickRealType *) RelinquishMagickMemory(
-            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; )
@@ -3187,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:
 %
@@ -3219,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)
@@ -3285,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)
     {
@@ -3339,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:
 %
@@ -3355,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=(ssize_t) (GetPixelInfoIntensity(color_1)-(ssize_t)
-    GetPixelInfoIntensity(color_2));
+  intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
+    GetPixelInfoIntensity((const Image *) NULL,color_2);
   return((int) intensity);
 }
 
@@ -3394,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;
@@ -3520,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);
 }