]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/quantize.c
https://github.com/ImageMagick/ImageMagick/issues/1584
[imagemagick] / MagickCore / quantize.c
index 68307bfacbd20ad2f9dd6d8cc77a061c033add84..76995a4433ecd15e846703065049de1978f0686f 100644 (file)
 %                              July 1992                                      %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2015 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,7 +436,7 @@ 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;
@@ -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;
@@ -479,7 +480,7 @@ static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
 }
 
 static inline size_t ColorToNodeId(const CubeInfo *cube_info,
-  const RealPixelInfo *pixel,size_t index)
+  const DoublePixelPacket *pixel,size_t index)
 {
   size_t
     id;
@@ -497,23 +498,22 @@ 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);;
+      image->filename);
   image->colors=0;
   cube_info->transparent_pixels=0;
   cube_info->transparent_index=(-1);
@@ -534,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++)
       {
@@ -543,7 +543,7 @@ static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
           cube;
 
         register Quantum
-          *restrict q;
+          *magick_restrict q;
 
         register ssize_t
           x;
@@ -563,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
@@ -631,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)
@@ -645,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=q->red;
-        q->blue=q->red;
-        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
@@ -746,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;
 }
@@ -759,6 +756,12 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   CacheView
     *image_view;
 
+  DoublePixelPacket
+    error,
+    mid,
+    midpoint,
+    pixel;
+
   MagickBooleanType
     proceed;
 
@@ -768,12 +771,6 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
   NodeInfo
     *node_info;
 
-  RealPixelInfo
-    error,
-    mid,
-    midpoint,
-    pixel;
-
   size_t
     count,
     id,
@@ -803,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;
@@ -816,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)
@@ -876,7 +873,7 @@ static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
           error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
         distance=(double) (error.red*error.red+error.green*error.green+
           error.blue*error.blue+error.alpha*error.alpha);
-        if (IsNaN(distance) != MagickFalse)
+        if (IsNaN(distance))
           distance=0.0;
         node_info->quantize_error+=count*sqrt(distance);
         cube_info->root->quantize_error+=node_info->quantize_error;
@@ -890,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,
@@ -907,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;
@@ -920,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)
@@ -994,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,
@@ -1041,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);
@@ -1110,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".
@@ -1140,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,7 +1193,7 @@ MagickExport MagickBooleanType CompressImageColormap(Image *image,
   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;
@@ -1250,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.
@@ -1418,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
@@ -1443,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)))
@@ -1484,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;
 
@@ -1497,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++)
   {
@@ -1509,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;
@@ -1539,7 +1554,7 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
     v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      RealPixelInfo
+      DoublePixelPacket
         color,
         pixel;
 
@@ -1553,11 +1568,11 @@ static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
       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)
         {
@@ -1569,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);
@@ -1595,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.
@@ -1603,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.
@@ -1801,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;
 
@@ -1819,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;
@@ -1892,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;
@@ -1935,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);
@@ -2010,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;
@@ -2038,8 +2052,7 @@ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
   /*
     Initialize color cache.
   */
-  (void) ResetMagickMemory(cube_info->cache,(-1),sizeof(*cube_info->cache)*
-    length);
+  (void) memset(cube_info->cache,(-1),sizeof(*cube_info->cache)*length);
   /*
     Distribute weights along a curve of exponential decay.
   */
@@ -2122,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;
@@ -2186,10 +2199,8 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
     mean_error,
     mean_error_per_pixel;
 
-  size_t
-    index;
-
   ssize_t
+    index,
     y;
 
   assert(image != (Image *) NULL);
@@ -2197,7 +2208,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
   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;
@@ -2210,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;
@@ -2220,7 +2231,7 @@ MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
       break;
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      index=GetPixelIndex(image,p);
+      index=(ssize_t) GetPixelIndex(image,p);
       if (image->alpha_trait == BlendPixelTrait)
         {
           alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
@@ -2281,7 +2292,7 @@ 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;
@@ -2336,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;
@@ -2365,8 +2376,8 @@ MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
   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++)
     {
@@ -2393,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;
@@ -2436,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;
       }
@@ -2471,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;
@@ -2501,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.
   */
@@ -2531,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;
@@ -2558,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
 /*
@@ -2580,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.
 %
@@ -2590,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;
@@ -2605,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
 /*
@@ -2640,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,12 +2669,11 @@ 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 (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))
     {
       if ((quantize_info->colorspace != UndefinedColorspace) &&
@@ -2775,13 +2712,10 @@ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
   if (status != MagickFalse)
     {
       /*
-        Reduce the number of colors in the image if it contains more than the
-        maximum, otherwise we can disable dithering to improve the performance.
+        Reduce the number of colors in the image.
       */
       if (cube_info->colors > cube_info->maximum_colors)
         ReduceImageColors(image,cube_info);
-      else
-        cube_info->quantize_info->dither_method=NoDitherMethod;
       status=AssignImageColors(image,cube_info,exception);
     }
   DestroyCubeInfo(cube_info);
@@ -2950,14 +2884,12 @@ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
 %
 %  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,
 %        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.
@@ -2967,7 +2899,7 @@ 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,
+static size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
   const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
 {
   register ssize_t
@@ -2984,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);
 }
@@ -3005,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;
@@ -3031,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
     {
       /*
@@ -3142,7 +3071,7 @@ static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
         sizeof(*quantize_error));
       if (quantize_error != (double *) NULL)
         {
-          (void) QuantizeErrorFlatten(image,cube_info,cube_info->root,0,
+          (void) QuantizeErrorFlatten(cube_info,cube_info->root,0,
             quantize_error);
           qsort(quantize_error,cube_info->nodes,sizeof(double),
             QuantizeErrorCompare);
@@ -3157,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);
@@ -3361,6 +3290,10 @@ static int IntensityCompare(const void *x,const void *y)
   color_2=(PixelInfo *) y;
   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);
 }
 
@@ -3383,6 +3316,9 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
   register ssize_t
     i;
 
+  size_t
+    extent;
+
   ssize_t
     *colormap_index,
     j,
@@ -3392,29 +3328,32 @@ static MagickBooleanType SetGrayscaleImage(Image *image,
   assert(image->signature == MagickCoreSignature);
   if (image->type != GrayscaleType)
     (void) TransformImageColorspace(image,GRAYColorspace,exception);
-  colormap_index=(ssize_t *) AcquireQuantumMemory(MaxColormapSize,
+  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)
     {
-      (void) ResetMagickMemory(colormap_index,(-1),MaxColormapSize*
-        sizeof(*colormap_index));
+      (void) memset(colormap_index,(-1),extent*sizeof(*colormap_index));
       if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
-        ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
-          image->filename);
+        {
+          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;
@@ -3459,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++)
@@ -3484,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;