Coverage Report

Created: 2025-06-16 07:00

/src/imagemagick/MagickCore/threshold.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3
%                                                                             %
4
%                                                                             %
5
%                                                                             %
6
%       TTTTT  H   H  RRRR   EEEEE  SSSSS  H   H   OOO   L      DDDD          %
7
%         T    H   H  R   R  E      SS     H   H  O   O  L      D   D         %
8
%         T    HHHHH  RRRR   EEE     SSS   HHHHH  O   O  L      D   D         %
9
%         T    H   H  R R    E         SS  H   H  O   O  L      D   D         %
10
%         T    H   H  R  R   EEEEE  SSSSS  H   H   OOO   LLLLL  DDDD          %
11
%                                                                             %
12
%                                                                             %
13
%                      MagickCore Image Threshold Methods                     %
14
%                                                                             %
15
%                               Software Design                               %
16
%                                    Cristy                                   %
17
%                                 October 1996                                %
18
%                                                                             %
19
%                                                                             %
20
%  Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization         %
21
%  dedicated to making software imaging solutions freely available.           %
22
%                                                                             %
23
%  You may not use this file except in compliance with the License.  You may  %
24
%  obtain a copy of the License at                                            %
25
%                                                                             %
26
%    https://imagemagick.org/script/license.php                               %
27
%                                                                             %
28
%  Unless required by applicable law or agreed to in writing, software        %
29
%  distributed under the License is distributed on an "AS IS" BASIS,          %
30
%  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31
%  See the License for the specific language governing permissions and        %
32
%  limitations under the License.                                             %
33
%                                                                             %
34
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35
%
36
%
37
%
38
*/
39

40
/*
41
  Include declarations.
42
*/
43
#include "MagickCore/studio.h"
44
#include "MagickCore/artifact.h"
45
#include "MagickCore/blob.h"
46
#include "MagickCore/cache-view.h"
47
#include "MagickCore/color.h"
48
#include "MagickCore/color-private.h"
49
#include "MagickCore/colormap.h"
50
#include "MagickCore/colorspace.h"
51
#include "MagickCore/colorspace-private.h"
52
#include "MagickCore/configure.h"
53
#include "MagickCore/constitute.h"
54
#include "MagickCore/decorate.h"
55
#include "MagickCore/draw.h"
56
#include "MagickCore/enhance.h"
57
#include "MagickCore/exception.h"
58
#include "MagickCore/exception-private.h"
59
#include "MagickCore/effect.h"
60
#include "MagickCore/fx.h"
61
#include "MagickCore/gem.h"
62
#include "MagickCore/gem-private.h"
63
#include "MagickCore/geometry.h"
64
#include "MagickCore/image-private.h"
65
#include "MagickCore/list.h"
66
#include "MagickCore/log.h"
67
#include "MagickCore/memory_.h"
68
#include "MagickCore/monitor.h"
69
#include "MagickCore/monitor-private.h"
70
#include "MagickCore/montage.h"
71
#include "MagickCore/option.h"
72
#include "MagickCore/pixel-accessor.h"
73
#include "MagickCore/property.h"
74
#include "MagickCore/quantize.h"
75
#include "MagickCore/quantum.h"
76
#include "MagickCore/quantum-private.h"
77
#include "MagickCore/random_.h"
78
#include "MagickCore/random-private.h"
79
#include "MagickCore/resize.h"
80
#include "MagickCore/resource_.h"
81
#include "MagickCore/segment.h"
82
#include "MagickCore/shear.h"
83
#include "MagickCore/signature-private.h"
84
#include "MagickCore/string_.h"
85
#include "MagickCore/string-private.h"
86
#include "MagickCore/thread-private.h"
87
#include "MagickCore/threshold.h"
88
#include "MagickCore/token.h"
89
#include "MagickCore/transform.h"
90
#include "MagickCore/xml-tree.h"
91
#include "MagickCore/xml-tree-private.h"
92

93
/*
94
  Define declarations.
95
*/
96
0
#define ThresholdsFilename  "thresholds.xml"
97

98
/*
99
  Typedef declarations.
100
*/
101
struct _ThresholdMap
102
{
103
  char
104
    *map_id,
105
    *description;
106
107
  size_t
108
    width,
109
    height;
110
111
  ssize_t
112
    divisor,
113
    *levels;
114
};
115

116
/*
117
  Static declarations.
118
*/
119
#if MAGICKCORE_ZERO_CONFIGURATION_SUPPORT
120
  #include "MagickCore/threshold-map.h"
121
#else
122
static const char *const
123
  BuiltinMap=
124
    "<?xml version=\"1.0\"?>"
125
    "<thresholds>"
126
    "  <threshold map=\"threshold\" alias=\"1x1\">"
127
    "    <description>Threshold 1x1 (non-dither)</description>"
128
    "    <levels width=\"1\" height=\"1\" divisor=\"2\">"
129
    "        1"
130
    "    </levels>"
131
    "  </threshold>"
132
    "  <threshold map=\"checks\" alias=\"2x1\">"
133
    "    <description>Checkerboard 2x1 (dither)</description>"
134
    "    <levels width=\"2\" height=\"2\" divisor=\"3\">"
135
    "       1 2"
136
    "       2 1"
137
    "    </levels>"
138
    "  </threshold>"
139
    "</thresholds>";
140
#endif
141

142
/*
143
  Forward declarations.
144
*/
145
static ThresholdMap
146
  *GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *);
147

148
/*
149
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
150
%                                                                             %
151
%                                                                             %
152
%                                                                             %
153
%     A d a p t i v e T h r e s h o l d I m a g e                             %
154
%                                                                             %
155
%                                                                             %
156
%                                                                             %
157
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
158
%
159
%  AdaptiveThresholdImage() selects an individual threshold for each pixel
160
%  based on the range of intensity values in its local neighborhood.  This
161
%  allows for thresholding of an image whose global intensity histogram
162
%  doesn't contain distinctive peaks.
163
%
164
%  The format of the AdaptiveThresholdImage method is:
165
%
166
%      Image *AdaptiveThresholdImage(const Image *image,const size_t width,
167
%        const size_t height,const double bias,ExceptionInfo *exception)
168
%
169
%  A description of each parameter follows:
170
%
171
%    o image: the image.
172
%
173
%    o width: the width of the local neighborhood.
174
%
175
%    o height: the height of the local neighborhood.
176
%
177
%    o bias: the mean bias.
178
%
179
%    o exception: return any errors or warnings in this structure.
180
%
181
*/
182
MagickExport Image *AdaptiveThresholdImage(const Image *image,
183
  const size_t width,const size_t height,const double bias,
184
  ExceptionInfo *exception)
185
0
{
186
0
#define AdaptiveThresholdImageTag  "AdaptiveThreshold/Image"
187
188
0
  CacheView
189
0
    *image_view,
190
0
    *threshold_view;
191
192
0
  Image
193
0
    *threshold_image;
194
195
0
  MagickBooleanType
196
0
    status;
197
198
0
  MagickOffsetType
199
0
    progress;
200
201
0
  MagickSizeType
202
0
    number_pixels;
203
204
0
  ssize_t
205
0
    y;
206
207
  /*
208
    Initialize threshold image attributes.
209
  */
210
0
  assert(image != (Image *) NULL);
211
0
  assert(image->signature == MagickCoreSignature);
212
0
  assert(exception != (ExceptionInfo *) NULL);
213
0
  assert(exception->signature == MagickCoreSignature);
214
0
  if (IsEventLogging() != MagickFalse)
215
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
216
0
  threshold_image=CloneImage(image,0,0,MagickTrue,exception);
217
0
  if (threshold_image == (Image *) NULL)
218
0
    return((Image *) NULL);
219
0
  if ((width == 0) || (height == 0))
220
0
    return(threshold_image);
221
0
  status=SetImageStorageClass(threshold_image,DirectClass,exception);
222
0
  if (status == MagickFalse)
223
0
    {
224
0
      threshold_image=DestroyImage(threshold_image);
225
0
      return((Image *) NULL);
226
0
    }
227
  /*
228
    Threshold image.
229
  */
230
0
  status=MagickTrue;
231
0
  progress=0;
232
0
  number_pixels=(MagickSizeType) width*height;
233
0
  image_view=AcquireVirtualCacheView(image,exception);
234
0
  threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
235
#if defined(MAGICKCORE_OPENMP_SUPPORT)
236
  #pragma omp parallel for schedule(static) shared(progress,status) \
237
    magick_number_threads(image,threshold_image,image->rows,1)
238
#endif
239
0
  for (y=0; y < (ssize_t) image->rows; y++)
240
0
  {
241
0
    double
242
0
      channel_bias[MaxPixelChannels],
243
0
      channel_sum[MaxPixelChannels];
244
245
0
    const Quantum
246
0
      *magick_restrict p,
247
0
      *magick_restrict pixels;
248
249
0
    Quantum
250
0
      *magick_restrict q;
251
252
0
    ssize_t
253
0
      center,
254
0
      i,
255
0
      u,
256
0
      v,
257
0
      x;
258
259
0
    if (status == MagickFalse)
260
0
      continue;
261
0
    p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
262
0
      (height/2L),image->columns+width,height,exception);
263
0
    q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
264
0
      1,exception);
265
0
    if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
266
0
      {
267
0
        status=MagickFalse;
268
0
        continue;
269
0
      }
270
0
    center=(ssize_t) GetPixelChannels(image)*((ssize_t) image->columns+
271
0
      (ssize_t) width)*((ssize_t) height/2L)+(ssize_t) GetPixelChannels(image)*
272
0
      ((ssize_t) width/2);
273
0
    for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
274
0
    {
275
0
      PixelChannel channel = GetPixelChannelChannel(image,i);
276
0
      PixelTrait traits = GetPixelChannelTraits(image,channel);
277
0
      PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
278
0
        channel);
279
0
      if ((traits == UndefinedPixelTrait) ||
280
0
          (threshold_traits == UndefinedPixelTrait))
281
0
        continue;
282
0
      if ((threshold_traits & CopyPixelTrait) != 0)
283
0
        {
284
0
          SetPixelChannel(threshold_image,channel,p[center+i],q);
285
0
          continue;
286
0
        }
287
0
      pixels=p;
288
0
      channel_bias[channel]=0.0;
289
0
      channel_sum[channel]=0.0;
290
0
      for (v=0; v < (ssize_t) height; v++)
291
0
      {
292
0
        for (u=0; u < (ssize_t) width; u++)
293
0
        {
294
0
          if (u == (ssize_t) (width-1))
295
0
            channel_bias[channel]+=(double) pixels[i];
296
0
          channel_sum[channel]+=(double) pixels[i];
297
0
          pixels+=(ptrdiff_t) GetPixelChannels(image);
298
0
        }
299
0
        pixels+=(ptrdiff_t) GetPixelChannels(image)*image->columns;
300
0
      }
301
0
    }
302
0
    for (x=0; x < (ssize_t) image->columns; x++)
303
0
    {
304
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
305
0
      {
306
0
        double
307
0
          mean;
308
309
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
310
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
311
0
        PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
312
0
          channel);
313
0
        if ((traits == UndefinedPixelTrait) ||
314
0
            (threshold_traits == UndefinedPixelTrait))
315
0
          continue;
316
0
        if ((threshold_traits & CopyPixelTrait) != 0)
317
0
          {
318
0
            SetPixelChannel(threshold_image,channel,p[center+i],q);
319
0
            continue;
320
0
          }
321
0
        channel_sum[channel]-=channel_bias[channel];
322
0
        channel_bias[channel]=0.0;
323
0
        pixels=p;
324
0
        for (v=0; v < (ssize_t) height; v++)
325
0
        {
326
0
          channel_bias[channel]+=(double) pixels[i];
327
0
          pixels+=(width-1)*GetPixelChannels(image);
328
0
          channel_sum[channel]+=(double) pixels[i];
329
0
          pixels+=(ptrdiff_t) GetPixelChannels(image)*(image->columns+1);
330
0
        }
331
0
        mean=(double) (channel_sum[channel]/number_pixels+bias);
332
0
        SetPixelChannel(threshold_image,channel,(Quantum) ((double)
333
0
          p[center+i] <= mean ? 0 : QuantumRange),q);
334
0
      }
