]> granicus.if.org Git - imagemagick/blobdiff - MagickCore/threshold.c
Added caNv, eXIf, and pHYs to the list of PNG chunks to be removed
[imagemagick] / MagickCore / threshold.c
index 99b62c75b3a9d9e530fd9750254cc5936228addc..108bfeb0813d45e33ebdca3f0334e075eb8c1f63 100644 (file)
 %                      MagickCore Image Threshold Methods                     %
 %                                                                             %
 %                               Software Design                               %
-%                                 John Cristy                                 %
+%                                    Cristy                                   %
 %                                 October 1996                                %
 %                                                                             %
 %                                                                             %
-%  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
+%  Copyright 1999-2017 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://www.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,          %
 #include "MagickCore/montage.h"
 #include "MagickCore/option.h"
 #include "MagickCore/pixel-accessor.h"
+#include "MagickCore/pixel-private.h"
 #include "MagickCore/quantize.h"
 #include "MagickCore/quantum.h"
+#include "MagickCore/quantum-private.h"
 #include "MagickCore/random_.h"
 #include "MagickCore/random-private.h"
 #include "MagickCore/resize.h"
@@ -110,6 +112,28 @@ struct _ThresholdMap
     *levels;
 };
 \f
+/*
+  Static declarations.
+*/
+static const char
+  *MinimalThresholdMap =
+    "<?xml version=\"1.0\"?>"
+    "<thresholds>"
+    "  <threshold map=\"threshold\" alias=\"1x1\">"
+    "    <description>Threshold 1x1 (non-dither)</description>"
+    "    <levels width=\"1\" height=\"1\" divisor=\"2\">"
+    "        1"
+    "    </levels>"
+    "  </threshold>"
+    "  <threshold map=\"checks\" alias=\"2x1\">"
+    "    <description>Checkerboard 2x1 (dither)</description>"
+    "    <levels width=\"2\" height=\"2\" divisor=\"3\">"
+    "       1 2"
+    "       2 1"
+    "    </levels>"
+    "  </threshold>"
+    "</thresholds>";
+\f
 /*
   Forward declarations.
 */
@@ -179,13 +203,11 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image,
     Initialize threshold image attributes.
   */
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
-  if ((width % 2) == 0)
-    ThrowImageException(OptionError,"KernelWidthMustBeAnOddNumber");
+  assert(exception->signature == MagickCoreSignature);
   threshold_image=CloneImage(image,image->columns,image->rows,MagickTrue,
     exception);
   if (threshold_image == (Image *) NULL)
@@ -206,21 +228,29 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image,
   threshold_view=AcquireAuthenticCacheView(threshold_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)
+    magick_threads(image,threshold_image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
+    double
+      channel_bias[MaxPixelChannels],
+      channel_sum[MaxPixelChannels];
+
     register const Quantum
-      *restrict p;
+      *magick_restrict p,
+      *magick_restrict pixels;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
+      i,
       x;
 
     ssize_t
-      center;
+      center,
+      u,
+      v;
 
     if (status == MagickFalse)
       continue;
@@ -235,63 +265,68 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image,
       }
     center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
       GetPixelChannels(image)*(width/2);
-    for (x=0; x < (ssize_t) image->columns; x++)
+    for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
     {
-      register ssize_t
-        i;
-
-      if (GetPixelMask(image,p) != 0)
+      PixelChannel channel=GetPixelChannelChannel(image,i);
+      PixelTrait traits=GetPixelChannelTraits(image,channel);
+      PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
+        channel);
+      if ((traits == UndefinedPixelTrait) ||
+          (threshold_traits == UndefinedPixelTrait))
+        continue;
+      if (((threshold_traits & CopyPixelTrait) != 0) ||
+          (GetPixelWriteMask(image,p) == 0))
         {
-          p+=GetPixelChannels(image);
-          q+=GetPixelChannels(threshold_image);
+          SetPixelChannel(threshold_image,channel,p[center+i],q);
           continue;
         }
+      pixels=p;
+      channel_bias[channel]=0.0;
+      channel_sum[channel]=0.0;
+      for (v=0; v < (ssize_t) height; v++)
+      {
+        for (u=0; u < (ssize_t) width; u++)
+        {
+          if (u == (ssize_t) (width-1))
+            channel_bias[channel]+=pixels[i];
+          channel_sum[channel]+=pixels[i];
+          pixels+=GetPixelChannels(image);
+        }
+        pixels+=GetPixelChannels(image)*image->columns;
+      }
+    }
+    for (x=0; x < (ssize_t) image->columns; x++)
+    {
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        MagickRealType
-          mean,
-          pixel;
-
-        PixelChannel
-          channel;
-
-        PixelTrait
-          threshold_traits,
-          traits;
-
-        register const Quantum
-          *restrict pixels;
+        double
+          mean;
 
-        register ssize_t
-          u;
-
-        ssize_t
-          v;
-
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
-        threshold_traits=GetPixelChannelMapTraits(threshold_image,channel);
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
+        PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
+          channel);
         if ((traits == UndefinedPixelTrait) ||
             (threshold_traits == UndefinedPixelTrait))
           continue;
-        if ((threshold_traits & CopyPixelTrait) != 0)
+        if (((threshold_traits & CopyPixelTrait) != 0) ||
+            (GetPixelWriteMask(image,p) == 0))
           {
             SetPixelChannel(threshold_image,channel,p[center+i],q);
             continue;
           }
+        channel_sum[channel]-=channel_bias[channel];
+        channel_bias[channel]=0.0;
         pixels=p;
