]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/statistic.c
sigmoidal-contrast: prevent argument out of range and remove unnecessary ClampToQuantum
[imagemagick] / MagickCore / statistic.c
index 26d9a3d425e88eac6dfeca66a185a4cfa85d5246..85fbcb3f906d3cbdcf6536ff712fb75ad946f970 100644 (file)
@@ -17,7 +17,7 @@
 %                                 July 1992                                   %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2012 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  %
@@ -81,6 +81,7 @@
 #include "MagickCore/quantum-private.h"
 #include "MagickCore/random_.h"
 #include "MagickCore/random-private.h"
+#include "MagickCore/resource_.h"
 #include "MagickCore/segment.h"
 #include "MagickCore/semaphore.h"
 #include "MagickCore/signature-private.h"
 
 typedef struct _PixelChannels
 {
-  MagickRealType
+  double
     channel[CompositePixelChannel];
 } PixelChannels;
 
@@ -140,7 +141,7 @@ static PixelChannels **DestroyPixelThreadSet(PixelChannels **pixels)
     i;
 
   assert(pixels != (PixelChannels **) NULL);
-  for (i=0; i < (ssize_t) GetOpenMPMaximumThreads(); i++)
+  for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
     if (pixels[i] != (PixelChannels *) NULL)
       pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]);
   pixels=(PixelChannels **) RelinquishMagickMemory(pixels);
@@ -160,8 +161,9 @@ static PixelChannels **AcquirePixelThreadSet(const Image *image,
     length,
     number_threads;
 
-  number_threads=GetOpenMPMaximumThreads();
-  pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,sizeof(*pixels));
+  number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
+  pixels=(PixelChannels **) AcquireQuantumMemory(number_threads,
+    sizeof(*pixels));
   if (pixels == (PixelChannels **) NULL)
     return((PixelChannels **) NULL);
   (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels));
@@ -188,7 +190,7 @@ static PixelChannels **AcquirePixelThreadSet(const Image *image,
   return(pixels);
 }
 
-static inline double MagickMax(const double x,const double y)
+static inline double EvaluateMax(const double x,const double y)
 {
   if (x > y)
     return(x);
@@ -205,7 +207,7 @@ static int IntensityCompare(const void *x,const void *y)
     *color_1,
     *color_2;
 
-  MagickRealType
+  double
     distance;
 
   register ssize_t
@@ -215,7 +217,7 @@ static int IntensityCompare(const void *x,const void *y)
   color_2=(const PixelChannels *) y;
   distance=0.0;
   for (i=0; i < MaxPixelChannels; i++)
-    distance+=color_1->channel[i]-(MagickRealType) color_2->channel[i];
+    distance+=color_1->channel[i]-(double) color_2->channel[i];
   return(distance < 0 ? -1 : distance > 0 ? 1 : 0);
 }
 
@@ -230,10 +232,10 @@ static inline double MagickMin(const double x,const double y)
   return(y);
 }
 
-static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
-  Quantum pixel,const MagickEvaluateOperator op,const MagickRealType value)
+static double ApplyEvaluateOperator(RandomInfo *random_info,
+  Quantum pixel,const MagickEvaluateOperator op,const double value)
 {
-  MagickRealType
+  double
     result;
 
   result=0.0;
@@ -243,21 +245,21 @@ static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
       break;
     case AbsEvaluateOperator:
     {
-      result=(MagickRealType) fabs((double) (pixel+value));
+      result=(double) fabs((double) (pixel+value));
       break;
     }
     case AddEvaluateOperator:
     {
-      result=(MagickRealType) (pixel+value);
+      result=(double) (pixel+value);
       break;
     }
     case AddModulusEvaluateOperator:
     {
       /*
-        This returns a 'floored modulus' of the addition which is a
-        positive result.  It differs from % or fmod() that returns a
-        'truncated modulus' result, where floor() is replaced by trunc() and
-        could return a negative result (which is clipped).
+        This returns a 'floored modulus' of the addition which is a positive
+        result.  It differs from % or fmod() that returns a 'truncated modulus'
+        result, where floor() is replaced by trunc() and could return a
+        negative result (which is clipped).
       */
       result=pixel+value;
       result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));
@@ -265,12 +267,12 @@ static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
     }
     case AndEvaluateOperator:
     {
-      result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));
+      result=(double) ((size_t) pixel & (size_t) (value+0.5));
       break;
     }
     case CosineEvaluateOperator:
     {
-      result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
+      result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
         QuantumScale*pixel*value))+0.5));
       break;
     }
@@ -281,90 +283,91 @@ static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
     }
     case ExponentialEvaluateOperator:
     {
-      result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*
+      result=(double) (QuantumRange*exp((double) (value*QuantumScale*
         pixel)));
       break;
     }
     case GaussianNoiseEvaluateOperator:
     {
-      result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
+      result=(double) GenerateDifferentialNoise(random_info,pixel,
         GaussianNoise,value);
       break;
     }
     case ImpulseNoiseEvaluateOperator:
     {
-      result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
+      result=(double) GenerateDifferentialNoise(random_info,pixel,
         ImpulseNoise,value);
       break;
     }
     case LaplacianNoiseEvaluateOperator:
     {
-      result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
+      result=(double) GenerateDifferentialNoise(random_info,pixel,
         LaplacianNoise,value);
       break;
     }
     case LeftShiftEvaluateOperator:
     {
-      result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));
+      result=(double) ((size_t) pixel << (size_t) (value+0.5));
       break;
     }
     case LogEvaluateOperator:
     {
-      result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*
-        pixel+1.0))/log((double) (value+1.0)));
+      if ((QuantumScale*pixel) >= MagickEpsilon)
+        result=(double) (QuantumRange*log((double) (QuantumScale*value*
+          pixel+1.0))/log((double) (value+1.0)));
       break;
     }
     case MaxEvaluateOperator:
     {
-      result=(MagickRealType) MagickMax((double) pixel,value);
+      result=(double) EvaluateMax((double) pixel,value);
       break;
     }
     case MeanEvaluateOperator:
     {
-      result=(MagickRealType) (pixel+value);
+      result=(double) (pixel+value);
       break;
     }
     case MedianEvaluateOperator:
     {
-      result=(MagickRealType) (pixel+value);
+      result=(double) (pixel+value);
       break;
     }
     case MinEvaluateOperator:
     {
-      result=(MagickRealType) MagickMin((double) pixel,value);
+      result=(double) MagickMin((double) pixel,value);
       break;
     }
     case MultiplicativeNoiseEvaluateOperator:
     {
-      result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
+      result=(double) GenerateDifferentialNoise(random_info,pixel,
         MultiplicativeGaussianNoise,value);
       break;
     }
     case MultiplyEvaluateOperator:
     {
-      result=(MagickRealType) (value*pixel);
+      result=(double) (value*pixel);
       break;
     }
     case OrEvaluateOperator:
     {
-      result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));
+      result=(double) ((size_t) pixel | (size_t) (value+0.5));
       break;
     }
     case PoissonNoiseEvaluateOperator:
     {
-      result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
+      result=(double) GenerateDifferentialNoise(random_info,pixel,
         PoissonNoise,value);
       break;
     }
     case PowEvaluateOperator:
     {
-      result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),
+      result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),
         (double) value));
       break;
     }
     case RightShiftEvaluateOperator:
     {
-      result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));
+      result=(double) ((size_t) pixel >> (size_t) (value+0.5));
       break;
     }
     case SetEvaluateOperator:
@@ -374,41 +377,46 @@ static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
     }
     case SineEvaluateOperator:
     {
-      result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
+      result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
         QuantumScale*pixel*value))+0.5));
       break;
     }
     case SubtractEvaluateOperator:
     {
-      result=(MagickRealType) (pixel-value);
+      result=(double) (pixel-value);
+      break;
+    }
+    case SumEvaluateOperator:
+    {
+      result=(double) (pixel+value);
       break;
     }
     case ThresholdEvaluateOperator:
     {
-      result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :
+      result=(double) (((double) pixel <= value) ? 0 :
         QuantumRange);
       break;
     }
     case ThresholdBlackEvaluateOperator:
     {
-      result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);
+      result=(double) (((double) pixel <= value) ? 0 : pixel);
       break;
     }
     case ThresholdWhiteEvaluateOperator:
     {
-      result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :
+      result=(double) (((double) pixel > value) ? QuantumRange :
         pixel);
       break;
     }
     case UniformNoiseEvaluateOperator:
     {
-      result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
+      result=(double) GenerateDifferentialNoise(random_info,pixel,
         UniformNoise,value);
       break;
     }
     case XorEvaluateOperator:
     {
-      result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));
+      result=(double) ((size_t) pixel ^ (size_t) (value+0.5));
       break;
     }
   }