335
0
      p+=(ptrdiff_t) GetPixelChannels(image);
336
0
      q+=(ptrdiff_t) GetPixelChannels(threshold_image);
337
0
    }
338
0
    if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
339
0
      status=MagickFalse;
340
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
341
0
      {
342
0
        MagickBooleanType
343
0
          proceed;
344
345
#if defined(MAGICKCORE_OPENMP_SUPPORT)
346
        #pragma omp atomic
347
#endif
348
0
        progress++;
349
0
        proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
350
0
          image->rows);
351
0
        if (proceed == MagickFalse)
352
0
          status=MagickFalse;
353
0
      }
354
0
  }
355
0
  threshold_image->type=image->type;
356
0
  threshold_view=DestroyCacheView(threshold_view);
357
0
  image_view=DestroyCacheView(image_view);
358
0
  if (status == MagickFalse)
359
0
    threshold_image=DestroyImage(threshold_image);
360
0
  return(threshold_image);
361
0
}
362

363
/*
364
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
365
%                                                                             %
366
%                                                                             %
367
%                                                                             %
368
%     A u t o T h r e s h o l d I m a g e                                     %
369
%                                                                             %
370
%                                                                             %
371
%                                                                             %
372
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
373
%
374
%  AutoThresholdImage()  automatically performs image thresholding
375
%  dependent on which method you specify.
376
%
377
%  The format of the AutoThresholdImage method is:
378
%
379
%      MagickBooleanType AutoThresholdImage(Image *image,
380
%        const AutoThresholdMethod method,ExceptionInfo *exception)
381
%
382
%  A description of each parameter follows:
383
%
384
%    o image: The image to auto-threshold.
385
%
386
%    o method: choose from Kapur, OTSU, or Triangle.
387
%
388
%    o exception: return any errors or warnings in this structure.
389
%
390
*/
391
392
static double KapurThreshold(const Image *image,const double *histogram,
393
  ExceptionInfo *exception)
394
0
{
395
0
#define MaxIntensity  255
396
397
0
  double
398
0
    *black_entropy,
399
0
    *cumulative_histogram,
400
0
    entropy,
401
0
    epsilon,
402
0
    maximum_entropy,
403
0
    *white_entropy;
404
405
0
  ssize_t
406
0
    i,
407
0
    j;
408
409
0
  size_t
410
0
    threshold;
411
412
  /*
413
    Compute optimal threshold from the entropy of the histogram.
414
  */
415
0
  cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
416
0
    sizeof(*cumulative_histogram));
417
0
  black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
418
0
    sizeof(*black_entropy));
419
0
  white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
420
0
    sizeof(*white_entropy));
421
0
  if ((cumulative_histogram == (double *) NULL) ||
422
0
      (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL))
423
0
    {
424
0
      if (white_entropy != (double *) NULL)
425
0
        white_entropy=(double *) RelinquishMagickMemory(white_entropy);
426
0
      if (black_entropy != (double *) NULL)
427
0
        black_entropy=(double *) RelinquishMagickMemory(black_entropy);
428
0
      if (cumulative_histogram != (double *) NULL)
429
0
        cumulative_histogram=(double *)
430
0
          RelinquishMagickMemory(cumulative_histogram);
431
0
      (void) ThrowMagickException(exception,GetMagickModule(),
432
0
        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
433
0
      return(-1.0);
434
0
    }
435
   /*
436
     Entropy for black and white parts of the histogram.
437
   */
438
0
   cumulative_histogram[0]=histogram[0];
439
0
   for (i=1; i <= MaxIntensity; i++)
440
0
     cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i];
441
0
   epsilon=MagickMinimumValue;
442
0
   for (j=0; j <= MaxIntensity; j++)
443
0
   {
444
     /*
445
       Black entropy.
446
     */
447
0
     black_entropy[j]=0.0;
448
0
     if (cumulative_histogram[j] > epsilon)
449
0
       {
450
0
         entropy=0.0;
451
0
         for (i=0; i <= j; i++)
452
0
           if (histogram[i] > epsilon)
453
0
             entropy-=histogram[i]/cumulative_histogram[j]*
454
0
               log(histogram[i]/cumulative_histogram[j]);
455
0
         black_entropy[j]=entropy;
456
0
       }
457
     /*
458
       White entropy.
459
     */
460
0
     white_entropy[j]=0.0;
461
0
     if ((1.0-cumulative_histogram[j]) > epsilon)
462
0
       {
463
0
         entropy=0.0;
464
0
         for (i=j+1; i <= MaxIntensity; i++)
465
0
           if (histogram[i] > epsilon)
466
0
             entropy-=histogram[i]/(1.0-cumulative_histogram[j])*
467
0
               log(histogram[i]/(1.0-cumulative_histogram[j]));
468
0
         white_entropy[j]=entropy;
469
0
       }
470
0
   }
471
  /*
472
    Find histogram bin with maximum entropy.
473
  */
474
0
  maximum_entropy=black_entropy[0]+white_entropy[0];
475
0
  threshold=0;
476
0
  for (j=1; j <= MaxIntensity; j++)
477
0
    if ((black_entropy[j]+white_entropy[j]) > maximum_entropy)
478
0
      {
479
0
        maximum_entropy=black_entropy[j]+white_entropy[j];
480
0
        threshold=(size_t) j;
481
0
      }
482
  /*
483
    Free resources.
484
  */
485
0
  white_entropy=(double *) RelinquishMagickMemory(white_entropy);
486
0
  black_entropy=(double *) RelinquishMagickMemory(black_entropy);
487
0
  cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram);
488
0
  return(100.0*threshold/MaxIntensity);
489
0
}
490
491
static double OTSUThreshold(const Image *image,const double *histogram,
492
  ExceptionInfo *exception)
493
0
{
494
0
  double
495
0
    max_sigma,
496
0
    *myu,
497
0
    *omega,
498
0
    *probability,
499
0
    *sigma,
500
0
    threshold;
501
502
0
  ssize_t
503
0
    i;
504
505
  /*
506
    Compute optimal threshold from maximization of inter-class variance.
507
  */
508
0
  myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu));
509
0
  omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega));
510
0
  probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
511
0
    sizeof(*probability));
512
0
  sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma));
513
0
  if ((myu == (double *) NULL) || (omega == (double *) NULL) ||
514
0
      (probability == (double *) NULL) || (sigma == (double *) NULL))
515
0
    {
516
0
      if (sigma != (double *) NULL)
517
0
        sigma=(double *) RelinquishMagickMemory(sigma);
518
0
      if (probability != (double *) NULL)
519
0
        probability=(double *) RelinquishMagickMemory(probability);
520
0
      if (omega != (double *) NULL)
521
0
        omega=(double *) RelinquishMagickMemory(omega);
522
0
      if (myu != (double *) NULL)
523
0
        myu=(double *) RelinquishMagickMemory(myu);
524
0
      (void) ThrowMagickException(exception,GetMagickModule(),
525
0
        ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
526
0
      return(-1.0);
527
0
    }
528
  /*
529
    Calculate probability density.
530
  */
531
0
  for (i=0; i <= (ssize_t) MaxIntensity; i++)
532
0
    probability[i]=histogram[i];
533
  /*
534
    Generate probability of graylevels and mean value for separation.
535
  */
536
0
  omega[0]=probability[0];
537
0
  myu[0]=0.0;
538
0
  for (i=1; i <= (ssize_t) MaxIntensity; i++)
539
0
  {
540
0
    omega[i]=omega[i-1]+probability[i];
541
0
    myu[i]=myu[i-1]+i*probability[i];
542
0
  }
543
  /*
544
    Sigma maximization: inter-class variance and compute optimal threshold.
545
  */
546
0
  threshold=0;
547
0
  max_sigma=0.0;
548
0
  for (i=0; i < (ssize_t) MaxIntensity; i++)
549
0
  {
550
0
    sigma[i]=0.0;
551
0
    if ((omega[i] != 0.0) && (omega[i] != 1.0))
552
0
      sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0-
553
0
        omega[i]));
554
0
    if (sigma[i] > max_sigma)
555
0
      {
556
0
        max_sigma=sigma[i];
557
0
        threshold=(double) i;
558
0
      }
559
0
  }
560
  /*
561
    Free resources.
562
  */
563
0
  myu=(double *) RelinquishMagickMemory(myu);
564
0
  omega=(double *) RelinquishMagickMemory(omega);
565
0
  probability=(double *) RelinquishMagickMemory(probability);
566
0
  sigma=(double *) RelinquishMagickMemory(sigma);
567
0
  return(100.0*threshold/MaxIntensity);
568
0
}
569
570
static double TriangleThreshold(const double *histogram)
571
0
{
572
0
  double
573
0
    a,
574
0
    b,
575
0
    c,
576
0
    count,
577
0
    distance,
578
0
    inverse_ratio,
579
0
    max_distance,
580
0
    segment,
581
0
    x1,
582
0
    x2,
583
0
    y1,
584
0
    y2;
585
586
0
  ssize_t
587
0
    i;
588
589
0
  ssize_t
590
0
    end,
591
0
    max,
592
0
    start,
593
0
    threshold;
594
595
  /*
596
    Compute optimal threshold with triangle algorithm.
597
  */
598
0
  start=0;  /* find start bin, first bin not zero count */
599
0
  for (i=0; i <= (ssize_t) MaxIntensity; i++)
600
0
    if (histogram[i] > 0.0)
601
0
      {
602
0
        start=i;
603
0
        break;
604
0
      }
605
0
  end=0;  /* find end bin, last bin not zero count */
606
0
  for (i=(ssize_t) MaxIntensity; i >= 0; i--)
607
0
    if (histogram[i] > 0.0)
608
0
      {
609
0
        end=i;
610
0
        break;
611
0
      }
612
0
  max=0;  /* find max bin, bin with largest count */
613
0
  count=0.0;
614
0
  for (i=0; i <= (ssize_t) MaxIntensity; i++)
615
0
    if (histogram[i] > count)
616
0
      {
617
0
        max=i;
618
0
        count=histogram[i];
619
0
      }
620
  /*
621
    Compute threshold at split point.
622
  */
623
0
  x1=(double) max;
624
0
  y1=histogram[max];
625
0
  x2=(double) end;
626
0
  if ((max-start) >= (end-max))
627
0
    x2=(double) start;
628
0
  y2=0.0;
629
0
  a=y1-y2;
630
0
  b=x2-x1;
631
0
  c=(-1.0)*(a*x1+b*y1);
632
0
  inverse_ratio=1.0/sqrt(a*a+b*b+c*c);
633
0
  threshold=0;
634
0
  max_distance=0.0;
635
0
  if (x2 == (double) start)
636
0
    for (i=start; i < max; i++)
637
0
    {
638
0
      segment=inverse_ratio*(a*i+b*histogram[i]+c);
639
0
      distance=sqrt(segment*segment);
640
0
      if ((distance > max_distance) && (segment > 0.0))
641
0
        {
642
0
          threshold=i;
643
0
          max_distance=distance;
644
0
        }
645
0
    }
646
0
  else
647
0
    for (i=end; i > max; i--)
648
0
    {
649
0
      segment=inverse_ratio*(a*i+b*histogram[i]+c);
650
0
      distance=sqrt(segment*segment);
651
0
      if ((distance > max_distance) && (segment < 0.0))
652
0
        {
653
0
          threshold=i;
654
0
          max_distance=distance;
655
0
        }
656
0
    }
657
0
  return(100.0*threshold/MaxIntensity);
658
0
}
659
660
MagickExport MagickBooleanType AutoThresholdImage(Image *image,
661
  const AutoThresholdMethod method,ExceptionInfo *exception)