-        pixel=0.0;
         for (v=0; v < (ssize_t) height; v++)
         {
-          for (u=0; u < (ssize_t) width; u++)
-          {
-            pixel+=pixels[i];
-            pixels+=GetPixelChannels(image);
-          }
-          pixels+=image->columns*GetPixelChannels(image);
+          channel_bias[channel]+=pixels[i];
+          pixels+=(width-1)*GetPixelChannels(image);
+          channel_sum[channel]+=pixels[i];
+          pixels+=GetPixelChannels(image)*(image->columns+1);
         }
-        mean=(MagickRealType) (pixel/number_pixels+bias);
-        SetPixelChannel(threshold_image,channel,(Quantum) ((MagickRealType)
+        mean=(double) (channel_sum[channel]/number_pixels+bias);
+        SetPixelChannel(threshold_image,channel,(Quantum) ((double)
           p[center+i] <= mean ? 0 : QuantumRange),q);
       }
       p+=GetPixelChannels(image);
@@ -326,6 +361,407 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image,
 %                                                                             %
 %                                                                             %
 %                                                                             %
+%     A u t o T h r e s o l d I m a g e                                       %
+%                                                                             %
+%                                                                             %
+%                                                                             %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%  AutoThresholdImage() automatically selects a threshold and replaces each
+%  pixel in the image with a black pixel if the image intentsity is less than
+%  the selected threshold otherwise white.
+%
+%  The format of the AutoThresholdImage method is:
+%
+%      MagickBooleanType AutoThresholdImage(Image *image,
+%        const AutoThresholdMethod method,ExceptionInfo *exception)
+%
+%  A description of each parameter follows:
+%
+%    o image: The image to auto-threshold.
+%
+%    o method: choose from Kapur, OTSU, or Triangle.
+%
+%    o exception: return any errors or warnings in this structure.
+%
+*/
+
+static double KapurThreshold(const Image *image,const double *histogram,
+  ExceptionInfo *exception)
+{
+#define MaxIntensity  255
+
+  double
+    *black_entropy,
+    *cumulative_histogram,
+    entropy,
+    epsilon,
+    maximum_entropy,
+    *white_entropy;
+
+  register ssize_t
+    i,
+    j;
+
+  size_t
+    threshold;
+
+  /*
+    Compute optimal threshold from the entopy of the histogram.
+  */
+  cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
+    sizeof(*cumulative_histogram));
+  black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
+    sizeof(*black_entropy));
+  white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
+    sizeof(*white_entropy));
+  if ((cumulative_histogram == (double *) NULL) ||
+      (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL))
+    {
+      if (white_entropy != (double *) NULL)
+        white_entropy=(double *) RelinquishMagickMemory(white_entropy);
+      if (black_entropy != (double *) NULL)
+        black_entropy=(double *) RelinquishMagickMemory(black_entropy);
+      if (cumulative_histogram != (double *) NULL)
+        cumulative_histogram=(double *)
+          RelinquishMagickMemory(cumulative_histogram);
+      (void) ThrowMagickException(exception,GetMagickModule(),
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
+      return(-1.0);
+    }
+   /*
+     Entropy for black and white parts of the histogram.
+   */
+   cumulative_histogram[0]=histogram[0];
+   for (i=1; i <= MaxIntensity; i++)
+     cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i];
+   epsilon=MagickMinimumValue;
+   for (j=0; j <= MaxIntensity; j++)
+   {
+     /*
+       Black entropy.
+     */
+     black_entropy[j]=0.0;
+     if (cumulative_histogram[j] > epsilon)
+       {
+         entropy=0.0;
+         for (i=0; i <= j; i++)
+           if (histogram[i] > epsilon)
+             entropy-=histogram[i]/cumulative_histogram[j]*
+               log(histogram[i]/cumulative_histogram[j]);
+         black_entropy[j]=entropy;
+       }
+     /*
+       White entropy.
+     */
+     white_entropy[j]=0.0;
+     if ((1.0-cumulative_histogram[j]) > epsilon)
+       {
+         entropy=0.0;
+         for (i=j+1; i <= MaxIntensity; i++)
+           if (histogram[i] > epsilon)
+             entropy-=histogram[i]/(1.0-cumulative_histogram[j])*
+               log(histogram[i]/(1.0-cumulative_histogram[j]));
+         white_entropy[j]=entropy;
+       }
+   }
+  /*
+    Find histogram bin with maximum entropy.
+  */
+  maximum_entropy=black_entropy[0]+white_entropy[0];
+  threshold=0;
+  for (j=1; j <= MaxIntensity; j++)
+    if ((black_entropy[j]+white_entropy[j]) > maximum_entropy)
+      {
+        maximum_entropy=black_entropy[j]+white_entropy[j];
+        threshold=(ssize_t) j;
+      }
+  /*
+    Free resources.
+  */
+  white_entropy=(double *) RelinquishMagickMemory(white_entropy);
+  black_entropy=(double *) RelinquishMagickMemory(black_entropy);
+  cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram);
+  return(100.0*threshold/MaxIntensity);
+}
+
+static double OTSUThreshold(const Image *image,const double *histogram,
+  ExceptionInfo *exception)
+{
+  double
+    max_sigma,
+    *myu,
+    *omega,
+    *probability,
+    *sigma,
+    threshold;
+
+  register ssize_t
+    i;
+
+  /*
+    Compute optimal threshold from maximization of inter-class variance.
+  */
+  myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu));
+  omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega));
+  probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
+    sizeof(*probability));
+  sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma));
+  if ((myu == (double *) NULL) || (omega == (double *) NULL) ||
+      (probability == (double *) NULL) || (sigma == (double *) NULL))
+    {
+      if (sigma != (double *) NULL)
+        sigma=(double *) RelinquishMagickMemory(sigma);
+      if (probability != (double *) NULL)
+        probability=(double *) RelinquishMagickMemory(probability);
+      if (omega != (double *) NULL)
+        omega=(double *) RelinquishMagickMemory(omega);
+      if (myu != (double *) NULL)
+        myu=(double *) RelinquishMagickMemory(myu);
+      (void) ThrowMagickException(exception,GetMagickModule(),
+        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
+      return(-1.0);
+    }
+  /*
+    Calculate probability density.
+  */
+  for (i=0; i <= (ssize_t) MaxIntensity; i++)
+    probability[i]=histogram[i];
+  /*
+    Generate probability of graylevels and mean value for separation.
+  */
+  omega[0]=probability[0];
+  myu[0]=0.0;
+  for (i=0; i <= (ssize_t) MaxIntensity; i++)
+  {
+    omega[i]=omega[i-1]+probability[i];
+    myu[i]=myu[i-1]+i*probability[i];
+  }
+  /*
+    Sigma maximization: inter-class variance and compute optimal threshold.
+  */
+  threshold=0;
+  max_sigma=0.0;
+  for (i=0; i < (ssize_t) MaxIntensity; i++)
+  {
+    sigma[i]=0.0;
+    if ((omega[i] != 0.0) && (omega[i] != 1.0))
+      sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0-
+        omega[i]));
+    if (sigma[i] > max_sigma)
+      {
+        max_sigma=sigma[i];
+        threshold=(double) i;
+      }
+  }
+  /*
+    Free resources.
+  */
+  myu=(double *) RelinquishMagickMemory(myu);
+  omega=(double *) RelinquishMagickMemory(omega);
+  probability=(double *) RelinquishMagickMemory(probability);
+  sigma=(double *) RelinquishMagickMemory(sigma);
+  return(100.0*threshold/MaxIntensity);
+}
+
+static double TriangleThreshold(const Image *image,const double *histogram,
+  ExceptionInfo *exception)
+{
+  double
+    a,
+    b,
+    c,
+    count,
+    distance,
+    inverse_ratio,
+    max_distance,
+    segment,
+    x1,
+    x2,
+    y1,
+    y2;
+
+  register ssize_t
+    i;
+
+  ssize_t
+    end,
+    max,
+    start,
+    threshold;
+
+  /*
+    Compute optimal threshold with triangle algorithm.
+  */
+  start=0;  /* find start bin, first bin not zero count */
+  for (i=0; i <= (ssize_t) MaxIntensity; i++)
+    if (histogram[i] > 0.0)
+      {
+        start=i;
+        break;
+      }
+  end=0;  /* find end bin, last bin not zero count */
+  for (i=(ssize_t) MaxIntensity; i >= 0; i--)
+    if (histogram[i] > 0.0)
+      {
+        end=i;
+        break;
+      }
+  max=0;  /* find max bin, bin with largest count */
+  count=0.0;
+  for (i=0; i <= (ssize_t) MaxIntensity; i++)
+    if (histogram[i] > count)
+      {
+        max=i;
+        count=histogram[i];
+      }
+  /*
+    Compute threshold at split point.
+  */
+  x1=(double) max;
+  y1=histogram[max];
+  x2=(double) end;
+  if ((max-start) >= (end-max))
+    x2=(double) start;
+  y2=0.0;
+  a=y1-y2;
+  b=x2-x1;
+  c=(-1.0)*(a*x1+b*y1);
+  inverse_ratio=1.0/sqrt(a*a+b*b+c*c);
+  threshold=0;
+  max_distance=0.0;
+  if (x2 == (double) start)
+    for (i=start; i < max; i++)
+    {
+      segment=inverse_ratio*(a*i+b*histogram[i]+c);
+      distance=sqrt(segment*segment);
+      if ((distance > max_distance) && (segment > 0.0))
+        {
+          threshold=i;
+          max_distance=distance;
+        }
+    }
+  else
+    for (i=end; i > max; i--)
+    {
+      segment=inverse_ratio*(a*i+b*histogram[i]+c);
+      distance=sqrt(segment*segment);
+      if ((distance > max_distance) && (segment < 0.0))
+        {
+          threshold=i;
+          max_distance=distance;
+        }
+    }
+  return(100.0*threshold/MaxIntensity);
+}
+
+MagickExport MagickBooleanType AutoThresholdImage(Image *image,
+  const AutoThresholdMethod method,ExceptionInfo *exception)
+{
+  CacheView
+    *image_view;
+
+  char
+    property[MagickPathExtent];
+
+  double
+    gamma,
+    *histogram,
+    sum,
+    threshold;
+
+  MagickBooleanType
+    status;
+
+  register ssize_t
+    i;
+
+  ssize_t
+    y;
+
+  /*
+    Form histogram.
+  */
+  assert(image != (Image *) NULL);
+  assert(image->signature == MagickCoreSignature);
+  if (image->debug != MagickFalse)
+    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
+    sizeof(*histogram));
+  if (histogram == (double *) NULL)
+    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
+      image->filename);
+  status=MagickTrue;
+  (void) ResetMagickMemory(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram));
+  image_view=AcquireVirtualCacheView(image,exception);
+  for (y=0; y < (ssize_t) image->rows; y++)
+  {
+    register const Quantum
+      *magick_restrict p;
+
+    register ssize_t
+      x;
+
+    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
+    if (p == (const Quantum *) NULL)
+      break;
+    for (x=0; x < (ssize_t) image->columns; x++)
+    {
+      double intensity = GetPixelIntensity(image,p);
+      histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++;
+      p+=GetPixelChannels(image);
+    }
+  }
+  image_view=DestroyCacheView(image_view);
+  /*
+    Normalize histogram.
+  */
+  sum=0.0;
+  for (i=0; i <= (ssize_t) MaxIntensity; i++)
+    sum+=histogram[i];
+  gamma=PerceptibleReciprocal(sum);
+  for (i=0; i <= (ssize_t) MaxIntensity; i++)
+    histogram[i]=gamma*histogram[i];
+  /*
+    Discover threshold from histogram.
+  */
+  switch (method)
+  {
+    case KapurThresholdMethod:
+    {
+      threshold=KapurThreshold(image,histogram,exception);
+      break;
+    }
+    case OTSUThresholdMethod:
+    default:
+    {
+      threshold=OTSUThreshold(image,histogram,exception);
+      break;
+    }
+    case TriangleThresholdMethod:
+    {
+      threshold=TriangleThreshold(image,histogram,exception);
+      break;
+    }
+  }
+  histogram=(double *) RelinquishMagickMemory(histogram);
+  if (threshold < 0.0)
+    status=MagickFalse;
+  if (status == MagickFalse)
+    return(MagickFalse);
+  /*
+    Threshold image.
+  */
+  (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold);
+  (void) SetImageProperty(image,"auto-threshold:threshold",property,exception);
+  return(BilevelImage(image,QuantumRange*threshold/100.0,exception));
+}
+\f
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%                                                                             %
+%                                                                             %
+%                                                                             %
 %     B i l e v e l I m a g e                                                 %
 %                                                                             %
 %                                                                             %