@@ -427,7 +435,7 @@ MagickExport Image *EvaluateImages(const Image *images,
     *next;
 
   Image
-    *evaluate_image;
+    *image;
 
   MagickBooleanType
     status;
@@ -447,6 +455,9 @@ MagickExport Image *EvaluateImages(const Image *images,
   ssize_t
     y;
 
+  unsigned long
+    key;
+
   /*
     Ensure the image are the same size.
   */
@@ -460,28 +471,28 @@ MagickExport Image *EvaluateImages(const Image *images,
     if ((next->columns != images->columns) || (next->rows != images->rows))
       {
         (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
-          "ImageWidthsOrHeightsDiffer","`%s'",images->filename);
+          "ImageWidthsOrHeightsDiffer","'%s'",images->filename);
         return((Image *) NULL);
       }
   /*
     Initialize evaluate next attributes.
   */
-  evaluate_image=CloneImage(images,images->columns,images->rows,MagickTrue,
+  image=CloneImage(images,images->columns,images->rows,MagickTrue,
     exception);
-  if (evaluate_image == (Image *) NULL)
+  if (image == (Image *) NULL)
     return((Image *) NULL);
-  if (SetImageStorageClass(evaluate_image,DirectClass,exception) == MagickFalse)
+  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
     {
-      evaluate_image=DestroyImage(evaluate_image);
+      image=DestroyImage(image);
       return((Image *) NULL);
     }
   number_images=GetImageListLength(images);
   evaluate_pixels=AcquirePixelThreadSet(images,number_images);
   if (evaluate_pixels == (PixelChannels **) NULL)
     {
-      evaluate_image=DestroyImage(evaluate_image);
+      image=DestroyImage(image);
       (void) ThrowMagickException(exception,GetMagickModule(),
-        ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
+        ResourceLimitError,"MemoryAllocationFailed","'%s'",images->filename);
       return((Image *) NULL);
     }
   /*
@@ -490,269 +501,288 @@ MagickExport Image *EvaluateImages(const Image *images,
   status=MagickTrue;
   progress=0;
   random_info=AcquireRandomInfoThreadSet();
-  evaluate_view=AcquireCacheView(evaluate_image);
+  key=GetRandomSecretKey(random_info[0]);
+  evaluate_view=AcquireAuthenticCacheView(image,exception);
   if (op == MedianEvaluateOperator)
+    {
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic) shared(progress,status)
+      #pragma omp parallel for schedule(static) shared(progress,status) \
+        dynamic_number_threads(image,image->columns,image->rows,key == ~0UL)
 #endif
-    for (y=0; y < (ssize_t) evaluate_image->rows; y++)
-    {
-      CacheView
-        *image_view;
-
-      const Image
-        *next;
+      for (y=0; y < (ssize_t) image->rows; y++)
+      {
+        CacheView
+          *image_view;
 
-      const int
-        id = GetOpenMPThreadId();
+        const Image
+          *next;
 
-      register PixelChannels
-        *evaluate_pixel;
+        const int
+          id = GetOpenMPThreadId();
 
-      register Quantum
-        *restrict q;
+        register PixelChannels
+          *evaluate_pixel;
 
-      register ssize_t
-        x;
+        register Quantum
+          *restrict q;
 
-      if (status == MagickFalse)
-        continue;
-      q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,evaluate_image->columns,
-        1,exception);
-      if (q == (Quantum *) NULL)
-        {
-          status=MagickFalse;
-          continue;
-        }
-      evaluate_pixel=evaluate_pixels[id];
-      for (x=0; x < (ssize_t) evaluate_image->columns; x++)
-      {
         register ssize_t
-          j,
-          k;
+          x;
 
-        for (j=0; j < (ssize_t) number_images; j++)
-          for (k=0; k < MaxPixelChannels; k++)
-            evaluate_pixel[j].channel[k]=0.0;
-        next=images;
-        for (j=0; j < (ssize_t) number_images; j++)
+        if (status == MagickFalse)
+          continue;
+        q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,
+          image->columns,1,exception);
+        if (q == (Quantum *) NULL)
+          {
+            status=MagickFalse;
+            continue;
+          }
+        evaluate_pixel=evaluate_pixels[id];
+        for (x=0; x < (ssize_t) image->columns; x++)
         {
-          register const Quantum
-            *p;
-
           register ssize_t
-            i;
-
-          image_view=AcquireCacheView(next);
-          p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception);
-          if (p == (const Quantum *) NULL)
-            {
-              image_view=DestroyCacheView(image_view);
-              break;
-            }
-          for (i=0; i < (ssize_t) GetPixelChannels(evaluate_image); i++)
+            j,
+            k;
+
+          for (j=0; j < (ssize_t) number_images; j++)
+            for (k=0; k < MaxPixelChannels; k++)
+              evaluate_pixel[j].channel[k]=0.0;
+          next=images;
+          for (j=0; j < (ssize_t) number_images; j++)
           {
-            PixelChannel
-              channel;
+            register const Quantum
+              *p;
 
-            PixelTrait
-              evaluate_traits,
-              traits;
+            register ssize_t
+              i;
 
-            evaluate_traits=GetPixelChannelMapTraits(evaluate_image,
-              (PixelChannel) i);
-            channel=GetPixelChannelMapChannel(evaluate_image,(PixelChannel) i);
-            traits=GetPixelChannelMapTraits(next,channel);
-            if ((traits == UndefinedPixelTrait) ||
-                (evaluate_traits == UndefinedPixelTrait))
-              continue;
-            if ((evaluate_traits & UpdatePixelTrait) == 0)
-              continue;
-            evaluate_pixel[j].channel[i]=ApplyEvaluateOperator(random_info[id],
-              GetPixelChannel(evaluate_image,channel,p),op,
-              evaluate_pixel[j].channel[i]);
+            image_view=AcquireVirtualCacheView(next,exception);
+            p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception);
+            if (p == (const Quantum *) NULL)
+              {
+                image_view=DestroyCacheView(image_view);
+                break;
+              }
+            for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+            {
+              PixelChannel
+                channel;
+
+              PixelTrait
+                evaluate_traits,
+                traits;
+
+              channel=GetPixelChannelChannel(image,i);
+              evaluate_traits=GetPixelChannelTraits(image,channel);
+              traits=GetPixelChannelTraits(next,channel);
+              if ((traits == UndefinedPixelTrait) ||
+                  (evaluate_traits == UndefinedPixelTrait))
+                continue;
+              if ((evaluate_traits & UpdatePixelTrait) == 0)
+                continue;
+              evaluate_pixel[j].channel[i]=ApplyEvaluateOperator(
+                random_info[id],GetPixelChannel(image,channel,p),op,
+                evaluate_pixel[j].channel[i]);
+            }
+            image_view=DestroyCacheView(image_view);
+            next=GetNextImageInList(next);
           }
-          image_view=DestroyCacheView(image_view);
-          next=GetNextImageInList(next);
+          qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
+            IntensityCompare);
+          for (k=0; k < (ssize_t) GetPixelChannels(image); k++)
+            q[k]=ClampToQuantum(evaluate_pixel[j/2].channel[k]);
+          q+=GetPixelChannels(image);
         }
-        qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
-          IntensityCompare);
-        for (k=0; k < (ssize_t) GetPixelChannels(evaluate_image); k++)
-          q[k]=ClampToQuantum(evaluate_pixel[j/2].channel[k]);
-        q+=GetPixelChannels(evaluate_image);
-      }
-      if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
-        status=MagickFalse;
-      if (images->progress_monitor != (MagickProgressMonitor) NULL)
-        {
-          MagickBooleanType
-            proceed;
+        if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
+          status=MagickFalse;
+        if (images->progress_monitor != (MagickProgressMonitor) NULL)
+          {
+            MagickBooleanType
+              proceed;
 
-#if defined(MAGICKCORE_OPENMP_SUPPORT)
-          #pragma omp critical (MagickCore_EvaluateImages)
+#if   defined(MAGICKCORE_OPENMP_SUPPORT)
+            #pragma omp critical (MagickCore_EvaluateImages)
 #endif
-          proceed=SetImageProgress(images,EvaluateImageTag,progress++,
-            evaluate_image->rows);
-          if (proceed == MagickFalse)
-            status=MagickFalse;
-        }
+            proceed=SetImageProgress(images,EvaluateImageTag,progress++,
+              image->rows);
+            if (proceed == MagickFalse)
+              status=MagickFalse;
+          }
+      }
     }
   else
+    {
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-    #pragma omp parallel for schedule(dynamic) shared(progress,status)
+      #pragma omp parallel for schedule(static) shared(progress,status) \
+        dynamic_number_threads(image,image->columns,image->rows,key == ~0UL)
 #endif
-    for (y=0; y < (ssize_t) evaluate_image->rows; y++)
-    {
-      CacheView
-        *image_view;
+      for (y=0; y < (ssize_t) image->rows; y++)
+      {
+        CacheView
+          *image_view;
 
-      const Image
-        *next;
+        const Image
+          *next;
 
-      const int
-        id = GetOpenMPThreadId();
+        const int
+          id = GetOpenMPThreadId();
 
-      register ssize_t
-        i,
-        x;
+        register ssize_t
+          i,
+          x;
 
-      register PixelChannels
-        *evaluate_pixel;
+        register PixelChannels
+          *evaluate_pixel;
 
-      register Quantum
-        *restrict q;
+        register Quantum
+          *restrict q;
 
-      ssize_t
-        j;
+        ssize_t
+          j;
 
-      if (status == MagickFalse)
-        continue;
-      q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,evaluate_image->columns,
-        1,exception);
-      if (q == (Quantum *) NULL)
-        {
-          status=MagickFalse;
+        if (status == MagickFalse)
           continue;
+        q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,
+          image->columns,1,exception);
+        if (q == (Quantum *) NULL)
+          {
+            status=MagickFalse;
+            continue;
+          }
+        evaluate_pixel=evaluate_pixels[id];
+        for (j=0; j < (ssize_t) image->columns; j++)
+          for (i=0; i < MaxPixelChannels; i++)
+            evaluate_pixel[j].channel[i]=0.0;
+        next=images;
+        for (j=0; j < (ssize_t) number_images; j++)
+        {
+          register const Quantum
+            *p;
+
+          image_view=AcquireVirtualCacheView(next,exception);
+          p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
+          if (p == (const Quantum *) NULL)
+            {
+              image_view=DestroyCacheView(image_view);
+              break;
+            }
+          for (x=0; x < (ssize_t) next->columns; x++)
+          {
+            register ssize_t
+              i;
+
+            if (GetPixelMask(next,p) != 0)
+              {
+                p+=GetPixelChannels(next);
+                continue;
+              }
+            for (i=0; i < (ssize_t) GetPixelChannels(next); i++)
+            {
+              PixelChannel
+                channel;
+
+              PixelTrait
+                evaluate_traits,
+                traits;
+
+              channel=GetPixelChannelChannel(image,i);
+              traits=GetPixelChannelTraits(next,channel);
+              evaluate_traits=GetPixelChannelTraits(image,channel);
+              if ((traits == UndefinedPixelTrait) ||
+                  (evaluate_traits == UndefinedPixelTrait))
+                continue;
+              if ((traits & UpdatePixelTrait) == 0)
+                continue;
+              evaluate_pixel[x].channel[i]=ApplyEvaluateOperator(
+                random_info[id],GetPixelChannel(image,channel,p),j ==
+                0 ? AddEvaluateOperator : op,evaluate_pixel[x].channel[i]);
+            }
+            p+=GetPixelChannels(next);
+          }
+          image_view=DestroyCacheView(image_view);
+          next=GetNextImageInList(next);
         }
-      evaluate_pixel=evaluate_pixels[id];
-      for (j=0; j < (ssize_t) evaluate_image->columns; j++)
-        for (i=0; i < MaxPixelChannels; i++)
-          evaluate_pixel[j].channel[i]=0.0;
-      next=images;
-      for (j=0; j < (ssize_t) number_images; j++)
-      {
-        register const Quantum
-          *p;
+        for (x=0; x < (ssize_t) image->columns; x++)
+        {
+          register ssize_t
+             i;
 
-        image_view=AcquireCacheView(next);
-        p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
-        if (p == (const Quantum *) NULL)
+          switch (op)
           {
-            image_view=DestroyCacheView(image_view);
-            break;
+            case MeanEvaluateOperator:
+            {
+              for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+                evaluate_pixel[x].channel[i]/=(double) number_images;
+              break;
+            }
+            case MultiplyEvaluateOperator:
+            {
+              for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+              {
+                register ssize_t
+                  j;
+
+                for (j=0; j < (ssize_t) (number_images-1); j++)
+                  evaluate_pixel[x].channel[i]*=QuantumScale;
+              }
+              break;
+            }
+            default:
+              break;
           }
-        for (x=0; x < (ssize_t) next->columns; x++)
+        }
+        for (x=0; x < (ssize_t) image->columns; x++)
         {
           register ssize_t
             i;
 
-          for (i=0; i < (ssize_t) GetPixelChannels(evaluate_image); i++)
+          if (GetPixelMask(image,q) != 0)
+            {
+              q+=GetPixelChannels(image);
+              continue;
+            }
+          for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
           {
             PixelChannel
               channel;
 
             PixelTrait
-              evaluate_traits,
               traits;
 
-            evaluate_traits=GetPixelChannelMapTraits(evaluate_image,
-              (PixelChannel) i);
-            channel=GetPixelChannelMapChannel(evaluate_image,(PixelChannel) i);
-            traits=GetPixelChannelMapTraits(next,channel);
-            if ((traits == UndefinedPixelTrait) ||
-                (evaluate_traits == UndefinedPixelTrait))
+            channel=GetPixelChannelChannel(image,i);
+            traits=GetPixelChannelTraits(image,channel);
+            if (traits == UndefinedPixelTrait)
               continue;
             if ((traits & UpdatePixelTrait) == 0)
               continue;
-            evaluate_pixel[x].channel[i]=ApplyEvaluateOperator(random_info[id],
-              GetPixelChannel(evaluate_image,channel,p),j == 0 ?
-              AddEvaluateOperator : op,evaluate_pixel[x].channel[i]);
+            q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]);
           }
-          p+=GetPixelChannels(next);
+          q+=GetPixelChannels(image);
         }
-        image_view=DestroyCacheView(image_view);
-        next=GetNextImageInList(next);
-      }
-      for (x=0; x < (ssize_t) evaluate_image->columns; x++)
-      {
-        register ssize_t
-           i;
-
-        switch (op)
-        {
-          case MeanEvaluateOperator:
-          {
-            for (i=0; i < (ssize_t) GetPixelChannels(evaluate_image); i++)
-              evaluate_pixel[x].channel[i]/=(MagickRealType) number_images;
-            break;
-          }
-          case MultiplyEvaluateOperator:
+        if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
+          status=MagickFalse;
+        if (images->progress_monitor != (MagickProgressMonitor) NULL)
           {
-            for (i=0; i < (ssize_t) GetPixelChannels(evaluate_image); i++)
-            {
-              register ssize_t
-                j;
+            MagickBooleanType
+              proceed;
 
-              for (j=0; j < (ssize_t) (number_images-1); j++)
-                evaluate_pixel[x].channel[i]*=QuantumScale;
-            }
-            break;
+#if   defined(MAGICKCORE_OPENMP_SUPPORT)
+            #pragma omp critical (MagickCore_EvaluateImages)
+#endif
+            proceed=SetImageProgress(images,EvaluateImageTag,progress++,
+              image->rows);
+            if (proceed == MagickFalse)
+              status=MagickFalse;
           }
-          default:
-            break;
-        }
-      }
-      for (x=0; x < (ssize_t) evaluate_image->columns; x++)
-      {
-        register ssize_t
-          i;
-
-        for (i=0; i < (ssize_t) GetPixelChannels(evaluate_image); i++)
-        {
-          PixelTrait
-            traits;
-
-          traits=GetPixelChannelMapTraits(evaluate_image,(PixelChannel) i);
-          if (traits == UndefinedPixelTrait)
-            continue;
-          if ((traits & UpdatePixelTrait) == 0)
-            continue;
-          q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]);
-        }
-        q+=GetPixelChannels(evaluate_image);
       }
-      if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
-        status=MagickFalse;
-      if (images->progress_monitor != (MagickProgressMonitor) NULL)
-        {
-          MagickBooleanType
-            proceed;
-
-#if defined(MAGICKCORE_OPENMP_SUPPORT)
-          #pragma omp critical (MagickCore_EvaluateImages)
-#endif
-          proceed=SetImageProgress(images,EvaluateImageTag,progress++,
-            evaluate_image->rows);
-          if (proceed == MagickFalse)
-            status=MagickFalse;
-        }
     }
   evaluate_view=DestroyCacheView(evaluate_view);
   evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels);
   random_info=DestroyRandomInfoThreadSet(random_info);
   if (status == MagickFalse)
-    evaluate_image=DestroyImage(evaluate_image);
-  return(evaluate_image);
+    image=DestroyImage(image);
+  return(image);
 }
 
 MagickExport MagickBooleanType EvaluateImage(Image *image,
@@ -773,6 +803,9 @@ MagickExport MagickBooleanType EvaluateImage(Image *image,
   ssize_t
     y;
 
+  unsigned long
+    key;
+
   assert(image != (Image *) NULL);
   assert(image->signature == MagickSignature);
   if (image->debug != MagickFalse)
@@ -784,9 +817,11 @@ MagickExport MagickBooleanType EvaluateImage(Image *image,
   status=MagickTrue;
   progress=0;
   random_info=AcquireRandomInfoThreadSet();
-  image_view=AcquireCacheView(image);
+  key=GetRandomSecretKey(random_info[0]);
+  image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    dynamic_number_threads(image,image->columns,image->rows,key == ~0UL)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -814,12 +849,19 @@ MagickExport MagickBooleanType EvaluateImage(Image *image,
 
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
+        PixelChannel
+          channel;
+
         PixelTrait
           traits;
 
-        traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+        channel=GetPixelChannelChannel(image,i);
+        traits=GetPixelChannelTraits(image,channel);
         if (traits == UndefinedPixelTrait)
           continue;
+        if (((traits & CopyPixelTrait) != 0) ||
+            (GetPixelMask(image,q) != 0))
+          continue;
         q[i]=ClampToQuantum(ApplyEvaluateOperator(random_info[id],q[i],op,
           value));
       }
@@ -833,7 +875,7 @@ MagickExport MagickBooleanType EvaluateImage(Image *image,
           proceed;
 
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp critical (MagickCore_EvaluateImage)
+        #pragma omp critical (MagickCore_EvaluateImage)
 #endif
         proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows);
         if (proceed == MagickFalse)
@@ -883,7 +925,7 @@ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
   const size_t number_parameters,const double *parameters,
   ExceptionInfo *exception)
 {
-  MagickRealType
+  double
     result;
 
   register ssize_t
@@ -896,8 +938,8 @@ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
     case PolynomialFunction:
     {
       /*
-        Polynomial: polynomial constants, highest to lowest order
-        (e.g. c0*x^3 + c1*x^2 + c2*x + c3).
+        Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+
+        c1*x^2+c2*x+c3).
       */
       result=0.0;
       for (i=0; i < (ssize_t) number_parameters; i++)
@@ -907,7 +949,7 @@ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
     }
     case SinusoidFunction:
     {
-      MagickRealType
+      double
         amplitude,
         bias,
         frequency,
@@ -920,21 +962,21 @@ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
       phase=(number_parameters >= 2) ? parameters[1] : 0.0;
       amplitude=(number_parameters >= 3) ? parameters[2] : 0.5;
       bias=(number_parameters >= 4) ? parameters[3] : 0.5;
-      result=(MagickRealType) (QuantumRange*(amplitude*sin((double) (2.0*
+      result=(double) (QuantumRange*(amplitude*sin((double) (2.0*
         MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias));
       break;
     }
     case ArcsinFunction:
     {
-      MagickRealType
+      double
         bias,
         center,
         range,
         width;
 
       /*
-        Arcsin (peged at range limits for invalid results):
-        width, center, range, and bias.
+        Arcsin (peged at range limits for invalid results): width, center,
+        range, and bias.
       */
       width=(number_parameters >= 1) ? parameters[0] : 1.0;
       center=(number_parameters >= 2) ? parameters[1] : 0.5;
@@ -947,13 +989,13 @@ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
         if (result >= 1.0)
           result=bias+range/2.0;
         else
-          result=(MagickRealType) (range/MagickPI*asin((double) result)+bias);
+          result=(double) (range/MagickPI*asin((double) result)+bias);
       result*=QuantumRange;
       break;
     }
     case ArctanFunction:
     {
-      MagickRealType
+      double
         center,
         bias,
         range,
@@ -966,8 +1008,8 @@ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
       center=(number_parameters >= 2) ? parameters[1] : 0.5;
       range=(number_parameters >= 3) ? parameters[2] : 1.0;
       bias=(number_parameters >= 4) ? parameters[3] : 0.5;
-      result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center));
-      result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double)
+      result=(double) (MagickPI*slope*(QuantumScale*pixel-center));
+      result=(double) (QuantumRange*(range/MagickPI*atan((double)
         result)+bias));
       break;
     }
@@ -1005,9 +1047,10 @@ MagickExport MagickBooleanType FunctionImage(Image *image,
     return(MagickFalse);
   status=MagickTrue;
   progress=0;
-  image_view=AcquireCacheView(image);
+  image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    dynamic_number_threads(image,image->columns,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1030,12 +1073,21 @@ MagickExport MagickBooleanType FunctionImage(Image *image,
       register ssize_t
         i;
 
+      if (GetPixelMask(image,q) != 0)
+        {
+          q+=GetPixelChannels(image);
+          continue;
+        }
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
+        PixelChannel
+          channel;
+
         PixelTrait
           traits;
 
-        traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+        channel=GetPixelChannelChannel(image,i);
+        traits=GetPixelChannelTraits(image,channel);
         if (traits == UndefinedPixelTrait)
           continue;
         if ((traits & UpdatePixelTrait) == 0)
@@ -1053,7 +1105,7 @@ MagickExport MagickBooleanType FunctionImage(Image *image,
           proceed;
 
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp critical (MagickCore_FunctionImage)
+        #pragma omp critical (MagickCore_FunctionImage)
 #endif
         proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows);
         if (proceed == MagickFalse)
@@ -1124,8 +1176,8 @@ MagickExport MagickBooleanType GetImageExtrema(const Image *image,
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  GetImageMean() returns the mean and standard deviation of one or more
-%  image channels.
+%  GetImageMean() returns the mean and standard deviation of one or more image
+%  channels.
 %
 %  The format of the GetImageMean method is:
 %
@@ -1146,15 +1198,15 @@ MagickExport MagickBooleanType GetImageExtrema(const Image *image,
 MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
   double *standard_deviation,ExceptionInfo *exception)
 {
+  double
+    area;
+
   ChannelStatistics
     *channel_statistics;
 
   register ssize_t
     i;
 
-  size_t
-    area;
-
   assert(image != (Image *) NULL);
   assert(image->signature == MagickSignature);
   if (image->debug != MagickFalse)
@@ -1162,15 +1214,19 @@ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
   channel_statistics=GetImageStatistics(image,exception);
   if (channel_statistics == (ChannelStatistics *) NULL)
     return(MagickFalse);
-  area=0;
+  area=0.0;
   channel_statistics[CompositePixelChannel].mean=0.0;
   channel_statistics[CompositePixelChannel].standard_deviation=0.0;
   for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
   {
+    PixelChannel
+      channel;
+
     PixelTrait
       traits;
 
-    traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+    channel=GetPixelChannelChannel(image,i);
+    traits=GetPixelChannelTraits(image,channel);
     if (traits == UndefinedPixelTrait)
       continue;
     if ((traits & UpdatePixelTrait) == 0)
@@ -1185,7 +1241,8 @@ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
   channel_statistics[CompositePixelChannel].standard_deviation=
     sqrt(channel_statistics[CompositePixelChannel].standard_deviation/area);
   *mean=channel_statistics[CompositePixelChannel].mean;
-  *standard_deviation=channel_statistics[CompositePixelChannel].standard_deviation;
+  *standard_deviation=
+    channel_statistics[CompositePixelChannel].standard_deviation;
   channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
     channel_statistics);
   return(MagickTrue);
@@ -1254,9 +1311,10 @@ MagickExport MagickBooleanType GetImageKurtosis(const Image *image,
   sum_squares=0.0;
   sum_cubes=0.0;
   sum_fourth_power=0.0;
-  image_view=AcquireCacheView(image);
+  image_view=AcquireVirtualCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic) shared(status) omp_throttle(1)
+  #pragma omp parallel for schedule(static) shared(status) \
+    dynamic_number_threads(image,image->columns,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1281,13 +1339,18 @@ MagickExport MagickBooleanType GetImageKurtosis(const Image *image,
 
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
+        PixelChannel
+          channel;
+
         PixelTrait
           traits;
 
-        traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+        channel=GetPixelChannelChannel(image,i);
+        traits=GetPixelChannelTraits(image,channel);
         if (traits == UndefinedPixelTrait)
           continue;
-        if ((traits & UpdatePixelTrait) == 0)
+        if (((traits & UpdatePixelTrait) == 0) ||
+            (GetPixelMask(image,p) != 0))
           continue;
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
         #pragma omp critical (MagickCore_GetImageKurtosis)
@@ -1361,6 +1424,7 @@ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
     *image_view;
 
   MagickBooleanType
+    initialize,
     status;
 
   ssize_t
@@ -1371,11 +1435,13 @@ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   status=MagickTrue;
-  *maxima=(-MagickHuge);
-  *minima=MagickHuge;
-  image_view=AcquireCacheView(image);
+  initialize=MagickTrue;
+  *maxima=0.0;
+  *minima=0.0;
+  image_view=AcquireVirtualCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(dynamic) shared(status) omp_throttle(1)
+  #pragma omp parallel for schedule(static) shared(status,initialize) \
+    dynamic_number_threads(image,image->columns,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1398,12 +1464,21 @@ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
       register ssize_t
         i;
 
+      if (GetPixelMask(image,p) != 0)
+        {
+          p+=GetPixelChannels(image);
+          continue;
+        }
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
+        PixelChannel
+          channel;
+
         PixelTrait
           traits;
 
-        traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+        channel=GetPixelChannelChannel(image,i);
+        traits=GetPixelChannelTraits(image,channel);
         if (traits == UndefinedPixelTrait)
           continue;
         if ((traits & UpdatePixelTrait) == 0)
@@ -1412,10 +1487,19 @@ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
         #pragma omp critical (MagickCore_GetImageRange)
 #endif
         {
-          if (p[i] < *minima)
-            *minima=(double) p[i];
-          if (p[i] > *maxima)
-            *maxima=(double) p[i];
+          if (initialize != MagickFalse)
+            {
+              *minima=(double) p[i];
+              *maxima=(double) p[i];
+              initialize=MagickFalse;
+            }
+          else
+            {
+              if ((double) p[i] < *minima)
+                *minima=(double) p[i];
+              if ((double) p[i] > *maxima)
+                *maxima=(double) p[i];
+           }
         }
       }
       p+=GetPixelChannels(image);
@@ -1436,10 +1520,10 @@ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  GetImageStatistics() returns statistics for each channel in the
-%  image.  The statistics include the channel depth, its minima, maxima, mean,
-%  standard deviation, kurtosis and skewness.  You can access the red channel
-%  mean, for example, like this:
+%  GetImageStatistics() returns statistics for each channel in the image.  The
+%  statistics include the channel depth, its minima, maxima, mean, standard
+%  deviation, kurtosis and skewness.  You can access the red channel mean, for
+%  example, like this:
 %
 %      channel_statistics=GetImageStatistics(image,exception);
 %      red_mean=channel_statistics[RedPixelChannel].mean;
@@ -1470,10 +1554,14 @@ static size_t GetImageChannels(const Image *image)
   channels=0;
   for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
   {
+    PixelChannel
+      channel;
+
     PixelTrait
       traits;
 
-    traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+    channel=GetPixelChannelChannel(image,i);
+    traits=GetPixelChannelTraits(image,channel);
     if ((traits & UpdatePixelTrait) != 0)
       channels++;
   }
@@ -1486,9 +1574,6 @@ MagickExport ChannelStatistics *GetImageStatistics(const Image *image,
   ChannelStatistics
     *channel_statistics;
 
-  double
-    area;
-
   MagickStatusType
     status;
 
@@ -1537,45 +1622,60 @@ MagickExport ChannelStatistics *GetImageStatistics(const Image *image,
       register ssize_t
         i;
 
+      if (GetPixelMask(image,p) != 0)
+        {
+          p+=GetPixelChannels(image);
+          continue;
+        }
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
+        PixelChannel
+          channel;
+
         PixelTrait
           traits;
 
-        traits=GetPixelChannelMapTraits(image,(PixelChannel) i);
+        channel=GetPixelChannelChannel(image,i);
+        traits=GetPixelChannelTraits(image,channel);
         if (traits == UndefinedPixelTrait)
           continue;
-        if (channel_statistics[i].depth != MAGICKCORE_QUANTUM_DEPTH)
+        if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH)
           {
-            depth=channel_statistics[i].depth;
+            depth=channel_statistics[channel].depth;
             range=GetQuantumRange(depth);
             status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range),
               range) ? MagickTrue : MagickFalse;
             if (status != MagickFalse)
               {
-                channel_statistics[i].depth++;
+                channel_statistics[channel].depth++;
+                i--;
                 continue;
               }
           }
-        if ((double) p[i] < channel_statistics[i].minima)
-          channel_statistics[i].minima=(double) p[i];
-        if ((double) p[i] > channel_statistics[i].maxima)
-          channel_statistics[i].maxima=(double) p[i];
-        channel_statistics[i].sum+=p[i];
-        channel_statistics[i].sum_squared+=(double) p[i]*p[i];
-        channel_statistics[i].sum_cubed+=(double) p[i]*p[i]*p[i];
-        channel_statistics[i].sum_fourth_power+=(double) p[i]*p[i]*p[i]*p[i];
+        if ((double) p[i] < channel_statistics[channel].minima)
+          channel_statistics[channel].minima=(double) p[i];
+        if ((double) p[i] > channel_statistics[channel].maxima)
+          channel_statistics[channel].maxima=(double) p[i];
+        channel_statistics[channel].sum+=p[i];
+        channel_statistics[channel].sum_squared+=(double) p[i]*p[i];
+        channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i];
+        channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*
+          p[i];
+        channel_statistics[channel].area++;
       }
       p+=GetPixelChannels(image);
     }
   }
-  area=(double) image->columns*image->rows;
   for (i=0; i < (ssize_t) MaxPixelChannels; i++)
   {
-    channel_statistics[i].sum/=area;
-    channel_statistics[i].sum_squared/=area;
-    channel_statistics[i].sum_cubed/=area;
-    channel_statistics[i].sum_fourth_power/=area;
+    double
+      area;
+
+    area=MagickEpsilonReciprocal(channel_statistics[i].area);
+    channel_statistics[i].sum*=area;
+    channel_statistics[i].sum_squared*=area;
+    channel_statistics[i].sum_cubed*=area;
+    channel_statistics[i].sum_fourth_power*=area;
     channel_statistics[i].mean=channel_statistics[i].sum;
     channel_statistics[i].variance=channel_statistics[i].sum_squared;
     channel_statistics[i].standard_deviation=sqrt(
@@ -1584,13 +1684,13 @@ MagickExport ChannelStatistics *GetImageStatistics(const Image *image,
   }
   for (i=0; i < (ssize_t) MaxPixelChannels; i++)
   {
-    channel_statistics[CompositePixelChannel].depth=(size_t) MagickMax((double)
-      channel_statistics[CompositePixelChannel].depth,(double)
+    channel_statistics[CompositePixelChannel].depth=(size_t) EvaluateMax(
+      (double) channel_statistics[CompositePixelChannel].depth,(double)
       channel_statistics[i].depth);
     channel_statistics[CompositePixelChannel].minima=MagickMin(
       channel_statistics[CompositePixelChannel].minima,
       channel_statistics[i].minima);
-    channel_statistics[CompositePixelChannel].maxima=MagickMax(
+    channel_statistics[CompositePixelChannel].maxima=EvaluateMax(
       channel_statistics[CompositePixelChannel].maxima,
       channel_statistics[i].maxima);
     channel_statistics[CompositePixelChannel].sum+=channel_statistics[i].sum;
@@ -1621,23 +1721,710 @@ MagickExport ChannelStatistics *GetImageStatistics(const Image *image,
   channel_statistics[CompositePixelChannel].skewness/=channels;
   for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
   {
-    if (channel_statistics[i].standard_deviation == 0.0)
-      continue;
-    channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-
-      3.0*channel_statistics[i].mean*channel_statistics[i].sum_squared+
-      2.0*channel_statistics[i].mean*channel_statistics[i].mean*
-      channel_statistics[i].mean)/(channel_statistics[i].standard_deviation*
-      channel_statistics[i].standard_deviation*
+    double
+      standard_deviation;
+
+    standard_deviation=MagickEpsilonReciprocal(
       channel_statistics[i].standard_deviation);
-    channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-
-      4.0*channel_statistics[i].mean*channel_statistics[i].sum_cubed+
-      6.0*channel_statistics[i].mean*channel_statistics[i].mean*
+    channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0*
+      channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0*
+      channel_statistics[i].mean*channel_statistics[i].mean*
+      channel_statistics[i].mean)*(standard_deviation*standard_deviation*
+      standard_deviation);
+    channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0*
+      channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0*
+      channel_statistics[i].mean*channel_statistics[i].mean*
       channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean*
       channel_statistics[i].mean*1.0*channel_statistics[i].mean*
-      channel_statistics[i].mean)/(channel_statistics[i].standard_deviation*
-      channel_statistics[i].standard_deviation*
-      channel_statistics[i].standard_deviation*
-      channel_statistics[i].standard_deviation)-3.0;
+      channel_statistics[i].mean)*(standard_deviation*standard_deviation*
+      standard_deviation*standard_deviation)-3.0;
   }
   return(channel_statistics);
 }
+\f
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%                                                                             %
+%                                                                             %
+%                                                                             %
+%     S t a t i s t i c I m a g e                                             %
+%                                                                             %
+%                                                                             %
+%                                                                             %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%  StatisticImage() makes each pixel the min / max / median / mode / etc. of
+%  the neighborhood of the specified width and height.
+%
+%  The format of the StatisticImage method is:
+%
+%      Image *StatisticImage(const Image *image,const StatisticType type,
+%        const size_t width,const size_t height,ExceptionInfo *exception)
+%
+%  A description of each parameter follows:
+%
+%    o image: the image.
+%
+%    o type: the statistic type (median, mode, etc.).
+%
+%    o width: the width of the pixel neighborhood.
+%
+%    o height: the height of the pixel neighborhood.
+%
+%    o exception: return any errors or warnings in this structure.
+%
+*/
+
+typedef struct _SkipNode
+{
+  size_t
+    next[9],
+    count,
+    signature;
+} SkipNode;
+
+typedef struct _SkipList
+{
+  ssize_t
+    level;
+
+  SkipNode
+    *nodes;
+} SkipList;
+
+typedef struct _PixelList
+{
+  size_t
+    length,
+    seed;
+
+  SkipList
+    skip_list;
+
+  size_t
+    signature;
+} PixelList;
+
+static PixelList *DestroyPixelList(PixelList *pixel_list)
+{
+  if (pixel_list == (PixelList *) NULL)
+    return((PixelList *) NULL);
+  if (pixel_list->skip_list.nodes != (SkipNode *) NULL)
+    pixel_list->skip_list.nodes=(SkipNode *) RelinquishMagickMemory(
+      pixel_list->skip_list.nodes);
+  pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
+  return(pixel_list);
+}
+
+static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list)
+{
+  register ssize_t
+    i;
+
+  assert(pixel_list != (PixelList **) NULL);
+  for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
+    if (pixel_list[i] != (PixelList *) NULL)
+      pixel_list[i]=DestroyPixelList(pixel_list[i]);
+  pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list);
+  return(pixel_list);
+}
+
+static PixelList *AcquirePixelList(const size_t width,const size_t height)
+{
+  PixelList
+    *pixel_list;
+
+  pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list));
+  if (pixel_list == (PixelList *) NULL)
+    return(pixel_list);
+  (void) ResetMagickMemory((void *) pixel_list,0,sizeof(*pixel_list));
+  pixel_list->length=width*height;
+  pixel_list->skip_list.nodes=(SkipNode *) AcquireQuantumMemory(65537UL,
+    sizeof(*pixel_list->skip_list.nodes));
+  if (pixel_list->skip_list.nodes == (SkipNode *) NULL)
+    return(DestroyPixelList(pixel_list));
+  (void) ResetMagickMemory(pixel_list->skip_list.nodes,0,65537UL*
+    sizeof(*pixel_list->skip_list.nodes));
+  pixel_list->signature=MagickSignature;
+  return(pixel_list);
+}
+
+static PixelList **AcquirePixelListThreadSet(const size_t width,
+  const size_t height)
+{
+  PixelList
+    **pixel_list;
+
+  register ssize_t
+    i;
+
+  size_t
+    number_threads;
+
+  number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
+  pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
+    sizeof(*pixel_list));
+  if (pixel_list == (PixelList **) NULL)
+    return((PixelList **) NULL);
+  (void) ResetMagickMemory(pixel_list,0,number_threads*sizeof(*pixel_list));
+  for (i=0; i < (ssize_t) number_threads; i++)
+  {
+    pixel_list[i]=AcquirePixelList(width,height);
+    if (pixel_list[i] == (PixelList *) NULL)
+      return(DestroyPixelListThreadSet(pixel_list));
+  }
+  return(pixel_list);
+}
+
+static void AddNodePixelList(PixelList *pixel_list,const size_t color)
+{
+  register SkipList
+    *p;
+
+  register ssize_t
+    level;
+
+  size_t
+    search,
+    update[9];
+
+  /*
+    Initialize the node.
+  */
+  p=(&pixel_list->skip_list);
+  p->nodes[color].signature=pixel_list->signature;
+  p->nodes[color].count=1;
+  /*
+    Determine where it belongs in the list.
+  */
+  search=65536UL;
+  for (level=p->level; level >= 0; level--)
+  {
+    while (p->nodes[search].next[level] < color)
+      search=p->nodes[search].next[level];
+    update[level]=search;
+  }
+  /*
+    Generate a pseudo-random level for this node.
+  */
+  for (level=0; ; level++)
+  {
+    pixel_list->seed=(pixel_list->seed*42893621L)+1L;
+    if ((pixel_list->seed & 0x300) != 0x300)
+      break;
+  }
+  if (level > 8)
+    level=8;
+  if (level > (p->level+2))
+    level=p->level+2;
+  /*
+    If we're raising the list's level, link back to the root node.
+  */
+  while (level > p->level)
+  {
+    p->level++;
+    update[p->level]=65536UL;
+  }
+  /*
+    Link the node into the skip-list.
+  */
+  do
+  {
+    p->nodes[color].next[level]=p->nodes[update[level]].next[level];
+    p->nodes[update[level]].next[level]=color;
+  } while (level-- > 0);
+}
+
+static inline void GetMaximumPixelList(PixelList *pixel_list,Quantum *pixel)
+{
+  register SkipList
+    *p;
+
+  size_t
+    color,
+    maximum;
+
+  ssize_t
+    count;
+
+  /*
+    Find the maximum value for each of the color.
+  */
+  p=(&pixel_list->skip_list);
+  color=65536L;
+  count=0;
+  maximum=p->nodes[color].next[0];
+  do
+  {
+    color=p->nodes[color].next[0];
+    if (color > maximum)
+      maximum=color;
+    count+=p->nodes[color].count;
+  } while (count < (ssize_t) pixel_list->length);
+  *pixel=ScaleShortToQuantum((unsigned short) maximum);
+}
+
+static inline void GetMeanPixelList(PixelList *pixel_list,Quantum *pixel)
+{
+  double
+    sum;
+
+  register SkipList
+    *p;
+
+  size_t
+    color;
+
+  ssize_t
+    count;
+
+  /*
+    Find the mean value for each of the color.
+  */
+  p=(&pixel_list->skip_list);
+  color=65536L;
+  count=0;
+  sum=0.0;
+  do
+  {
+    color=p->nodes[color].next[0];
+    sum+=(double) p->nodes[color].count*color;
+    count+=p->nodes[color].count;
+  } while (count < (ssize_t) pixel_list->length);
+  sum/=pixel_list->length;
+  *pixel=ScaleShortToQuantum((unsigned short) sum);
+}
+
+static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel)
+{
+  register SkipList
+    *p;
+
+  size_t
+    color;
+
+  ssize_t
+    count;
+
+  /*
+    Find the median value for each of the color.
+  */
+  p=(&pixel_list->skip_list);
+  color=65536L;
+  count=0;
+  do
+  {
+    color=p->nodes[color].next[0];
+    count+=p->nodes[color].count;
+  } while (count <= (ssize_t) (pixel_list->length >> 1));
+  *pixel=ScaleShortToQuantum((unsigned short) color);
+}
+
+static inline void GetMinimumPixelList(PixelList *pixel_list,Quantum *pixel)
+{
+  register SkipList
+    *p;
+
+  size_t
+    color,
+    minimum;
+
+  ssize_t
+    count;
+
+  /*
+    Find the minimum value for each of the color.
+  */
+  p=(&pixel_list->skip_list);
+  count=0;
+  color=65536UL;
+  minimum=p->nodes[color].next[0];
+  do
+  {
+    color=p->nodes[color].next[0];
+    if (color < minimum)
+      minimum=color;
+    count+=p->nodes[color].count;
+  } while (count < (ssize_t) pixel_list->length);
+  *pixel=ScaleShortToQuantum((unsigned short) minimum);
+}
+
+static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel)
+{
+  register SkipList
+    *p;
+
+  size_t
+    color,
+    max_count,
+    mode;
+
+  ssize_t
+    count;
+
+  /*
+    Make each pixel the 'predominant color' of the specified neighborhood.
+  */
+  p=(&pixel_list->skip_list);
+  color=65536L;
+  mode=color;
+  max_count=p->nodes[mode].count;
+  count=0;
+  do
+  {
+    color=p->nodes[color].next[0];
+    if (p->nodes[color].count > max_count)
+      {
+        mode=color;
+        max_count=p->nodes[mode].count;
+      }
+    count+=p->nodes[color].count;
+  } while (count < (ssize_t) pixel_list->length);
+  *pixel=ScaleShortToQuantum((unsigned short) mode);
+}
+
+static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel)
+{
+  register SkipList
+    *p;
+
+  size_t
+    color,
+    next,
+    previous;
+
+  ssize_t
+    count;
+
+  /*
+    Finds the non peak value for each of the colors.
+  */
+  p=(&pixel_list->skip_list);
+  color=65536L;
+  next=p->nodes[color].next[0];
+  count=0;
+  do
+  {
+    previous=color;
+    color=next;
+    next=p->nodes[color].next[0];
+    count+=p->nodes[color].count;
+  } while (count <= (ssize_t) (pixel_list->length >> 1));
+  if ((previous == 65536UL) && (next != 65536UL))
+    color=next;
+  else
+    if ((previous != 65536UL) && (next == 65536UL))
+      color=previous;
+  *pixel=ScaleShortToQuantum((unsigned short) color);
+}
+
+static inline void GetStandardDeviationPixelList(PixelList *pixel_list,
+  Quantum *pixel)
+{
+  double
+    sum,
+    sum_squared;
+
+  register SkipList
+    *p;
+
+  size_t
+    color;
+
+  ssize_t
+    count;
+
+  /*
+    Find the standard-deviation value for each of the color.
+  */
+  p=(&pixel_list->skip_list);
+  color=65536L;
+  count=0;
+  sum=0.0;
+  sum_squared=0.0;
+  do
+  {
+    register ssize_t
+      i;
+
+    color=p->nodes[color].next[0];
+    sum+=(double) p->nodes[color].count*color;
+    for (i=0; i < (ssize_t) p->nodes[color].count; i++)
+      sum_squared+=((double) color)*((double) color);
+    count+=p->nodes[color].count;
+  } while (count < (ssize_t) pixel_list->length);
+  sum/=pixel_list->length;
+  sum_squared/=pixel_list->length;
+  *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum_squared-(sum*sum)));
+}
+
+static inline void InsertPixelList(const Image *image,const Quantum pixel,
+  PixelList *pixel_list)
+{
+  size_t
+    signature;
+
+  unsigned short
+    index;
+
+  index=ScaleQuantumToShort(pixel);
+  signature=pixel_list->skip_list.nodes[index].signature;
+  if (signature == pixel_list->signature)
+    {
+      pixel_list->skip_list.nodes[index].count++;
+      return;
+    }
+  AddNodePixelList(pixel_list,index);
+}
+
+static inline double MagickAbsoluteValue(const double x)
+{
+  if (x < 0)
+    return(-x);
+  return(x);
+}
+
+static inline size_t MagickMax(const size_t x,const size_t y)
+{
+  if (x > y)
+    return(x);
+  return(y);
+}
+
+static void ResetPixelList(PixelList *pixel_list)
+{
+  int
+    level;
+
+  register SkipNode
+    *root;
+
+  register SkipList
+    *p;
+
+  /*
+    Reset the skip-list.
+  */
+  p=(&pixel_list->skip_list);
+  root=p->nodes+65536UL;
+  p->level=0;
+  for (level=0; level < 9; level++)
+    root->next[level]=65536UL;
+  pixel_list->seed=pixel_list->signature++;
+}
+
+MagickExport Image *StatisticImage(const Image *image,const StatisticType type,
+  const size_t width,const size_t height,ExceptionInfo *exception)
+{
+#define StatisticImageTag  "Statistic/Image"
+
+  CacheView
+    *image_view,
+    *statistic_view;
+
+  Image
+    *statistic_image;
+
+  MagickBooleanType
+    status;
+
+  MagickOffsetType
+    progress;
+
+  PixelList
+    **restrict pixel_list;
+
+  ssize_t
+    center,
+    y;
+
+  /*
+    Initialize statistics image attributes.
+  */
+  assert(image != (Image *) NULL);
+  assert(image->signature == MagickSignature);
+  if (image->debug != MagickFalse)
+    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  assert(exception != (ExceptionInfo *) NULL);
+  assert(exception->signature == MagickSignature);
+  statistic_image=CloneImage(image,image->columns,image->rows,MagickTrue,
+    exception);
+  if (statistic_image == (Image *) NULL)
+    return((Image *) NULL);
+  status=SetImageStorageClass(statistic_image,DirectClass,exception);
+  if (status == MagickFalse)
+    {
+      statistic_image=DestroyImage(statistic_image);
+      return((Image *) NULL);
+    }
+  pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1));
+  if (pixel_list == (PixelList **) NULL)
+    {
+      statistic_image=DestroyImage(statistic_image);
+      ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
+    }
+  /*
+    Make each pixel the min / max / median / mode / etc. of the neighborhood.
+  */
+  center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))*
+    (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L);
+  status=MagickTrue;
+  progress=0;
+  image_view=AcquireVirtualCacheView(image,exception);
+  statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
+#if defined(MAGICKCORE_OPENMP_SUPPORT)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    dynamic_number_threads(image,image->columns,image->rows,1)
+#endif
+  for (y=0; y < (ssize_t) statistic_image->rows; y++)
+  {
+    const int
+      id = GetOpenMPThreadId();
+
+    register const Quantum
+      *restrict p;
+
+    register Quantum
+      *restrict q;
+
+    register ssize_t
+      x;
+
+    if (status == MagickFalse)
+      continue;
+    p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y-
+      (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1),
+      MagickMax(height,1),exception);
+    q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns,      1,exception);
+    if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
+      {
+        status=MagickFalse;
+        continue;
+      }
+    for (x=0; x < (ssize_t) statistic_image->columns; x++)
+    {
+      register ssize_t
+        i;
+
+      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+      {
+        PixelChannel
+          channel;
+
+        PixelTrait
+          statistic_traits,
+          traits;
+
+        Quantum
+          pixel;
+
+        register const Quantum
+          *restrict pixels;
+
+        register ssize_t
+          u;
+
+        ssize_t
+          v;
+
+        channel=GetPixelChannelChannel(image,i);
+        traits=GetPixelChannelTraits(image,channel);
+        statistic_traits=GetPixelChannelTraits(statistic_image,channel);
+        if ((traits == UndefinedPixelTrait) ||
+            (statistic_traits == UndefinedPixelTrait))
+          continue;
+        if (((statistic_traits & CopyPixelTrait) != 0) ||
+            (GetPixelMask(image,p) != 0))
+          {
+            SetPixelChannel(statistic_image,channel,p[center+i],q);
+            continue;
+          }
+        pixels=p;
+        ResetPixelList(pixel_list[id]);
+        for (v=0; v < (ssize_t) MagickMax(height,1); v++)
+        {
+          for (u=0; u < (ssize_t) MagickMax(width,1); u++)
+          {
+            InsertPixelList(image,pixels[i],pixel_list[id]);
+            pixels+=GetPixelChannels(image);
+          }
+          pixels+=image->columns*GetPixelChannels(image);
+        }
+        switch (type)
+        {
+          case GradientStatistic:
+          {
+            double
+              maximum,
+              minimum;
+
+            GetMinimumPixelList(pixel_list[id],&pixel);
+            minimum=(double) pixel;
+            GetMaximumPixelList(pixel_list[id],&pixel);
+            maximum=(double) pixel;
+            pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum));
+            break;
+          }
+          case MaximumStatistic:
+          {
+            GetMaximumPixelList(pixel_list[id],&pixel);
+            break;
+          }
+          case MeanStatistic:
+          {
+            GetMeanPixelList(pixel_list[id],&pixel);
+            break;
+          }
+          case MedianStatistic:
+          default:
+          {
+            GetMedianPixelList(pixel_list[id],&pixel);
+            break;
+          }
+          case MinimumStatistic:
+          {
+            GetMinimumPixelList(pixel_list[id],&pixel);
+            break;
+          }
+          case ModeStatistic:
+          {
+            GetModePixelList(pixel_list[id],&pixel);
+            break;
+          }
+          case NonpeakStatistic:
+          {
+            GetNonpeakPixelList(pixel_list[id],&pixel);
+            break;
+          }
+          case StandardDeviationStatistic:
+          {
+            GetStandardDeviationPixelList(pixel_list[id],&pixel);
+            break;
+          }
+        }
+        SetPixelChannel(statistic_image,channel,pixel,q);
+      }
+      p+=GetPixelChannels(image);
+      q+=GetPixelChannels(statistic_image);
+    }
+    if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
+      status=MagickFalse;
+    if (image->progress_monitor != (MagickProgressMonitor) NULL)
+      {
+        MagickBooleanType
+          proceed;
+
+#if defined(MAGICKCORE_OPENMP_SUPPORT)
+        #pragma omp critical (MagickCore_StatisticImage)
+#endif
+        proceed=SetImageProgress(image,StatisticImageTag,progress++,
+          image->rows);
+        if (proceed == MagickFalse)
+          status=MagickFalse;
+      }
+  }
+  statistic_view=DestroyCacheView(statistic_view);
+  image_view=DestroyCacheView(image_view);
+  pixel_list=DestroyPixelListThreadSet(pixel_list);
+  return(statistic_image);
+}