662
0
{
663
0
  CacheView
664
0
    *image_view;
665
666
0
  char
667
0
    property[MagickPathExtent];
668
669
0
  double
670
0
    gamma,
671
0
    *histogram,
672
0
    sum,
673
0
    threshold;
674
675
0
  MagickBooleanType
676
0
    status;
677
678
0
  ssize_t
679
0
    i;
680
681
0
  ssize_t
682
0
    y;
683
684
  /*
685
    Form histogram.
686
  */
687
0
  assert(image != (Image *) NULL);
688
0
  assert(image->signature == MagickCoreSignature);
689
0
  if (IsEventLogging() != MagickFalse)
690
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
691
0
  histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
692
0
    sizeof(*histogram));
693
0
  if (histogram == (double *) NULL)
694
0
    ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
695
0
      image->filename);
696
0
  status=MagickTrue;
697
0
  (void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram));
698
0
  image_view=AcquireVirtualCacheView(image,exception);
699
0
  for (y=0; y < (ssize_t) image->rows; y++)
700
0
  {
701
0
    const Quantum
702
0
      *magick_restrict p;
703
704
0
    ssize_t
705
0
      x;
706
707
0
    p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
708
0
    if (p == (const Quantum *) NULL)
709
0
      break;
710
0
    for (x=0; x < (ssize_t) image->columns; x++)
711
0
    {
712
0
      double intensity = GetPixelIntensity(image,p);
713
0
      histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++;
714
0
      p+=(ptrdiff_t) GetPixelChannels(image);
715
0
    }
716
0
  }
717
0
  image_view=DestroyCacheView(image_view);
718
  /*
719
    Normalize histogram.
720
  */
721
0
  sum=0.0;
722
0
  for (i=0; i <= (ssize_t) MaxIntensity; i++)
723
0
    sum+=histogram[i];
724
0
  gamma=MagickSafeReciprocal(sum);
725
0
  for (i=0; i <= (ssize_t) MaxIntensity; i++)
726
0
    histogram[i]=gamma*histogram[i];
727
  /*
728
    Discover threshold from histogram.
729
  */
730
0
  switch (method)
731
0
  {
732
0
    case KapurThresholdMethod:
733
0
    {
734
0
      threshold=KapurThreshold(image,histogram,exception);
735
0
      break;
736
0
    }
737
0
    case OTSUThresholdMethod:
738
0
    default:
739
0
    {
740
0
      threshold=OTSUThreshold(image,histogram,exception);
741
0
      break;
742
0
    }
743
0
    case TriangleThresholdMethod:
744
0
    {
745
0
      threshold=TriangleThreshold(histogram);
746
0
      break;
747
0
    }
748
0
  }
749
0
  histogram=(double *) RelinquishMagickMemory(histogram);
750
0
  if (threshold < 0.0)
751
0
    status=MagickFalse;
752
0
  if (status == MagickFalse)
753
0
    return(MagickFalse);
754
  /*
755
    Threshold image.
756
  */
757
0
  (void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold);
758
0
  (void) SetImageProperty(image,"auto-threshold:threshold",property,exception);
759
0
  if (IsStringTrue(GetImageArtifact(image,"auto-threshold:verbose")) != MagickFalse)
760
0
    (void) FormatLocaleFile(stdout,"%.*g%%\n",GetMagickPrecision(),threshold);
761
0
  return(BilevelImage(image,(double) QuantumRange*threshold/100.0,exception));
762
0
}
763

764
/*
765
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
766
%                                                                             %
767
%                                                                             %
768
%                                                                             %
769
%     B i l e v e l I m a g e                                                 %
770
%                                                                             %
771
%                                                                             %
772
%                                                                             %
773
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
774
%
775
%  BilevelImage() changes the value of individual pixels based on the
776
%  intensity of each pixel channel.  The result is a high-contrast image.
777
%
778
%  More precisely each channel value of the image is 'thresholded' so that if
779
%  it is equal to or less than the given value it is set to zero, while any
780
%  value greater than that give is set to it maximum or QuantumRange.
781
%
782
%  This function is what is used to implement the "-threshold" operator for
783
%  the command line API.
784
%
785
%  If the default channel setting is given the image is thresholded using just
786
%  the gray 'intensity' of the image, rather than the individual channels.
787
%
788
%  The format of the BilevelImage method is:
789
%
790
%      MagickBooleanType BilevelImage(Image *image,const double threshold,
791
%        ExceptionInfo *exception)
792
%
793
%  A description of each parameter follows:
794
%
795
%    o image: the image.
796
%
797
%    o threshold: define the threshold values.
798
%
799
%    o exception: return any errors or warnings in this structure.
800
%
801
%  Aside: You can get the same results as operator using LevelImages()
802
%  with the 'threshold' value for both the black_point and the white_point.
803
%
804
*/
805
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
806
  ExceptionInfo *exception)
807
2.85k
{
808
2.85k
#define ThresholdImageTag  "Threshold/Image"
809
810
2.85k
  CacheView
811
2.85k
    *image_view;
812
813
2.85k
  MagickBooleanType
814
2.85k
    status;
815
816
2.85k
  MagickOffsetType
817
2.85k
    progress;
818
819
2.85k
  ssize_t
820
2.85k
    y;
821
822
2.85k
  assert(image != (Image *) NULL);
823
2.85k
  assert(image->signature == MagickCoreSignature);
824
2.85k
  if (IsEventLogging() != MagickFalse)
825
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
826
2.85k
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
827
0
    return(MagickFalse);
828
2.85k
  if (IsGrayColorspace(image->colorspace) == MagickFalse)
829
628
    (void) SetImageColorspace(image,sRGBColorspace,exception);
830
  /*
831
    Bilevel threshold image.
832
  */
833
2.85k
  status=MagickTrue;
834
2.85k
  progress=0;
835
2.85k
  image_view=AcquireAuthenticCacheView(image,exception);
836
#if defined(MAGICKCORE_OPENMP_SUPPORT)
837
  #pragma omp parallel for schedule(static) shared(progress,status) \
838
    magick_number_threads(image,image,image->rows,2)
839
#endif
840
240k
  for (y=0; y < (ssize_t) image->rows; y++)
841
237k
  {
842
237k
    ssize_t
843
237k
      x;
844
845
237k
    Quantum
846
237k
      *magick_restrict q;
847
848
237k
    if (status == MagickFalse)
849
0
      continue;
850
237k
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
851
237k
    if (q == (Quantum *) NULL)
852
0
      {
853
0
        status=MagickFalse;
854
0
        continue;
855
0
      }
856
92.5M
    for (x=0; x < (ssize_t) image->columns; x++)
857
92.3M
    {
858
92.3M
      double
859
92.3M
        pixel;
860
861
92.3M
      ssize_t
862
92.3M
        i;
863
864
92.3M
      pixel=GetPixelIntensity(image,q);
865
184M
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
866
92.4M
      {
867
92.4M
        PixelChannel channel = GetPixelChannelChannel(image,i);
868
92.4M
        PixelTrait traits = GetPixelChannelTraits(image,channel);
869
92.4M
        if ((traits & UpdatePixelTrait) == 0)
870
135k
          continue;
871
92.3M
        if (image->channel_mask != AllChannels)
872
47.9k
          pixel=(double) q[i];
873
92.3M
        q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange);
874
92.3M
      }
875
92.3M
      q+=(ptrdiff_t) GetPixelChannels(image);
876
92.3M
    }
877
237k
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
878
0
      status=MagickFalse;
879
237k
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
880
0
      {
881
0
        MagickBooleanType
882
0
          proceed;
883
884
#if defined(MAGICKCORE_OPENMP_SUPPORT)
885
        #pragma omp atomic
886
#endif
887
0
        progress++;
888
0
        proceed=SetImageProgress(image,ThresholdImageTag,progress++,
889
0
          image->rows);
890
0
        if (proceed == MagickFalse)
891
0
          status=MagickFalse;
892
0
      }
893
237k
  }
894
2.85k
  image_view=DestroyCacheView(image_view);
895
2.85k
  return(status);
896
2.85k
}
897

898
/*
899
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
900
%                                                                             %
901
%                                                                             %
902
%                                                                             %
903
%     B l a c k T h r e s h o l d I m a g e                                   %
904
%                                                                             %
905
%                                                                             %
906
%                                                                             %
907
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
908
%
909
%  BlackThresholdImage() is like ThresholdImage() but forces all pixels below
910
%  the threshold into black while leaving all pixels at or above the threshold
911
%  unchanged.
912
%
913
%  The format of the BlackThresholdImage method is:
914
%
915
%      MagickBooleanType BlackThresholdImage(Image *image,
916
%        const char *threshold,ExceptionInfo *exception)
917
%
918
%  A description of each parameter follows:
919
%
920
%    o image: the image.
921
%
922
%    o threshold: define the threshold value.
923
%
924
%    o exception: return any errors or warnings in this structure.
925
%
926
*/
927
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
928
  const char *thresholds,ExceptionInfo *exception)
929
0
{
930
0
#define ThresholdImageTag  "Threshold/Image"
931
932
0
  CacheView
933
0
    *image_view;
934
935
0
  GeometryInfo
936
0
    geometry_info;
937
938
0
  MagickBooleanType
939
0
    status;
940
941
0
  MagickOffsetType
942
0
    progress;
943
944
0
  PixelInfo
945
0
    threshold;
946
947
0
  MagickStatusType
948
0
    flags;
949
950
0
  ssize_t
951
0
    y;
952
953
0
  assert(image != (Image *) NULL);
954
0
  assert(image->signature == MagickCoreSignature);
955
0
  if (IsEventLogging() != MagickFalse)
956
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
957
0
  if (thresholds == (const char *) NULL)
958
0
    return(MagickTrue);
959
0
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
960
0
    return(MagickFalse);
961
0
  if (IsGrayColorspace(image->colorspace) != MagickFalse)
962
0
    (void) SetImageColorspace(image,sRGBColorspace,exception);
963
0
  GetPixelInfo(image,&threshold);
964
0
  flags=ParseGeometry(thresholds,&geometry_info);
965
0
  threshold.red=geometry_info.rho;
966
0
  threshold.green=geometry_info.rho;
967
0
  threshold.blue=geometry_info.rho;
968
0
  threshold.black=geometry_info.rho;
969
0
  threshold.alpha=100.0;
970
0
  if ((flags & SigmaValue) != 0)
971
0
    threshold.green=geometry_info.sigma;
972
0
  if ((flags & XiValue) != 0)
973
0
    threshold.blue=geometry_info.xi;
974
0
  if ((flags & PsiValue) != 0)
975
0
    threshold.alpha=geometry_info.psi;
976
0
  if (threshold.colorspace == CMYKColorspace)
977
0
    {
978
0
      if ((flags & PsiValue) != 0)
979
0
        threshold.black=geometry_info.psi;
980
0
      if ((flags & ChiValue) != 0)
981
0
        threshold.alpha=geometry_info.chi;
982
0
    }
983
0
  if ((flags & PercentValue) != 0)
984
0
    {
985
0
      threshold.red*=((MagickRealType) QuantumRange/100.0);
986
0
      threshold.green*=((MagickRealType) QuantumRange/100.0);
987
0
      threshold.blue*=((MagickRealType) QuantumRange/100.0);
988
0
      threshold.black*=((MagickRealType) QuantumRange/100.0);
989
0
      threshold.alpha*=((MagickRealType) QuantumRange/100.0);
990
0
    }
991
  /*
992
    White threshold image.
993
  */
994
0
  status=MagickTrue;
995
0
  progress=0;
996
0
  image_view=AcquireAuthenticCacheView(image,exception);
997
#if defined(MAGICKCORE_OPENMP_SUPPORT)
998
  #pragma omp parallel for schedule(static) shared(progress,status) \
999
    magick_number_threads(image,image,image->rows,2)
1000
#endif
1001
0
  for (y=0; y < (ssize_t) image->rows; y++)
1002
0
  {
1003
0
    ssize_t
1004
0
      x;
1005
1006
0
    Quantum
1007
0
      *magick_restrict q;
1008
1009
0
    if (status == MagickFalse)
1010
0
      continue;
1011
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1012
0
    if (q == (Quantum *) NULL)
1013
0
      {
1014
0
        status=MagickFalse;
1015
0
        continue;
1016
0
      }
1017
0
    for (x=0; x < (ssize_t) image->columns; x++)
1018
0
    {
1019
0
      double
1020
0
        pixel;
1021
1022
0
      ssize_t
1023
0
        i;
1024
1025
0
      pixel=GetPixelIntensity(image,q);
1026
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1027
0
      {
1028
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
1029
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
1030
0
        if ((traits & UpdatePixelTrait) == 0)
1031
0
          continue;
1032
0
        if (image->channel_mask != AllChannels)
1033
0
          pixel=(double) q[i];
1034
0
        if (pixel < GetPixelInfoChannel(&threshold,channel))
1035
0
          q[i]=(Quantum) 0;
1036
0
      }
1037
0
      q+=(ptrdiff_t) GetPixelChannels(image);
1038
0
    }
1039
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1040
0
      status=MagickFalse;
1041
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
1042
0
      {
1043
0
        MagickBooleanType
1044
0
          proceed;
1045
1046
#if defined(MAGICKCORE_OPENMP_SUPPORT)
1047
        #pragma omp atomic
1048
#endif
1049
0
        progress++;
1050
0
        proceed=SetImageProgress(image,ThresholdImageTag,progress,
1051
0
          image->rows);
1052
0
        if (proceed == MagickFalse)
1053
0
          status=MagickFalse;
1054
0
      }
1055
0
  }
1056
0
  image_view=DestroyCacheView(image_view);
1057
0
  return(status);
1058
0
}
1059