@@ -380,11 +816,13 @@ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
     return(MagickFalse);
+  if (IsGrayColorspace(image->colorspace) != MagickFalse)
+    (void) SetImageColorspace(image,sRGBColorspace,exception);
   /*
     Bilevel threshold image.
   */
@@ -392,8 +830,8 @@ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
   progress=0;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,8) shared(progress,status) \
-    dynamic_number_threads(image,image->columns,image->rows,1)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -401,7 +839,7 @@ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
       x;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     if (status == MagickFalse)
       continue;
@@ -413,27 +851,27 @@ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
       }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
+      double
+        pixel;
+
       register ssize_t
         i;
 
-      if (GetPixelMask(image,q) != 0)
+      if (GetPixelWriteMask(image,q) == 0)
         {
           q+=GetPixelChannels(image);
           continue;
         }
+      pixel=GetPixelIntensity(image,q);
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        PixelChannel
-          channel;
-
-        PixelTrait
-          traits;
-
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        q[i]=(Quantum) ((MagickRealType) q[i] <= threshold ? 0 : QuantumRange);
+        if (image->channel_mask != DefaultChannels)
+          pixel=(double) q[i];
+        q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange);
       }
       q+=GetPixelChannels(image);
     }
@@ -513,7 +951,7 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   if (thresholds == (const char *) NULL)
@@ -521,7 +959,7 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
     return(MagickFalse);
   if (IsGrayColorspace(image->colorspace) != MagickFalse)
-    (void) TransformImageColorspace(image,sRGBColorspace,exception);
+    (void) SetImageColorspace(image,sRGBColorspace,exception);
   GetPixelInfo(image,&threshold);
   flags=ParseGeometry(thresholds,&geometry_info);
   threshold.red=geometry_info.rho;
@@ -544,11 +982,11 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
     }
   if ((flags & PercentValue) != 0)
     {
-      threshold.red*=(QuantumRange/100.0);
-      threshold.green*=(QuantumRange/100.0);
-      threshold.blue*=(QuantumRange/100.0);
-      threshold.black*=(QuantumRange/100.0);
-      threshold.alpha*=(QuantumRange/100.0);
+      threshold.red*=(MagickRealType) (QuantumRange/100.0);
+      threshold.green*=(MagickRealType) (QuantumRange/100.0);
+      threshold.blue*=(MagickRealType) (QuantumRange/100.0);
+      threshold.black*=(MagickRealType) (QuantumRange/100.0);
+      threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
     }
   /*
     White threshold image.
@@ -557,8 +995,8 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
   progress=0;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,8) shared(progress,status) \
-    dynamic_number_threads(image,image->columns,image->rows,1)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -566,7 +1004,7 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
       x;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     if (status == MagickFalse)
       continue;
@@ -578,25 +1016,28 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
       }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
-      if (GetPixelMask(image,q) != 0)
+      double
+        pixel;
+
+      register ssize_t
+        i;
+
+      if (GetPixelWriteMask(image,q) == 0)
         {
           q+=GetPixelChannels(image);
           continue;
         }
+      pixel=GetPixelIntensity(image,q);
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        PixelChannel
-          channel;
-
-        PixelTrait
-          traits;
-
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        if ((double) q[i] <= GetPixelInfoChannel(&threshold,channel))
-          q[i]=0;
+        if (image->channel_mask != DefaultChannels)
+          pixel=(double) q[i];
+        if (pixel < GetPixelInfoChannel(&threshold,channel))
+          q[i]=(Quantum) 0;
       }
       q+=GetPixelChannels(image);
     }
@@ -631,7 +1072,9 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  ClampImage() restricts the color range from 0 to the quantum depth.
+%  ClampImage() set each pixel whose value is below zero to zero and any the
+%  pixel whose value is above the quantum range to the quantum range (e.g.
+%  65535) otherwise the pixel value remains unchanged.
 %
 %  The format of the ClampImage method is:
 %
@@ -645,19 +1088,6 @@ MagickExport MagickBooleanType BlackThresholdImage(Image *image,
 %
 */
 