1060
/*
1061
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1062
%                                                                             %
1063
%                                                                             %
1064
%                                                                             %
1065
%     C l a m p I m a g e                                                     %
1066
%                                                                             %
1067
%                                                                             %
1068
%                                                                             %
1069
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1070
%
1071
%  ClampImage() set each pixel whose value is below zero to zero and any the
1072
%  pixel whose value is above the quantum range to the quantum range (e.g.
1073
%  65535) otherwise the pixel value remains unchanged.
1074
%
1075
%  The format of the ClampImage method is:
1076
%
1077
%      MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
1078
%
1079
%  A description of each parameter follows:
1080
%
1081
%    o image: the image.
1082
%
1083
%    o exception: return any errors or warnings in this structure.
1084
%
1085
*/
1086
1087
MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
1088
0
{
1089
0
#define ClampImageTag  "Clamp/Image"
1090
1091
0
  CacheView
1092
0
    *image_view;
1093
1094
0
  MagickBooleanType
1095
0
    status;
1096
1097
0
  MagickOffsetType
1098
0
    progress;
1099
1100
0
  ssize_t
1101
0
    y;
1102
1103
0
  assert(image != (Image *) NULL);
1104
0
  assert(image->signature == MagickCoreSignature);
1105
0
  if (IsEventLogging() != MagickFalse)
1106
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1107
0
  if (image->storage_class == PseudoClass)
1108
0
    {
1109
0
      ssize_t
1110
0
        i;
1111
1112
0
      PixelInfo
1113
0
        *magick_restrict q;
1114
1115
0
      q=image->colormap;
1116
0
      for (i=0; i < (ssize_t) image->colors; i++)
1117
0
      {
1118
0
        q->red=(double) ClampPixel(q->red);
1119
0
        q->green=(double) ClampPixel(q->green);
1120
0
        q->blue=(double) ClampPixel(q->blue);
1121
0
        q->alpha=(double) ClampPixel(q->alpha);
1122
0
        q++;
1123
0
      }
1124
0
      return(SyncImage(image,exception));
1125
0
    }
1126
  /*
1127
    Clamp image.
1128
  */
1129
0
  status=MagickTrue;
1130
0
  progress=0;
1131
0
  image_view=AcquireAuthenticCacheView(image,exception);
1132
#if defined(MAGICKCORE_OPENMP_SUPPORT)
1133
  #pragma omp parallel for schedule(static) shared(progress,status) \
1134
    magick_number_threads(image,image,image->rows,2)
1135
#endif
1136
0
  for (y=0; y < (ssize_t) image->rows; y++)
1137
0
  {
1138
0
    ssize_t
1139
0
      x;
1140
1141
0
    Quantum
1142
0
      *magick_restrict q;
1143
1144
0
    if (status == MagickFalse)
1145
0
      continue;
1146
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1147
0
    if (q == (Quantum *) NULL)
1148
0
      {
1149
0
        status=MagickFalse;
1150
0
        continue;
1151
0
      }
1152
0
    for (x=0; x < (ssize_t) image->columns; x++)
1153
0
    {
1154
0
      ssize_t
1155
0
        i;
1156
1157
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1158
0
      {
1159
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
1160
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
1161
0
        if ((traits & UpdatePixelTrait) == 0)
1162
0
          continue;
1163
0
        q[i]=ClampPixel((MagickRealType) q[i]);
1164
0
      }
1165
0
      q+=(ptrdiff_t) GetPixelChannels(image);
1166
0
    }
1167
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1168
0
      status=MagickFalse;
1169
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
1170
0
      {
1171
0
        MagickBooleanType
1172
0
          proceed;
1173
1174
#if defined(MAGICKCORE_OPENMP_SUPPORT)
1175
        #pragma omp atomic
1176
#endif
1177
0
        progress++;
1178
0
        proceed=SetImageProgress(image,ClampImageTag,progress,image->rows);
1179
0
        if (proceed == MagickFalse)
1180
0
          status=MagickFalse;
1181
0
      }
1182
0
  }
1183
0
  image_view=DestroyCacheView(image_view);
1184
0
  return(status);
1185
0
}
1186

1187
/*
1188
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1189
%                                                                             %
1190
%                                                                             %
1191
%                                                                             %
1192
%     C o l o r T h r e s h o l d I m a g e                                   %
1193
%                                                                             %
1194
%                                                                             %
1195
%                                                                             %
1196
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1197
%
1198
%  ColorThresholdImage() forces all pixels in the color range to white
1199
%  otherwise black.
1200
%
1201
%  The format of the ColorThresholdImage method is:
1202
%
1203
%      MagickBooleanType ColorThresholdImage(Image *image,
1204
%        const PixelInfo *start_color,const PixelInfo *stop_color,
1205
%        ExceptionInfo *exception)
1206
%
1207
%  A description of each parameter follows:
1208
%
1209
%    o image: the image.
1210
%
1211
%    o start_color, stop_color: define the start and stop color range.  Any
1212
%      pixel within the range returns white otherwise black.
1213
%
1214
%    o exception: return any errors or warnings in this structure.
1215
%
1216
*/
1217
MagickExport MagickBooleanType ColorThresholdImage(Image *image,
1218
  const PixelInfo *start_color,const PixelInfo *stop_color,
1219
  ExceptionInfo *exception)
1220
0
{
1221
0
#define ThresholdImageTag  "Threshold/Image"
1222
1223
0
  CacheView
1224
0
    *image_view;
1225
1226
0
  const char
1227
0
    *artifact;
1228
1229
0
  IlluminantType
1230
0
    illuminant = D65Illuminant;
1231
1232
0
  MagickBooleanType
1233
0
    status;
1234
1235
0
  MagickOffsetType
1236
0
    progress;
1237
1238
0
  PixelInfo
1239
0
    start,
1240
0
    stop;
1241
1242
0
  ssize_t
1243
0
    y;
1244
1245
  /*
1246
    Color threshold image.
1247
  */
1248
0
  assert(image != (Image *) NULL);
1249
0
  assert(image->signature == MagickCoreSignature);
1250
0
  if (IsEventLogging() != MagickFalse)
1251
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1252
0
  status=AcquireImageColormap(image,2,exception);
1253
0
  if (status == MagickFalse)
1254
0
    return(status);
1255
0
  artifact=GetImageArtifact(image,"color:illuminant");
1256
0
  if (artifact != (const char *) NULL)
1257
0
    {
1258
0
      ssize_t
1259
0
        illuminant_type;
1260
1261
0
      illuminant_type=ParseCommandOption(MagickIlluminantOptions,MagickFalse,
1262
0
        artifact);
1263
0
      if (illuminant_type < 0)
1264
0
        illuminant=UndefinedIlluminant;
1265
0
      else
1266
0
        illuminant=(IlluminantType) illuminant_type;
1267
0
    }
1268
0
  start=(*start_color);
1269
0
  stop=(*stop_color);
1270
0
  switch (image->colorspace)
1271
0
  {
1272
0
    case HCLColorspace:
1273
0
    {
1274
0
      ConvertRGBToHCL(start_color->red,start_color->green,start_color->blue,
1275
0
        &start.red,&start.green,&start.blue);
1276
0
      ConvertRGBToHCL(stop_color->red,stop_color->green,stop_color->blue,
1277
0
        &stop.red,&stop.green,&stop.blue);
1278
0
      break;
1279
0
    }
1280
0
    case HSBColorspace:
1281
0
    {
1282
0
      ConvertRGBToHSB(start_color->red,start_color->green,start_color->blue,
1283
0
        &start.red,&start.green,&start.blue);
1284
0
      ConvertRGBToHSB(stop_color->red,stop_color->green,stop_color->blue,
1285
0
        &stop.red,&stop.green,&stop.blue);
1286
0
      break;
1287
0
    }
1288
0
    case HSLColorspace:
1289
0
    {
1290
0
      ConvertRGBToHSL(start_color->red,start_color->green,start_color->blue,
1291
0
        &start.red,&start.green,&start.blue);
1292
0
      ConvertRGBToHSL(stop_color->red,stop_color->green,stop_color->blue,
1293
0
        &stop.red,&stop.green,&stop.blue);
1294
0
      break;
1295
0
    }
1296
0
    case HSVColorspace:
1297
0
    {
1298
0
      ConvertRGBToHSV(start_color->red,start_color->green,start_color->blue,
1299
0
        &start.red,&start.green,&start.blue);
1300
0
      ConvertRGBToHSV(stop_color->red,stop_color->green,stop_color->blue,
1301
0
        &stop.red,&stop.green,&stop.blue);
1302
0
      break;
1303
0
    }
1304
0
    case HWBColorspace:
1305
0
    {
1306
0
      ConvertRGBToHWB(start_color->red,start_color->green,start_color->blue,
1307
0
        &start.red,&start.green,&start.blue);
1308
0
      ConvertRGBToHWB(stop_color->red,stop_color->green,stop_color->blue,
1309
0
        &stop.red,&stop.green,&stop.blue);
1310
0
      break;
1311
0
    }
1312
0
    case LabColorspace:
1313
0
    {
1314
0
      ConvertRGBToLab(start_color->red,start_color->green,start_color->blue,
1315
0
        illuminant,&start.red,&start.green,&start.blue);
1316
0
      ConvertRGBToLab(stop_color->red,stop_color->green,stop_color->blue,
1317
0
        illuminant,&stop.red,&stop.green,&stop.blue);
1318
0
      break;
1319
0
    }
1320
0
    default:
1321
0
    {
1322
0
      start.red*=QuantumScale;
1323
0
      start.green*=QuantumScale;
1324
0
      start.blue*=QuantumScale;
1325
0
      stop.red*=QuantumScale;
1326
0
      stop.green*=QuantumScale;
1327
0
      stop.blue*=QuantumScale;
1328
0
      break;
1329
0
    }
1330
0
  }
1331
0
  start.red*=(double) QuantumRange;
1332
0
  start.green*=(double) QuantumRange;
1333
0
  start.blue*=(double) QuantumRange;
1334
0
  stop.red*=(double) QuantumRange;
1335
0
  stop.green*=(double) QuantumRange;
1336
0
  stop.blue*=(double) QuantumRange;
1337
0
  progress=0;
1338
0
  image_view=AcquireAuthenticCacheView(image,exception);
1339
#if defined(MAGICKCORE_OPENMP_SUPPORT)
1340
  #pragma omp parallel for schedule(static) shared(progress,status) \
1341
    magick_number_threads(image,image,image->rows,2)
1342
#endif
1343
0
  for (y=0; y < (ssize_t) image->rows; y++)
1344
0
  {
1345
0
    ssize_t
1346
0
      x;
1347
1348
0
    Quantum
1349
0
      *magick_restrict q;
1350
1351
0
    if (status == MagickFalse)
1352
0
      continue;
1353
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1354
0
    if (q == (Quantum *) NULL)
1355
0
      {
1356
0
        status=MagickFalse;
1357
0
        continue;
1358
0
      }
1359
0
    for (x=0; x < (ssize_t) image->columns; x++)
1360
0
    {
1361
0
      MagickBooleanType
1362
0
        foreground = MagickTrue;
1363
1364
0
      ssize_t
1365
0
        i;
1366
1367
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1368
0
      {
1369
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
1370
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
1371
0
        if ((traits & UpdatePixelTrait) == 0)
1372
0
          continue;
1373
0
        if (((double) q[i] < GetPixelInfoChannel(&start,channel)) ||
1374
0
            ((double) q[i] > GetPixelInfoChannel(&stop,channel)))
1375
0
          foreground=MagickFalse;
1376
0
      }
1377
0
      SetPixelIndex(image,(Quantum) (foreground != MagickFalse ? 1 : 0),q);
1378
0
      q+=(ptrdiff_t) GetPixelChannels(image);
1379
0
    }
1380
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1381
0
      status=MagickFalse;
1382
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
1383
0
      {
1384
0
        MagickBooleanType
1385
0
          proceed;
1386
1387
#if defined(MAGICKCORE_OPENMP_SUPPORT)
1388
        #pragma omp atomic
1389
#endif
1390
0
        progress++;
1391
0
        proceed=SetImageProgress(image,ThresholdImageTag,progress,
1392
0
          image->rows);
1393
0
        if (proceed == MagickFalse)
1394
0
          status=MagickFalse;
1395
0
      }
1396
0
  }
1397
0
  image_view=DestroyCacheView(image_view);
1398
0
  image->colorspace=sRGBColorspace;
1399
0
  return(SyncImage(image,exception));
1400
0
}
1401