-static inline Quantum ClampToUnsignedQuantum(const Quantum quantum)
-{
-#if defined(MAGICKCORE_HDRI_SUPPORT)
-  if (quantum <= 0)
-    return(0);
-  if (quantum >= QuantumRange)
-    return(QuantumRange);
-  return(quantum);
-#else
-  return(quantum);
-#endif
-}
-
 MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
 {
 #define ClampImageTag  "Clamp/Image"
@@ -675,7 +1105,7 @@ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   if (image->storage_class == PseudoClass)
@@ -684,15 +1114,15 @@ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
         i;
 
       register PixelInfo
-        *restrict q;
+        *magick_restrict q;
 
       q=image->colormap;
       for (i=0; i < (ssize_t) image->colors; i++)
       {
-        q->red=(double) ClampToUnsignedQuantum(ClampToQuantum(q->red));
-        q->green=(double) ClampToUnsignedQuantum(ClampToQuantum(q->green));
-        q->blue=(double) ClampToUnsignedQuantum(ClampToQuantum(q->blue));
-        q->alpha=(double) ClampToUnsignedQuantum(ClampToQuantum(q->alpha));
+        q->red=(double) ClampPixel(q->red);
+        q->green=(double) ClampPixel(q->green);
+        q->blue=(double) ClampPixel(q->blue);
+        q->alpha=(double) ClampPixel(q->alpha);
         q++;
       }
       return(SyncImage(image,exception));
@@ -704,8 +1134,8 @@ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
   progress=0;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,8) shared(progress,status) \
-    dynamic_number_threads(image,image->columns,image->rows,1)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -713,7 +1143,7 @@ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
       x;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     if (status == MagickFalse)
       continue;
@@ -728,24 +1158,18 @@ MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
       register ssize_t
         i;
 
-      if (GetPixelMask(image,q) != 0)
+      if (GetPixelWriteMask(image,q) == 0)
         {
           q+=GetPixelChannels(image);
           continue;
         }
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        PixelChannel
-          channel;
-
-        PixelTrait
-          traits;
-
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
-        if (traits == UndefinedPixelTrait)
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
+        if ((traits & UpdatePixelTrait) == 0)
           continue;
-        q[i]=ClampToUnsignedQuantum(q[i]);
+        q[i]=ClampPixel((MagickRealType) q[i]);
       }
       q+=GetPixelChannels(image);
     }
@@ -832,22 +1256,33 @@ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
 MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
   ExceptionInfo *exception)
 {
-  const StringInfo
-    *option;
-
-  LinkedListInfo
-    *options;
-
   ThresholdMap
     *map;
 
-  map=(ThresholdMap *)NULL;
-  options=GetConfigureOptions(ThresholdsFilename,exception);
-  while ((option=(const StringInfo *) GetNextValueInLinkedList(options)) !=
-         (const StringInfo *) NULL && (map == (ThresholdMap *) NULL))
-    map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
-      GetStringInfoPath(option),map_id,exception);
-  options=DestroyConfigureOptions(options);
+  map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
+  if (map != (ThresholdMap *) NULL)
+    return(map);
+#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
+  {
+    const StringInfo
+      *option;
+
+    LinkedListInfo
+      *options;
+
+    options=GetConfigureOptions(ThresholdsFilename,exception);
+    option=(const StringInfo *) GetNextValueInLinkedList(options);
+    while (option != (const StringInfo *) NULL)
+    {
+      map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
+        GetStringInfoPath(option),map_id,exception);
+      if (map != (ThresholdMap *) NULL)
+        break;
+      option=(const StringInfo *) GetNextValueInLinkedList(options);
+    }
+    options=DestroyConfigureOptions(options);
+  }
+#endif
   return(map);
 }
 \f
@@ -881,8 +1316,8 @@ MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
 %    o exception: return any errors or warnings in this structure.
 %
 */
-static ThresholdMap *GetThresholdMapFile(const char *xml,
-  const char *filename,const char *map_id,ExceptionInfo *exception)
+static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename,
+  const char *map_id,ExceptionInfo *exception)
 {
   char
     *p;
@@ -924,7 +1359,10 @@ static ThresholdMap *GetThresholdMapFile(const char *xml,
       break;
   }
   if (threshold == (XMLTreeInfo *) NULL)
-    return(map);
+    {
+      thresholds=DestroyXMLTree(thresholds);
+      return(map);
+    }
   description=GetXMLTreeChild(threshold,"description");
   if (description == (XMLTreeInfo *) NULL)
     {
@@ -1099,12 +1537,12 @@ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
     *threshold,
     *thresholds;
 
-  assert( xml != (char *)NULL );
-  assert( file != (FILE *)NULL );
+  assert( xml != (char *) NULL );
+  assert( file != (FILE *) NULL );
   (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
     "Loading threshold map file \"%s\" ...",filename);
   thresholds=NewXMLTree(xml,exception);
-  if ( thresholds == (XMLTreeInfo *)NULL )
+  if ( thresholds == (XMLTreeInfo *) NULL )
     return(MagickFalse);
   (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
   (void) FormatLocaleFile(file,
@@ -1182,18 +1620,19 @@ MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
   MagickStatusType
     status;
 
-  status=MagickFalse;
+  status=MagickTrue;
   if (file == (FILE *) NULL)
     file=stdout;
   options=GetConfigureOptions(ThresholdsFilename,exception);
   (void) FormatLocaleFile(file,
     "\n   Threshold Maps for Ordered Dither Operations\n");
-  while ((option=(const StringInfo *) GetNextValueInLinkedList(options)) !=
-         (const StringInfo *) NULL)
+  option=(const StringInfo *) GetNextValueInLinkedList(options);
+  while (option != (const StringInfo *) NULL)
   {
-    (void) FormatLocaleFile(file,"\nPATH: %s\n\n",GetStringInfoPath(option));
-    status|=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
+    (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
+    status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
       GetStringInfoPath(option),exception);
+    option=(const StringInfo *) GetNextValueInLinkedList(options);
   }
   options=DestroyConfigureOptions(options);
   return(status != 0 ? MagickTrue : MagickFalse);
@@ -1204,20 +1643,20 @@ MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
 %                                                                             %
 %                                                                             %
 %                                                                             %
-%     O r d e r e d P o s t e r i z e I m a g e                               %
+%     O r d e r e d D i t h e r I m a g e                                     %
 %                                                                             %
 %                                                                             %
 %                                                                             %
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %
-%  OrderedPosterizeImage() will perform a ordered dither based on a number
+%  OrderedDitherImage() will perform a ordered dither based on a number
 %  of pre-defined dithering threshold maps, but over multiple intensity
 %  levels, which can be different for different channels, according to the
 %  input argument.
 %
-%  The format of the OrderedPosterizeImage method is:
+%  The format of the OrderedDitherImage method is:
 %
-%      MagickBooleanType OrderedPosterizeImage(Image *image,
+%      MagickBooleanType OrderedDitherImage(Image *image,
 %        const char *threshold_map,ExceptionInfo *exception)
 %
 %  A description of each parameter follows:
@@ -1246,7 +1685,7 @@ MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
 %    o exception: return any errors or warnings in this structure.
 %
 */
-MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
+MagickExport MagickBooleanType OrderedDitherImage(Image *image,
   const char *threshold_map,ExceptionInfo *exception)
 {
 #define DitherImageTag  "Dither/Image"
@@ -1255,20 +1694,20 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
     *image_view;
 
   char
-    token[MaxTextExtent];
+    token[MagickPathExtent];
 
   const char
     *p;
 
+  double
+    levels[CompositePixelChannel];
+
   MagickBooleanType
     status;
 
   MagickOffsetType
     progress;
 
-  MagickRealType
-    levels[CompositePixelChannel];
-
   register ssize_t
     i;
 
@@ -1279,11 +1718,11 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
     *map;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
+  assert(exception->signature == MagickCoreSignature);
   if (threshold_map == (const char *) NULL)
     return(MagickTrue);
   p=(char *) threshold_map;
@@ -1294,7 +1733,7 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
   while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
          (*p != '\0'))
   {
-    if ((p-threshold_map) >= (MaxTextExtent-1))
+    if ((p-threshold_map) >= (MagickPathExtent-1))
       break;
     token[p-threshold_map]=(*p);
     p++;
@@ -1311,12 +1750,17 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
     levels[i]=2.0;
   p=strchr((char *) threshold_map,',');
   if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0))
-    for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++)
     {
-      GetMagickToken(p,&p,token);
-      if (*token == ',')
-        GetMagickToken(p,&p,token);
-      levels[i]=StringToDouble(token,(char **) NULL);
+      GetNextToken(p,&p,MagickPathExtent,token);
+      for (i=0; (i < MaxPixelChannels); i++)
+        levels[i]=StringToDouble(token,(char **) NULL);
+      for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++)
+      {
+        GetNextToken(p,&p,MagickPathExtent,token);
+        if (*token == ',')
+          GetNextToken(p,&p,MagickPathExtent,token);
+        levels[i]=StringToDouble(token,(char **) NULL);
+      }
     }
   for (i=0; i < MaxPixelChannels; i++)
     if (fabs(levels[i]) >= 1)
@@ -1327,8 +1771,8 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
   progress=0;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,8) shared(progress,status) \
-    dynamic_number_threads(image,image->columns,image->rows,1)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1336,7 +1780,7 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
       x;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     if (status == MagickFalse)
       continue;
@@ -1355,33 +1799,30 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
         n;
 
       n=0;
-      if (GetPixelMask(image,q) != 0)
+      if (GetPixelWriteMask(image,q) == 0)
         {
           q+=GetPixelChannels(image);
           continue;
         }
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        PixelChannel
-          channel;
-
-        PixelTrait
-          traits;
-
         ssize_t
           level,
           threshold;
 
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        if (fabs(levels[n++]) < MagickEpsilon)
-          continue;
+        if (fabs(levels[n]) < MagickEpsilon)
+          {
+            n++;
+            continue;
+          }
         threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1));
         level=threshold/(map->divisor-1);
         threshold-=level*(map->divisor-1);