1402
/*
1403
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1404
%                                                                             %
1405
%                                                                             %
1406
%                                                                             %
1407
%  D e s t r o y T h r e s h o l d M a p                                      %
1408
%                                                                             %
1409
%                                                                             %
1410
%                                                                             %
1411
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1412
%
1413
%  DestroyThresholdMap() de-allocate the given ThresholdMap
1414
%
1415
%  The format of the ListThresholdMaps method is:
1416
%
1417
%      ThresholdMap *DestroyThresholdMap(Threshold *map)
1418
%
1419
%  A description of each parameter follows.
1420
%
1421
%    o map:    Pointer to the Threshold map to destroy
1422
%
1423
*/
1424
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
1425
0
{
1426
0
  assert(map != (ThresholdMap *) NULL);
1427
0
  if (map->map_id != (char *) NULL)
1428
0
    map->map_id=DestroyString(map->map_id);
1429
0
  if (map->description != (char *) NULL)
1430
0
    map->description=DestroyString(map->description);
1431
0
  if (map->levels != (ssize_t *) NULL)
1432
0
    map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
1433
0
  map=(ThresholdMap *) RelinquishMagickMemory(map);
1434
0
  return(map);
1435
0
}
1436

1437
/*
1438
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1439
%                                                                             %
1440
%                                                                             %
1441
%                                                                             %
1442
%  G e t T h r e s h o l d M a p                                              %
1443
%                                                                             %
1444
%                                                                             %
1445
%                                                                             %
1446
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1447
%
1448
%  GetThresholdMap() loads and searches one or more threshold map files for the
1449
%  map matching the given name or alias.
1450
%
1451
%  The format of the GetThresholdMap method is:
1452
%
1453
%      ThresholdMap *GetThresholdMap(const char *map_id,
1454
%        ExceptionInfo *exception)
1455
%
1456
%  A description of each parameter follows.
1457
%
1458
%    o map_id:  ID of the map to look for.
1459
%
1460
%    o exception: return any errors or warnings in this structure.
1461
%
1462
*/
1463
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
1464
  ExceptionInfo *exception)
1465
0
{
1466
0
  ThresholdMap
1467
0
    *map;
1468
1469
0
  map=GetThresholdMapFile(BuiltinMap,"built-in",map_id,exception);
1470
0
  if (map != (ThresholdMap *) NULL)
1471
0
    return(map);
1472
0
#if !MAGICKCORE_ZERO_CONFIGURATION_SUPPORT
1473
0
  {
1474
0
    const StringInfo
1475
0
      *option;
1476
1477
0
    LinkedListInfo
1478
0
      *options;
1479
1480
0
    options=GetConfigureOptions(ThresholdsFilename,exception);
1481
0
    option=(const StringInfo *) GetNextValueInLinkedList(options);
1482
0
    while (option != (const StringInfo *) NULL)
1483
0
    {
1484
0
      map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
1485
0
        GetStringInfoPath(option),map_id,exception);
1486
0
      if (map != (ThresholdMap *) NULL)
1487
0
        break;
1488
0
      option=(const StringInfo *) GetNextValueInLinkedList(options);
1489
0
    }
1490
0
    options=DestroyConfigureOptions(options);
1491
0
  }
1492
0
#endif
1493
0
  return(map);
1494
0
}
1495

1496
/*
1497
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1498
%                                                                             %
1499
%                                                                             %
1500
%                                                                             %
1501
+  G e t T h r e s h o l d M a p F i l e                                      %
1502
%                                                                             %
1503
%                                                                             %
1504
%                                                                             %
1505
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1506
%
1507
%  GetThresholdMapFile() look for a given threshold map name or alias in the
1508
%  given XML file data, and return the allocated the map when found.
1509
%
1510
%  The format of the ListThresholdMaps method is:
1511
%
1512
%      ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
1513
%         const char *map_id,ExceptionInfo *exception)
1514
%
1515
%  A description of each parameter follows.
1516
%
1517
%    o xml:  The threshold map list in XML format.
1518
%
1519
%    o filename:  The threshold map XML filename.
1520
%
1521
%    o map_id:  ID of the map to look for in XML list.
1522
%
1523
%    o exception: return any errors or warnings in this structure.
1524
%
1525
*/
1526
static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename,
1527
  const char *map_id,ExceptionInfo *exception)
1528
0
{
1529
0
  char
1530
0
    *p;
1531
1532
0
  const char
1533
0
    *attribute,
1534
0
    *content;
1535
1536
0
  double
1537
0
    value;
1538
1539
0
  ssize_t
1540
0
    i;
1541
1542
0
  ThresholdMap
1543
0
    *map;
1544
1545
0
  XMLTreeInfo
1546
0
    *description,
1547
0
    *levels,
1548
0
    *threshold,
1549
0
    *thresholds;
1550
1551
0
  (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
1552
0
    "Loading threshold map file \"%s\" ...",filename);
1553
0
  map=(ThresholdMap *) NULL;
1554
0
  thresholds=NewXMLTree(xml,exception);
1555
0
  if (thresholds == (XMLTreeInfo *) NULL)
1556
0
    return(map);
1557
0
  for (threshold=GetXMLTreeChild(thresholds,"threshold");
1558
0
       threshold != (XMLTreeInfo *) NULL;
1559
0
       threshold=GetNextXMLTreeTag(threshold))
1560
0
  {
1561
0
    attribute=GetXMLTreeAttribute(threshold,"map");
1562
0
    if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
1563
0
      break;
1564
0
    attribute=GetXMLTreeAttribute(threshold,"alias");
1565
0
    if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
1566
0
      break;
1567
0
  }
1568
0
  if (threshold == (XMLTreeInfo *) NULL)
1569
0
    {
1570
0
      thresholds=DestroyXMLTree(thresholds);
1571
0
      return(map);
1572
0
    }
1573
0
  description=GetXMLTreeChild(threshold,"description");
1574
0
  if (description == (XMLTreeInfo *) NULL)
1575
0
    {
1576
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1577
0
        "XmlMissingElement", "<description>, map \"%s\"",map_id);
1578
0
      thresholds=DestroyXMLTree(thresholds);
1579
0
      return(map);
1580
0
    }
1581
0
  levels=GetXMLTreeChild(threshold,"levels");
1582
0
  if (levels == (XMLTreeInfo *) NULL)
1583
0
    {
1584
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1585
0
        "XmlMissingElement", "<levels>, map \"%s\"", map_id);
1586
0
      thresholds=DestroyXMLTree(thresholds);
1587
0
      return(map);
1588
0
    }
1589
0
  map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map));
1590
0
  map->map_id=(char *) NULL;
1591
0
  map->description=(char *) NULL;
1592
0
  map->levels=(ssize_t *) NULL;
1593
0
  attribute=GetXMLTreeAttribute(threshold,"map");
1594
0
  if (attribute != (char *) NULL)
1595
0
    map->map_id=ConstantString(attribute);
1596
0
  content=GetXMLTreeContent(description);
1597
0
  if (content != (char *) NULL)
1598
0
    map->description=ConstantString(content);
1599
0
  attribute=GetXMLTreeAttribute(levels,"width");
1600
0
  if (attribute == (char *) NULL)
1601
0
    {
1602
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1603
0
        "XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
1604
0
      thresholds=DestroyXMLTree(thresholds);
1605
0
      map=DestroyThresholdMap(map);
1606
0
      return(map);
1607
0
    }
1608
0
  map->width=StringToUnsignedLong(attribute);
1609
0
  if (map->width == 0)
1610
0
    {
1611
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1612
0
       "XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id);
1613
0
      thresholds=DestroyXMLTree(thresholds);
1614
0
      map=DestroyThresholdMap(map);
1615
0
      return(map);
1616
0
    }
1617
0
  attribute=GetXMLTreeAttribute(levels,"height");
1618
0
  if (attribute == (char *) NULL)
1619
0
    {
1620
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1621
0
        "XmlMissingAttribute", "<levels height>, map \"%s\"",map_id);
1622
0
      thresholds=DestroyXMLTree(thresholds);
1623
0
      map=DestroyThresholdMap(map);
1624
0
      return(map);
1625
0
    }
1626
0
  map->height=StringToUnsignedLong(attribute);
1627
0
  if (map->height == 0)
1628
0
    {
1629
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1630
0
        "XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id);
1631
0
      thresholds=DestroyXMLTree(thresholds);
1632
0
      map=DestroyThresholdMap(map);
1633
0
      return(map);
1634
0
    }
1635
0
  attribute=GetXMLTreeAttribute(levels,"divisor");
1636
0
  if (attribute == (char *) NULL)
1637
0
    {
1638
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1639
0
        "XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id);
1640
0
      thresholds=DestroyXMLTree(thresholds);
1641
0
      map=DestroyThresholdMap(map);
1642
0
      return(map);
1643
0
    }
1644
0
  map->divisor=(ssize_t) StringToLong(attribute);
1645
0
  if (map->divisor < 2)
1646
0
    {
1647
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1648
0
        "XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id);
1649
0
      thresholds=DestroyXMLTree(thresholds);
1650
0
      map=DestroyThresholdMap(map);
1651
0
      return(map);
1652
0
    }
1653
0
  content=GetXMLTreeContent(levels);
1654
0
  if (content == (char *) NULL)
1655
0
    {
1656
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1657
0
        "XmlMissingContent", "<levels>, map \"%s\"",map_id);