-        q[i]=RoundToQuantum((MagickRealType) (level+(threshold >=
+        q[i]=ClampToQuantum((double) (level+(threshold >=
           map->levels[(x % map->width)+map->width*(y % map->height)]))*
           QuantumRange/levels[n]);
         n++;
@@ -1396,7 +1837,7 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
           proceed;
 
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-        #pragma omp critical (MagickCore_OrderedPosterizeImage)
+        #pragma omp critical (MagickCore_OrderedDitherImage)
 #endif
         proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows);
         if (proceed == MagickFalse)
@@ -1413,6 +1854,157 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
 %                                                                             %
 %                                                                             %
 %                                                                             %
+%     P e r c e p t i b l e I m a g e                                         %
+%                                                                             %
+%                                                                             %
+%                                                                             %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%  PerceptibleImage() set each pixel whose value is less than |epsilon| to
+%  epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
+%  unchanged.
+%
+%  The format of the PerceptibleImage method is:
+%
+%      MagickBooleanType PerceptibleImage(Image *image,const double epsilon,
+%        ExceptionInfo *exception)
+%
+%  A description of each parameter follows:
+%
+%    o image: the image.
+%
+%    o epsilon: the epsilon threshold (e.g. 1.0e-9).
+%
+%    o exception: return any errors or warnings in this structure.
+%
+*/
+
+static inline Quantum PerceptibleThreshold(const Quantum quantum,
+  const double epsilon)
+{
+  double
+    sign;
+
+  sign=(double) quantum < 0.0 ? -1.0 : 1.0;
+  if ((sign*quantum) >= epsilon)
+    return(quantum);
+  return((Quantum) (sign*epsilon));
+}
+
+MagickExport MagickBooleanType PerceptibleImage(Image *image,
+  const double epsilon,ExceptionInfo *exception)
+{
+#define PerceptibleImageTag  "Perceptible/Image"
+
+  CacheView
+    *image_view;
+
+  MagickBooleanType
+    status;
+
+  MagickOffsetType
+    progress;
+
+  ssize_t
+    y;
+
+  assert(image != (Image *) NULL);
+  assert(image->signature == MagickCoreSignature);
+  if (image->debug != MagickFalse)
+    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+  if (image->storage_class == PseudoClass)
+    {
+      register ssize_t
+        i;
+
+      register PixelInfo
+        *magick_restrict q;
+
+      q=image->colormap;
+      for (i=0; i < (ssize_t) image->colors; i++)
+      {
+        q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red),
+          epsilon);
+        q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green),
+          epsilon);
+        q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue),
+          epsilon);
+        q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha),
+          epsilon);
+        q++;
+      }
+      return(SyncImage(image,exception));
+    }
+  /*
+    Perceptible image.
+  */
+  status=MagickTrue;
+  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)
+#endif
+  for (y=0; y < (ssize_t) image->rows; y++)
+  {
+    register ssize_t
+      x;
+
+    register Quantum
+      *magick_restrict q;
+
+    if (status == MagickFalse)
+      continue;
+    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
+    if (q == (Quantum *) NULL)
+      {
+        status=MagickFalse;
+        continue;
+      }
+    for (x=0; x < (ssize_t) image->columns; x++)
+    {
+      register ssize_t
+        i;
+
+      if (GetPixelWriteMask(image,q) == 0)
+        {
+          q+=GetPixelChannels(image);
+          continue;
+        }
+      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
+      {
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
+        if (traits == UndefinedPixelTrait)
+          continue;
+        q[i]=PerceptibleThreshold(q[i],epsilon);
+      }
+      q+=GetPixelChannels(image);
+    }
+    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
+      status=MagickFalse;
+    if (image->progress_monitor != (MagickProgressMonitor) NULL)
+      {
+        MagickBooleanType
+          proceed;
+
+#if defined(MAGICKCORE_OPENMP_SUPPORT)
+        #pragma omp critical (MagickCore_PerceptibleImage)
+#endif
+        proceed=SetImageProgress(image,PerceptibleImageTag,progress++,image->rows);
+        if (proceed == MagickFalse)
+          status=MagickFalse;
+      }
+  }
+  image_view=DestroyCacheView(image_view);
+  return(status);
+}
+\f
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%                                                                             %
+%                                                                             %
+%                                                                             %
 %     R a n d o m T h r e s h o l d I m a g e                                 %
 %                                                                             %
 %                                                                             %
@@ -1432,27 +2024,20 @@ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
 %
 %    o image: the image.
 %
-%    o thresholds: a geometry string containing low,high thresholds.  If the
-%      string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4
-%      is performed instead.
+%    o low,high: Specify the high and low thresholds. These values range from
+%      0 to QuantumRange.
 %
 %    o exception: return any errors or warnings in this structure.
 %
 */
 MagickExport MagickBooleanType RandomThresholdImage(Image *image,
-  const char *thresholds,ExceptionInfo *exception)
+  const double min_threshold, const double max_threshold,ExceptionInfo *exception)
 {
 #define ThresholdImageTag  "Threshold/Image"
 
   CacheView
     *image_view;
 
-  GeometryInfo
-    geometry_info;
-
-  MagickStatusType
-    flags;
-
   MagickBooleanType
     status;
 
@@ -1462,53 +2047,37 @@ MagickExport MagickBooleanType RandomThresholdImage(Image *image,
   PixelInfo
     threshold;
 
-  MagickRealType
-    min_threshold,
-    max_threshold;
-
   RandomInfo
-    **restrict random_info;
+    **magick_restrict random_info;
 
   ssize_t
     y;
 
+#if defined(MAGICKCORE_OPENMP_SUPPORT)
   unsigned long
     key;
+#endif
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   assert(exception != (ExceptionInfo *) NULL);
-  assert(exception->signature == MagickSignature);
-  if (thresholds == (const char *) NULL)
-    return(MagickTrue);
+  assert(exception->signature == MagickCoreSignature);
   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
     return(MagickFalse);
   GetPixelInfo(image,&threshold);
-  min_threshold=0.0;
-  max_threshold=(MagickRealType) QuantumRange;
-  flags=ParseGeometry(thresholds,&geometry_info);
-  min_threshold=geometry_info.rho;
-  max_threshold=geometry_info.sigma;
-  if ((flags & SigmaValue) == 0)
-    max_threshold=min_threshold;
-  if (strchr(thresholds,'%') != (char *) NULL)
-    {
-      max_threshold*=(MagickRealType) (0.01*QuantumRange);
-      min_threshold*=(MagickRealType) (0.01*QuantumRange);
-    }
   /*
     Random threshold image.
   */
   status=MagickTrue;
   progress=0;
   random_info=AcquireRandomInfoThreadSet();
-  key=GetRandomSecretKey(random_info[0]);
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,8) shared(progress,status) \
-    dynamic_number_threads(image,image->columns,image->rows,key == ~0UL)
+  key=GetRandomSecretKey(random_info[0]);
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,key == ~0UL)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1516,7 +2085,7 @@ MagickExport MagickBooleanType RandomThresholdImage(Image *image,
       id = GetOpenMPThreadId();
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     register ssize_t
       x;
@@ -1534,36 +2103,29 @@ MagickExport MagickBooleanType RandomThresholdImage(Image *image,
       register ssize_t
         i;
 
-      if (GetPixelMask(image,q) != 0)
+      if (GetPixelWriteMask(image,q) == 0)
         {
           q+=GetPixelChannels(image);
           continue;
         }
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        MagickRealType
+        double
           threshold;
 
-        PixelChannel
-          channel;
-
-        PixelTrait
-          traits;
-
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        if ((MagickRealType) q[i] < min_threshold)
+        if ((double) q[i] < min_threshold)
           threshold=min_threshold;
         else
-          if ((MagickRealType) q[i] > max_threshold)
+          if ((double) q[i] > max_threshold)
             threshold=max_threshold;
           else
-            threshold=(MagickRealType) (QuantumRange*
+            threshold=(double) (QuantumRange*
               GetPseudoRandomValue(random_info[id]));
-          q[i]=(Quantum) ((MagickRealType) q[i] <= threshold ? 0 :
-            QuantumRange);
+        q[i]=(double) q[i] <= threshold ? 0 : QuantumRange;
       }
       q+=GetPixelChannels(image);
     }
@@ -1644,7 +2206,7 @@ MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
     y;
 
   assert(image != (Image *) NULL);
-  assert(image->signature == MagickSignature);
+  assert(image->signature == MagickCoreSignature);
   if (image->debug != MagickFalse)
     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
   if (thresholds == (const char *) NULL)
@@ -1675,11 +2237,11 @@ MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
     }
   if ((flags & PercentValue) != 0)
     {
-      threshold.red*=(QuantumRange/100.0);
-      threshold.green*=(QuantumRange/100.0);
-      threshold.blue*=(QuantumRange/100.0);
-      threshold.black*=(QuantumRange/100.0);
-      threshold.alpha*=(QuantumRange/100.0);
+      threshold.red*=(MagickRealType) (QuantumRange/100.0);
+      threshold.green*=(MagickRealType) (QuantumRange/100.0);
+      threshold.blue*=(MagickRealType) (QuantumRange/100.0);
+      threshold.black*=(MagickRealType) (QuantumRange/100.0);
+      threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
     }
   /*
     White threshold image.
@@ -1688,8 +2250,8 @@ MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
   progress=0;
   image_view=AcquireAuthenticCacheView(image,exception);
 #if defined(MAGICKCORE_OPENMP_SUPPORT)
-  #pragma omp parallel for schedule(static,8) shared(progress,status) \
-    dynamic_number_threads(image,image->columns,image->rows,1)
+  #pragma omp parallel for schedule(static,4) shared(progress,status) \
+    magick_threads(image,image,image->rows,1)
 #endif
   for (y=0; y < (ssize_t) image->rows; y++)
   {
@@ -1697,7 +2259,7 @@ MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
       x;
 
     register Quantum
-      *restrict q;
+      *magick_restrict q;
 
     if (status == MagickFalse)
       continue;
@@ -1709,27 +2271,27 @@ MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
       }
     for (x=0; x < (ssize_t) image->columns; x++)
     {
+      double
+        pixel;
+
       register ssize_t
         i;
 
-      if (GetPixelMask(image,q) != 0)
+      if (GetPixelWriteMask(image,q) == 0)
         {
           q+=GetPixelChannels(image);
           continue;
         }
+      pixel=GetPixelIntensity(image,q);
       for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
       {
-        PixelChannel
-          channel;
-
-        PixelTrait
-          traits;
-
-        channel=GetPixelChannelMapChannel(image,i);
-        traits=GetPixelChannelMapTraits(image,channel);
+        PixelChannel channel=GetPixelChannelChannel(image,i);
+        PixelTrait traits=GetPixelChannelTraits(image,channel);
         if ((traits & UpdatePixelTrait) == 0)
           continue;
-        if ((double) q[i] > GetPixelInfoChannel(&threshold,channel))
+        if (image->channel_mask != DefaultChannels)
+          pixel=(double) q[i];
+        if (pixel > GetPixelInfoChannel(&threshold,channel))
           q[i]=QuantumRange;
       }
       q+=GetPixelChannels(image);