1658
0
      thresholds=DestroyXMLTree(thresholds);
1659
0
      map=DestroyThresholdMap(map);
1660
0
      return(map);
1661
0
    }
1662
0
  map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
1663
0
    sizeof(*map->levels));
1664
0
  if (map->levels == (ssize_t *) NULL)
1665
0
    ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
1666
0
  for (i=0; i < (ssize_t) (map->width*map->height); i++)
1667
0
  {
1668
0
    map->levels[i]=(ssize_t) strtol(content,&p,10);
1669
0
    if (p == content)
1670
0
      {
1671
0
        (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1672
0
          "XmlInvalidContent", "<level> too few values, map \"%s\"",map_id);
1673
0
        thresholds=DestroyXMLTree(thresholds);
1674
0
        map=DestroyThresholdMap(map);
1675
0
        return(map);
1676
0
      }
1677
0
    if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
1678
0
      {
1679
0
        (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1680
0
          "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
1681
0
          (double) map->levels[i],map_id);
1682
0
        thresholds=DestroyXMLTree(thresholds);
1683
0
        map=DestroyThresholdMap(map);
1684
0
        return(map);
1685
0
      }
1686
0
    content=p;
1687
0
  }
1688
0
  value=(double) strtol(content,&p,10);
1689
0
  (void) value;
1690
0
  if (p != content)
1691
0
    {
1692
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1693
0
        "XmlInvalidContent", "<level> too many values, map \"%s\"",map_id);
1694
0
     thresholds=DestroyXMLTree(thresholds);
1695
0
     map=DestroyThresholdMap(map);
1696
0
     return(map);
1697
0
   }
1698
0
  thresholds=DestroyXMLTree(thresholds);
1699
0
  return(map);
1700
0
}
1701

1702
/*
1703
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1704
%                                                                             %
1705
%                                                                             %
1706
%                                                                             %
1707
+  L i s t T h r e s h o l d M a p F i l e                                    %
1708
%                                                                             %
1709
%                                                                             %
1710
%                                                                             %
1711
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1712
%
1713
%  ListThresholdMapFile() lists the threshold maps and their descriptions
1714
%  in the given XML file data.
1715
%
1716
%  The format of the ListThresholdMaps method is:
1717
%
1718
%      MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
1719
%         const char *filename,ExceptionInfo *exception)
1720
%
1721
%  A description of each parameter follows.
1722
%
1723
%    o file:  An pointer to the output FILE.
1724
%
1725
%    o xml:  The threshold map list in XML format.
1726
%
1727
%    o filename:  The threshold map XML filename.
1728
%
1729
%    o exception: return any errors or warnings in this structure.
1730
%
1731
*/
1732
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
1733
  const char *filename,ExceptionInfo *exception)
1734
0
{
1735
0
  const char
1736
0
    *alias,
1737
0
    *content,
1738
0
    *map;
1739
1740
0
  XMLTreeInfo
1741
0
    *description,
1742
0
    *threshold,
1743
0
    *thresholds;
1744
1745
0
  assert( xml != (char *) NULL );
1746
0
  assert( file != (FILE *) NULL );
1747
0
  (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
1748
0
    "Loading threshold map file \"%s\" ...",filename);
1749
0
  thresholds=NewXMLTree(xml,exception);
1750
0
  if ( thresholds == (XMLTreeInfo *) NULL )
1751
0
    return(MagickFalse);
1752
0
  (void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
1753
0
  (void) FormatLocaleFile(file,
1754
0
    "----------------------------------------------------\n");
1755
0
  threshold=GetXMLTreeChild(thresholds,"threshold");
1756
0
  for ( ; threshold != (XMLTreeInfo *) NULL;
1757
0
          threshold=GetNextXMLTreeTag(threshold))
1758
0
  {
1759
0
    map=GetXMLTreeAttribute(threshold,"map");
1760
0
    if (map == (char *) NULL)
1761
0
      {
1762
0
        (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1763
0
          "XmlMissingAttribute", "<map>");
1764
0
        thresholds=DestroyXMLTree(thresholds);
1765
0
        return(MagickFalse);
1766
0
      }
1767
0
    alias=GetXMLTreeAttribute(threshold,"alias");
1768
0
    description=GetXMLTreeChild(threshold,"description");
1769
0
    if (description == (XMLTreeInfo *) NULL)
1770
0
      {
1771
0
        (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1772
0
          "XmlMissingElement", "<description>, map \"%s\"",map);
1773
0
        thresholds=DestroyXMLTree(thresholds);
1774
0
        return(MagickFalse);
1775
0
      }
1776
0
    content=GetXMLTreeContent(description);
1777
0
    if (content == (char *) NULL)
1778
0
      {
1779
0
        (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1780
0
          "XmlMissingContent", "<description>, map \"%s\"", map);
1781
0
        thresholds=DestroyXMLTree(thresholds);
1782
0
        return(MagickFalse);
1783
0
      }
1784
0
    (void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
1785
0
      content);
1786
0
  }
1787
0
  thresholds=DestroyXMLTree(thresholds);
1788
0
  return(MagickTrue);
1789
0
}
1790

1791
/*
1792
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1793
%                                                                             %
1794
%                                                                             %
1795
%                                                                             %
1796
%  L i s t T h r e s h o l d M a p s                                          %
1797
%                                                                             %
1798
%                                                                             %
1799
%                                                                             %
1800
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1801
%
1802
%  ListThresholdMaps() lists the threshold maps and their descriptions
1803
%  as defined by "threshold.xml" to a file.
1804
%
1805
%  The format of the ListThresholdMaps method is:
1806
%
1807
%      MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
1808
%
1809
%  A description of each parameter follows.
1810
%
1811
%    o file:  An pointer to the output FILE.
1812
%
1813
%    o exception: return any errors or warnings in this structure.
1814
%
1815
*/
1816
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
1817
  ExceptionInfo *exception)
1818
0
{
1819
0
  const StringInfo
1820
0
    *option;
1821
1822
0
  LinkedListInfo
1823
0
    *options;
1824
1825
0
  MagickStatusType
1826
0
    status;
1827
1828
0
  status=MagickTrue;
1829
0
  if (file == (FILE *) NULL)
1830
0
    file=stdout;
1831
0
  options=GetConfigureOptions(ThresholdsFilename,exception);
1832
0
  (void) FormatLocaleFile(file,
1833
0
    "\n   Threshold Maps for Ordered Dither Operations\n");
1834
0
  option=(const StringInfo *) GetNextValueInLinkedList(options);
1835
0
  while (option != (const StringInfo *) NULL)
1836
0
  {
1837
0
    (void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
1838
0
    status&=(MagickStatusType) ListThresholdMapFile(file,(const char *)
1839
0
      GetStringInfoDatum(option),GetStringInfoPath(option),exception);
1840
0
    option=(const StringInfo *) GetNextValueInLinkedList(options);
1841
0
  }
1842
0
  options=DestroyConfigureOptions(options);
1843
0
  return(status != 0 ? MagickTrue : MagickFalse);
1844
0
}
1845

1846
/*
1847
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1848
%                                                                             %
1849
%                                                                             %
1850
%                                                                             %
1851
%     O r d e r e d D i t h e r I m a g e                                     %
1852
%                                                                             %
1853
%                                                                             %
1854
%                                                                             %
1855
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1856
%
1857
%  OrderedDitherImage() will perform a ordered dither based on a number
1858
%  of pre-defined dithering threshold maps, but over multiple intensity
1859
%  levels, which can be different for different channels, according to the
1860
%  input argument.
1861
%
1862
%  The format of the OrderedDitherImage method is:
1863
%
1864
%      MagickBooleanType OrderedDitherImage(Image *image,
1865
%        const char *threshold_map,ExceptionInfo *exception)
1866
%
1867
%  A description of each parameter follows:
1868
%
1869
%    o image: the image.
1870
%
1871
%    o threshold_map: A string containing the name of the threshold dither
1872
%      map to use, followed by zero or more numbers representing the number
1873
%      of color levels to dither between.
1874
%
1875
%      Any level number less than 2 will be equivalent to 2, and means only
1876
%      binary dithering will be applied to each color channel.
1877
%
1878
%      No numbers also means a 2 level (bitmap) dither will be applied to all
1879
%      channels, while a single number is the number of levels applied to each
1880
%      channel in sequence.  More numbers will be applied in turn to each of
1881
%      the color channels.
1882
%
1883
%      For example: "o3x3,6" will generate a 6 level posterization of the
1884
%      image with an ordered 3x3 diffused pixel dither being applied between
1885
%      each level. While checker,8,8,4 will produce a 332 colormaped image
1886
%      with only a single checkerboard hash pattern (50% grey) between each
1887
%      color level, to basically double the number of color levels with
1888
%      a bare minimum of dithering.
1889
%
1890
%    o exception: return any errors or warnings in this structure.
1891
%
1892
*/
1893
MagickExport MagickBooleanType OrderedDitherImage(Image *image,
1894
  const char *threshold_map,ExceptionInfo *exception)
1895
0
{
1896
0
#define DitherImageTag  "Dither/Image"
1897
1898
0
  CacheView
1899
0
    *image_view;
1900
1901
0
  char
1902
0
    token[MagickPathExtent];
1903
1904
0
  const char
1905
0
    *p;
1906
1907
0
  double
1908
0
    levels[CompositePixelChannel];
1909
1910
0
  MagickBooleanType
1911
0
    status;
1912
1913
0
  MagickOffsetType
1914
0
    progress;
1915
1916
0
  ssize_t
1917
0
    i,
1918
0
    y;
1919
1920
0
  ThresholdMap
1921
0
    *map;
1922
1923
0
  assert(image != (Image *) NULL);
1924
0
  assert(image->signature == MagickCoreSignature);
1925
0
  assert(exception != (ExceptionInfo *) NULL);
1926
0
  assert(exception->signature == MagickCoreSignature);
1927
0
  if (IsEventLogging() != MagickFalse)
1928
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1929
0
  if (threshold_map == (const char *) NULL)
1930
0
    return(MagickTrue);
1931
0
  p=(char *) threshold_map;
1932
0
  while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
1933
0
         (*p != '\0'))
1934
0
    p++;
1935
0
  threshold_map=p;
1936
0
  while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
1937
0
         (*p != '\0'))
1938
0
  {
1939
0
    if ((p-threshold_map) >= (MagickPathExtent-1))
1940
0
      break;
1941
0
    token[p-threshold_map]=(*p);
1942
0
    p++;
1943
0
  }
1944
0
  token[p-threshold_map]='\0';
1945
0
  map=GetThresholdMap(token,exception);
1946
0
  if (map == (ThresholdMap *) NULL)
1947
0
    {
1948
0
      (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1949
0
        "InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
1950
0
      return(MagickFalse);
1951
0
    }
1952
0
  for (i=0; i < MaxPixelChannels; i++)
1953
0
    levels[i]=2.0;
1954
0
  p=strchr((char *) threshold_map,',');
1955
0
  if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0))
1956
0
    {
1957
0
      (void) GetNextToken(p,&p,MagickPathExtent,token);
1958
0
      for (i=0; (i < MaxPixelChannels); i++)
1959
0
        levels[i]=StringToDouble(token,(char **) NULL);
1960
0
      for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++)
1961
0
      {
1962
0
        (void) GetNextToken(p,&p,MagickPathExtent,token);
1963
0
        if (*token == ',')
1964
0
          (void) GetNextToken(p,&p,MagickPathExtent,token);
1965
0
        levels[i]=StringToDouble(token,(char **) NULL);
1966
0
      }
1967
0
    }
1968
0
  for (i=0; i < MaxPixelChannels; i++)
1969
0
    if (fabs(levels[i]) >= 1)
1970
0
      levels[i]-=1.0;
1971
0
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
1972
0
    return(MagickFalse);
1973
0
  status=MagickTrue;
1974
0
  progress=0;
1975
0
  image_view=AcquireAuthenticCacheView(image,exception);
1976
#if defined(MAGICKCORE_OPENMP_SUPPORT)
1977
  #pragma omp parallel for schedule(static) shared(progress,status) \
1978
    magick_number_threads(image,image,image->rows,2)
1979
#endif
1980
0
  for (y=0; y < (ssize_t) image->rows; y++)
1981
0
  {
1982
0
    ssize_t
1983
0
      x;
1984
1985
0
    Quantum
1986
0
      *magick_restrict q;
1987
1988
0
    if (status == MagickFalse)
1989
0
      continue;
1990
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1991
0
    if (q == (Quantum *) NULL)
1992
0
      {
1993
0
        status=MagickFalse;
1994
0
        continue;
1995
0
      }
1996
0
    for (x=0; x < (ssize_t) image->columns; x++)
1997
0
    {
1998
0
      ssize_t
1999
0
        j,
2000
0
        n;
2001
2002
0
      n=0;
2003
0
      for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
2004
0
      {
2005
0
        ssize_t
2006
0
          level,
2007
0
          threshold;
2008
2009
0
        PixelChannel channel = GetPixelChannelChannel(image,j);
2010
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
2011
0
        if ((traits & UpdatePixelTrait) == 0)
2012
0
          continue;
2013
0
        if (fabs(levels[n]) < MagickEpsilon)
2014
0
          {
2015
0
            n++;
2016
0
            continue;
2017
0
          }
2018
0
        threshold=(ssize_t) (QuantumScale*(double) q[j]*(levels[n]*
2019
0
          (map->divisor-1)+1));
2020
0
        level=threshold/(map->divisor-1);
2021
0
        threshold-=level*(map->divisor-1);
2022
0
        q[j]=ClampToQuantum((double) (level+(threshold >=
2023
0
          map->levels[(x % (ssize_t) map->width)+(ssize_t) map->width*
2024
0
          (y % (ssize_t) map->height)]))*(double) QuantumRange/levels[n]);
2025
0
        n++;
2026
0
      }
2027
0
      q+=(ptrdiff_t) GetPixelChannels(image);
2028
0
    }
2029
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2030
0
      status=MagickFalse;
2031
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
2032
0
      {
2033
0
        MagickBooleanType
2034
0
          proceed;
2035
2036
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2037
        #pragma omp atomic
2038
#endif
2039
0
        progress++;
2040
0
        proceed=SetImageProgress(image,DitherImageTag,progress,image->rows);
2041
0
        if (proceed == MagickFalse)
2042
0
          status=MagickFalse;
2043
0
      }
2044
0
  }
2045
0
  image_view=DestroyCacheView(image_view);
2046
0
  map=DestroyThresholdMap(map);
2047
0
  return(MagickTrue);
2048
0
}
2049

2050
/*
2051
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2052
%                                                                             %
2053
%                                                                             %
2054
%                                                                             %
2055
%     P e r c e p t i b l e I m a g e                                         %
2056
%                                                                             %
2057
%                                                                             %
2058
%                                                                             %
2059
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2060
%
2061
%  PerceptibleImage() set each pixel whose value is less than |epsilon| to
2062
%  epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
2063
%  unchanged.
2064
%
2065
%  The format of the PerceptibleImage method is:
2066
%
2067
%      MagickBooleanType PerceptibleImage(Image *image,const double epsilon,
2068
%        ExceptionInfo *exception)
2069
%
2070
%  A description of each parameter follows:
2071
%
2072
%    o image: the image.
2073
%
2074
%    o epsilon: the epsilon threshold (e.g. 1.0e-9).
2075
%
2076
%    o exception: return any errors or warnings in this structure.
2077
%
2078
*/
2079
2080
static inline Quantum PerceptibleThreshold(const Quantum quantum,
2081
  const double epsilon)
2082
0
{
2083
0
  double
2084
0
    sign;
2085
2086
0
  sign=(double) quantum < 0.0 ? -1.0 : 1.0;
2087
0
  if ((sign*(double) quantum) >= epsilon)
2088
0
    return(quantum);
2089
0
  return((Quantum) (sign*epsilon));
2090
0
}
2091
2092
MagickExport MagickBooleanType PerceptibleImage(Image *image,
2093
  const double epsilon,ExceptionInfo *exception)
2094
0
{
2095
0
#define PerceptibleImageTag  "Perceptible/Image"
2096
2097
0
  CacheView
2098
0
    *image_view;
2099
2100
0
  MagickBooleanType
2101
0
    status;
2102
2103
0
  MagickOffsetType
2104
0
    progress;
2105
2106
0
  ssize_t
2107
0
    y;
2108
2109
0
  assert(image != (Image *) NULL);
2110
0
  assert(image->signature == MagickCoreSignature);
2111
0
  if (IsEventLogging() != MagickFalse)
2112
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2113
0
  if (image->storage_class == PseudoClass)
2114
0
    {
2115
0
      ssize_t
2116
0
        i;
2117
2118
0
      PixelInfo
2119
0
        *magick_restrict q;
2120
2121
0
      q=image->colormap;
2122
0
      for (i=0; i < (ssize_t) image->colors; i++)
2123
0
      {
2124
0
        if ((GetPixelChannelTraits(image,RedPixelChannel) & UpdatePixelTrait) != 0)
2125
0
          q->red=(MagickRealType) PerceptibleThreshold(ClampToQuantum(q->red),
2126
0
            epsilon);
2127
0
        if ((GetPixelChannelTraits(image,GreenPixelChannel) & UpdatePixelTrait) != 0)
2128
0
          q->green=(MagickRealType) PerceptibleThreshold(ClampToQuantum(q->green),
2129
0
            epsilon);
2130
0
        if ((GetPixelChannelTraits(image,BluePixelChannel) & UpdatePixelTrait) != 0)
2131
0
          q->blue=(MagickRealType) PerceptibleThreshold(ClampToQuantum(q->blue),
2132
0
            epsilon);
2133
0
        if ((GetPixelChannelTraits(image,AlphaPixelChannel) & UpdatePixelTrait) != 0)
2134
0
          q->alpha=(MagickRealType) PerceptibleThreshold(ClampToQuantum(q->alpha),
2135
0
            epsilon);
2136
0
        q++;
2137
0
      }
2138
0
      return(SyncImage(image,exception));
2139
0
    }
2140
  /*
2141
    Perceptible image.
2142
  */
2143
0
  status=MagickTrue;
2144
0
  progress=0;
2145
0
  image_view=AcquireAuthenticCacheView(image,exception);
2146
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2147
  #pragma omp parallel for schedule(static) shared(progress,status) \
2148
    magick_number_threads(image,image,image->rows,2)
2149
#endif
2150
0
  for (y=0; y < (ssize_t) image->rows; y++)
2151
0
  {
2152
0
    ssize_t
2153
0
      x;
2154
2155
0
    Quantum
2156
0
      *magick_restrict q;
2157
2158
0
    if (status == MagickFalse)
2159
0
      continue;
2160
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2161
0
    if (q == (Quantum *) NULL)
2162
0
      {
2163
0
        status=MagickFalse;
2164
0
        continue;
2165
0
      }
2166
0
    for (x=0; x < (ssize_t) image->columns; x++)
2167
0
    {
2168
0
      ssize_t
2169
0
        i;
2170
2171
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2172
0
      {
2173
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
2174
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
2175
0
        if ((traits & UpdatePixelTrait) != 0)
2176
0
          q[i]=PerceptibleThreshold(q[i],epsilon);
2177
0
      }
2178
0
      q+=(ptrdiff_t) GetPixelChannels(image);
2179
0
    }
2180
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2181
0
      status=MagickFalse;
2182
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
2183
0
      {
2184
0
        MagickBooleanType
2185
0
          proceed;
2186
2187
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2188
        #pragma omp atomic
2189
#endif
2190
0
        progress++;
2191
0
        proceed=SetImageProgress(image,PerceptibleImageTag,progress,
2192
0
          image->rows);
2193
0
        if (proceed == MagickFalse)
2194
0
          status=MagickFalse;
2195
0
      }
2196
0
  }
2197
0
  image_view=DestroyCacheView(image_view);
2198
0
  return(status);
2199
0
}
2200

2201
/*
2202
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2203
%                                                                             %
2204
%                                                                             %
2205
%                                                                             %
2206
%     R a n d o m T h r e s h o l d I m a g e                                 %
2207
%                                                                             %
2208
%                                                                             %
2209
%                                                                             %
2210
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2211
%
2212
%  RandomThresholdImage() changes the value of individual pixels based on the
2213
%  intensity of each pixel compared to a random threshold.  The result is a
2214
%  low-contrast, two color image.
2215
%
2216
%  The format of the RandomThresholdImage method is:
2217
%
2218
%      MagickBooleanType RandomThresholdImage(Image *image,
2219
%        const char *thresholds,ExceptionInfo *exception)
2220
%
2221
%  A description of each parameter follows:
2222
%
2223
%    o image: the image.
2224
%
2225
%    o low,high: Specify the high and low thresholds. These values range from
2226
%      0 to QuantumRange.
2227
%
2228
%    o exception: return any errors or warnings in this structure.
2229
%
2230
*/
2231
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
2232
  const double min_threshold, const double max_threshold,ExceptionInfo *exception)
2233
0
{
2234
0
#define ThresholdImageTag  "Threshold/Image"
2235
2236
0
  CacheView
2237
0
    *image_view;
2238
2239
0
  MagickBooleanType
2240
0
    status;
2241
2242
0
  MagickOffsetType
2243
0
    progress;
2244
2245
0
  RandomInfo
2246
0
    **magick_restrict random_info;
2247
2248
0
  ssize_t
2249
0
    y;
2250
2251
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2252
  unsigned long
2253
    key;
2254
#endif
2255
2256
0
  assert(image != (Image *) NULL);
2257
0
  assert(image->signature == MagickCoreSignature);
2258
0
  assert(exception != (ExceptionInfo *) NULL);
2259
0
  assert(exception->signature == MagickCoreSignature);
2260
0
  if (IsEventLogging() != MagickFalse)
2261
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2262
0
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2263
0
    return(MagickFalse);
2264
  /*
2265
    Random threshold image.
2266
  */
2267
0
  status=MagickTrue;
2268
0
  progress=0;
2269
0
  random_info=AcquireRandomInfoTLS();
2270
0
  image_view=AcquireAuthenticCacheView(image,exception);
2271
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2272
  key=GetRandomSecretKey(random_info[0]);
2273
  #pragma omp parallel for schedule(static) shared(progress,status) \
2274
    magick_number_threads(image,image,image->rows,key == ~0UL ? 0 : 1)
2275
#endif
2276
0
  for (y=0; y < (ssize_t) image->rows; y++)
2277
0
  {
2278
0
    const int
2279
0
      id = GetOpenMPThreadId();
2280
2281
0
    Quantum
2282
0
      *magick_restrict q;
2283
2284
0
    ssize_t
2285
0
      x;
2286
2287
0
    if (status == MagickFalse)
2288
0
      continue;
2289
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2290
0
    if (q == (Quantum *) NULL)
2291
0
      {
2292
0
        status=MagickFalse;
2293
0
        continue;
2294
0
      }
2295
0
    for (x=0; x < (ssize_t) image->columns; x++)
2296
0
    {
2297
0
      ssize_t
2298
0
        i;
2299
2300
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2301
0
      {
2302
0
        double
2303
0
          threshold;
2304
2305
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
2306
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
2307
0
        if ((traits & UpdatePixelTrait) == 0)
2308
0
          continue;
2309
0
        if ((double) q[i] < min_threshold)
2310
0
          threshold=min_threshold;
2311
0
        else
2312
0
          if ((double) q[i] > max_threshold)
2313
0
            threshold=max_threshold;
2314
0
          else
2315
0
            threshold=((double) QuantumRange*
2316
0
              GetPseudoRandomValue(random_info[id]));
2317
0
        q[i]=(double) q[i] <= threshold ? 0 : QuantumRange;
2318
0
      }
2319
0
      q+=(ptrdiff_t) GetPixelChannels(image);
2320
0
    }
2321
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2322
0
      status=MagickFalse;
2323
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
2324
0
      {
2325
0
        MagickBooleanType
2326
0
          proceed;
2327
2328
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2329
        #pragma omp atomic
2330
#endif
2331
0
        progress++;
2332
0
        proceed=SetImageProgress(image,ThresholdImageTag,progress,
2333
0
          image->rows);
2334
0
        if (proceed == MagickFalse)
2335
0
          status=MagickFalse;
2336
0
      }
2337
0
  }
2338
0
  image_view=DestroyCacheView(image_view);
2339
0
  random_info=DestroyRandomInfoTLS(random_info);
2340
0
  return(status);
2341
0
}
2342

2343
/*
2344
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2345
%                                                                             %
2346
%                                                                             %
2347
%                                                                             %
2348
%     R a n g e T h r e s h o l d I m a g e                                   %
2349
%                                                                             %
2350
%                                                                             %
2351
%                                                                             %
2352
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2353
%
2354
%  RangeThresholdImage() applies soft and hard thresholding.
2355
%
2356
%  The format of the RangeThresholdImage method is:
2357
%
2358
%      MagickBooleanType RangeThresholdImage(Image *image,
2359
%        const double low_black,const double low_white,const double high_white,
2360
%        const double high_black,ExceptionInfo *exception)
2361
%
2362
%  A description of each parameter follows:
2363
%
2364
%    o image: the image.
2365
%
2366
%    o low_black: Define the minimum black threshold value.
2367
%
2368
%    o low_white: Define the minimum white threshold value.
2369
%
2370
%    o high_white: Define the maximum white threshold value.
2371
%
2372
%    o high_black: Define the maximum black threshold value.
2373
%
2374
%    o exception: return any errors or warnings in this structure.
2375
%
2376
*/
2377
MagickExport MagickBooleanType RangeThresholdImage(Image *image,
2378
  const double low_black,const double low_white,const double high_white,
2379
  const double high_black,ExceptionInfo *exception)
2380
0
{
2381
0
#define ThresholdImageTag  "Threshold/Image"
2382
2383
0
  CacheView
2384
0
    *image_view;
2385
2386
0
  MagickBooleanType
2387
0
    status;
2388
2389
0
  MagickOffsetType
2390
0
    progress;
2391
2392
0
  ssize_t
2393
0
    y;
2394
2395
0
  assert(image != (Image *) NULL);
2396
0
  assert(image->signature == MagickCoreSignature);
2397
0
  if (IsEventLogging() != MagickFalse)
2398
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2399
0
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2400
0
    return(MagickFalse);
2401
0
  if (IsGrayColorspace(image->colorspace) != MagickFalse)
2402
0
    (void) TransformImageColorspace(image,sRGBColorspace,exception);
2403
  /*
2404
    Range threshold image.
2405
  */
2406
0
  status=MagickTrue;
2407
0
  progress=0;
2408
0
  image_view=AcquireAuthenticCacheView(image,exception);
2409
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2410
  #pragma omp parallel for schedule(static) shared(progress,status) \
2411
    magick_number_threads(image,image,image->rows,2)
2412
#endif
2413
0
  for (y=0; y < (ssize_t) image->rows; y++)
2414
0
  {
2415
0
    ssize_t
2416
0
      x;
2417
2418
0
    Quantum
2419
0
      *magick_restrict q;
2420
2421
0
    if (status == MagickFalse)
2422
0
      continue;
2423
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2424
0
    if (q == (Quantum *) NULL)
2425
0
      {
2426
0
        status=MagickFalse;
2427
0
        continue;
2428
0
      }
2429
0
    for (x=0; x < (ssize_t) image->columns; x++)
2430
0
    {
2431
0
      double
2432
0
        pixel;
2433
2434
0
      ssize_t
2435
0
        i;
2436
2437
0
      pixel=GetPixelIntensity(image,q);
2438
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2439
0
      {
2440
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
2441
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
2442
0
        if ((traits & UpdatePixelTrait) == 0)
2443
0
          continue;
2444
0
        if (image->channel_mask != AllChannels)
2445
0
          pixel=(double) q[i];
2446
0
        if (pixel < low_black)
2447
0
          q[i]=(Quantum) 0;
2448
0
        else
2449
0
          if ((pixel >= low_black) && (pixel < low_white))
2450
0
            q[i]=ClampToQuantum((double) QuantumRange*
2451
0
              MagickSafeReciprocal(low_white-low_black)*(pixel-low_black));
2452
0
          else
2453
0
            if ((pixel >= low_white) && (pixel <= high_white))
2454
0
              q[i]=QuantumRange;
2455
0
            else
2456
0
              if ((pixel > high_white) && (pixel <= high_black))
2457
0
                q[i]=ClampToQuantum((double) QuantumRange*(double)
2458
0
                  MagickSafeReciprocal(high_black-high_white)*
2459
0
                  (high_black-pixel));
2460
0
              else
2461
0
                if (pixel > high_black)
2462
0
                  q[i]=(Quantum) 0;
2463
0
                else
2464
0
                  q[i]=(Quantum) 0;
2465
0
      }
2466
0
      q+=(ptrdiff_t) GetPixelChannels(image);
2467
0
    }
2468
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2469
0
      status=MagickFalse;
2470
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
2471
0
      {
2472
0
        MagickBooleanType
2473
0
          proceed;
2474
2475
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2476
        #pragma omp atomic
2477
#endif
2478
0
        progress++;
2479
0
        proceed=SetImageProgress(image,ThresholdImageTag,progress,
2480
0
          image->rows);
2481
0
        if (proceed == MagickFalse)
2482
0
          status=MagickFalse;
2483
0
      }
2484
0
  }
2485
0
  image_view=DestroyCacheView(image_view);
2486
0
  return(status);
2487
0
}
2488

2489
/*
2490
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2491
%                                                                             %
2492
%                                                                             %
2493
%                                                                             %
2494
%     W h i t e T h r e s h o l d I m a g e                                   %
2495
%                                                                             %
2496
%                                                                             %
2497
%                                                                             %
2498
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2499
%
2500
%  WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
2501
%  the threshold into white while leaving all pixels at or below the threshold
2502
%  unchanged.
2503
%
2504
%  The format of the WhiteThresholdImage method is:
2505
%
2506
%      MagickBooleanType WhiteThresholdImage(Image *image,
2507
%        const char *threshold,ExceptionInfo *exception)
2508
%
2509
%  A description of each parameter follows:
2510
%
2511
%    o image: the image.
2512
%
2513
%    o threshold: Define the threshold value.
2514
%
2515
%    o exception: return any errors or warnings in this structure.
2516
%
2517
*/
2518
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
2519
  const char *thresholds,ExceptionInfo *exception)
2520
0
{
2521
0
#define ThresholdImageTag  "Threshold/Image"
2522
2523
0
  CacheView
2524
0
    *image_view;
2525
2526
0
  GeometryInfo
2527
0
    geometry_info;
2528
2529
0
  MagickBooleanType
2530
0
    status;
2531
2532
0
  MagickOffsetType
2533
0
    progress;
2534
2535
0
  PixelInfo
2536
0
    threshold;
2537
2538
0
  MagickStatusType
2539
0
    flags;
2540
2541
0
  ssize_t
2542
0
    y;
2543
2544
0
  assert(image != (Image *) NULL);
2545
0
  assert(image->signature == MagickCoreSignature);
2546
0
  if (IsEventLogging() != MagickFalse)
2547
0
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2548
0
  if (thresholds == (const char *) NULL)
2549
0
    return(MagickTrue);
2550
0
  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2551
0
    return(MagickFalse);
2552
0
  if (IsGrayColorspace(image->colorspace) != MagickFalse)
2553
0
    (void) TransformImageColorspace(image,sRGBColorspace,exception);
2554
0
  GetPixelInfo(image,&threshold);
2555
0
  flags=ParseGeometry(thresholds,&geometry_info);
2556
0
  threshold.red=geometry_info.rho;
2557
0
  threshold.green=geometry_info.rho;
2558
0
  threshold.blue=geometry_info.rho;
2559
0
  threshold.black=geometry_info.rho;
2560
0
  threshold.alpha=100.0;
2561
0
  if ((flags & SigmaValue) != 0)
2562
0
    threshold.green=geometry_info.sigma;
2563
0
  if ((flags & XiValue) != 0)
2564
0
    threshold.blue=geometry_info.xi;
2565
0
  if ((flags & PsiValue) != 0)
2566
0
    threshold.alpha=geometry_info.psi;
2567
0
  if (threshold.colorspace == CMYKColorspace)
2568
0
    {
2569
0
      if ((flags & PsiValue) != 0)
2570
0
        threshold.black=geometry_info.psi;
2571
0
      if ((flags & ChiValue) != 0)
2572
0
        threshold.alpha=geometry_info.chi;
2573
0
    }
2574
0
  if ((flags & PercentValue) != 0)
2575
0
    {
2576
0
      threshold.red*=((MagickRealType) QuantumRange/100.0);
2577
0
      threshold.green*=((MagickRealType) QuantumRange/100.0);
2578
0
      threshold.blue*=((MagickRealType) QuantumRange/100.0);
2579
0
      threshold.black*=((MagickRealType) QuantumRange/100.0);
2580
0
      threshold.alpha*=((MagickRealType) QuantumRange/100.0);
2581
0
    }
2582
  /*
2583
    White threshold image.
2584
  */
2585
0
  status=MagickTrue;
2586
0
  progress=0;
2587
0
  image_view=AcquireAuthenticCacheView(image,exception);
2588
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2589
  #pragma omp parallel for schedule(static) shared(progress,status) \
2590
    magick_number_threads(image,image,image->rows,2)
2591
#endif
2592
0
  for (y=0; y < (ssize_t) image->rows; y++)
2593
0
  {
2594
0
    ssize_t
2595
0
      x;
2596
2597
0
    Quantum
2598
0
      *magick_restrict q;
2599
2600
0
    if (status == MagickFalse)
2601
0
      continue;
2602
0
    q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2603
0
    if (q == (Quantum *) NULL)
2604
0
      {
2605
0
        status=MagickFalse;
2606
0
        continue;
2607
0
      }
2608
0
    for (x=0; x < (ssize_t) image->columns; x++)
2609
0
    {
2610
0
      double
2611
0
        pixel;
2612
2613
0
      ssize_t
2614
0
        i;
2615
2616
0
      pixel=GetPixelIntensity(image,q);
2617
0
      for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2618
0
      {
2619
0
        PixelChannel channel = GetPixelChannelChannel(image,i);
2620
0
        PixelTrait traits = GetPixelChannelTraits(image,channel);
2621
0
        if ((traits & UpdatePixelTrait) == 0)
2622
0
          continue;
2623
0
        if (image->channel_mask != AllChannels)
2624
0
          pixel=(double) q[i];
2625
0
        if (pixel > GetPixelInfoChannel(&threshold,channel))
2626
0
          q[i]=QuantumRange;
2627
0
      }
2628
0
      q+=(ptrdiff_t) GetPixelChannels(image);
2629
0
    }
2630
0
    if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2631
0
      status=MagickFalse;
2632
0
    if (image->progress_monitor != (MagickProgressMonitor) NULL)
2633
0
      {
2634
0
        MagickBooleanType
2635
0
          proceed;
2636
2637
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2638
        #pragma omp atomic
2639
#endif
2640
0
        progress++;
2641
0
        proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
2642
0
        if (proceed == MagickFalse)
2643
0
          status=MagickFalse;
2644
0
      }
2645
0
  }
2646
0
  image_view=DestroyCacheView(image_view);
2647
0
  return(status);
2648
0
}