MagickCore  7.1.0
Convert, Edit, Or Compose Bitmap Images
statistic.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 % %
4 % %
5 % %
6 % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC %
7 % SS T A A T I SS T I C %
8 % SSS T AAAAA T I SSS T I C %
9 % SS T A A T I SS T I C %
10 % SSSSS T A A T IIIII SSSSS T IIIII CCCC %
11 % %
12 % %
13 % MagickCore Image Statistical Methods %
14 % %
15 % Software Design %
16 % Cristy %
17 % July 1992 %
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/accelerate-private.h"
45 #include "MagickCore/animate.h"
46 #include "MagickCore/artifact.h"
47 #include "MagickCore/blob.h"
48 #include "MagickCore/blob-private.h"
49 #include "MagickCore/cache.h"
50 #include "MagickCore/cache-private.h"
51 #include "MagickCore/cache-view.h"
52 #include "MagickCore/client.h"
53 #include "MagickCore/color.h"
54 #include "MagickCore/color-private.h"
55 #include "MagickCore/colorspace.h"
56 #include "MagickCore/colorspace-private.h"
57 #include "MagickCore/composite.h"
58 #include "MagickCore/composite-private.h"
59 #include "MagickCore/compress.h"
60 #include "MagickCore/constitute.h"
61 #include "MagickCore/display.h"
62 #include "MagickCore/draw.h"
63 #include "MagickCore/enhance.h"
64 #include "MagickCore/exception.h"
65 #include "MagickCore/exception-private.h"
66 #include "MagickCore/gem.h"
67 #include "MagickCore/gem-private.h"
68 #include "MagickCore/geometry.h"
69 #include "MagickCore/list.h"
70 #include "MagickCore/image-private.h"
71 #include "MagickCore/magic.h"
72 #include "MagickCore/magick.h"
73 #include "MagickCore/memory_.h"
74 #include "MagickCore/module.h"
75 #include "MagickCore/monitor.h"
76 #include "MagickCore/monitor-private.h"
77 #include "MagickCore/option.h"
78 #include "MagickCore/paint.h"
79 #include "MagickCore/pixel-accessor.h"
80 #include "MagickCore/profile.h"
81 #include "MagickCore/property.h"
82 #include "MagickCore/quantize.h"
83 #include "MagickCore/quantum-private.h"
84 #include "MagickCore/random_.h"
85 #include "MagickCore/random-private.h"
86 #include "MagickCore/resource_.h"
87 #include "MagickCore/segment.h"
88 #include "MagickCore/semaphore.h"
89 #include "MagickCore/signature-private.h"
90 #include "MagickCore/statistic.h"
91 #include "MagickCore/string_.h"
92 #include "MagickCore/thread-private.h"
93 #include "MagickCore/timer.h"
94 #include "MagickCore/utility.h"
95 #include "MagickCore/version.h"
96 ␌
97 /*
98 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
99 % %
100 % %
101 % %
102 % E v a l u a t e I m a g e %
103 % %
104 % %
105 % %
106 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
107 %
108 % EvaluateImage() applies a value to the image with an arithmetic, relational,
109 % or logical operator to an image. Use these operations to lighten or darken
110 % an image, to increase or decrease contrast in an image, or to produce the
111 % "negative" of an image.
112 %
113 % The format of the EvaluateImage method is:
114 %
115 % MagickBooleanType EvaluateImage(Image *image,
116 % const MagickEvaluateOperator op,const double value,
117 % ExceptionInfo *exception)
118 % MagickBooleanType EvaluateImages(Image *images,
119 % const MagickEvaluateOperator op,const double value,
120 % ExceptionInfo *exception)
121 %
122 % A description of each parameter follows:
123 %
124 % o image: the image.
125 %
126 % o op: A channel op.
127 %
128 % o value: A value value.
129 %
130 % o exception: return any errors or warnings in this structure.
131 %
132 */
133 
134 typedef struct _PixelChannels
135 {
136  double
137  channel[MaxPixelChannels];
138 } PixelChannels;
139 
140 static PixelChannels **DestroyPixelTLS(const Image *images,
141  PixelChannels **pixels)
142 {
143  ssize_t
144  i;
145 
146  size_t
147  rows;
148 
149  assert(pixels != (PixelChannels **) NULL);
150  rows=MagickMax(GetImageListLength(images),(size_t)
151  GetMagickResourceLimit(ThreadResource));
152  for (i=0; i < (ssize_t) rows; i++)
153  if (pixels[i] != (PixelChannels *) NULL)
154  pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]);
155  pixels=(PixelChannels **) RelinquishMagickMemory(pixels);
156  return(pixels);
157 }
158 
159 static PixelChannels **AcquirePixelTLS(const Image *images)
160 {
161  const Image
162  *next;
163 
165  **pixels;
166 
167  ssize_t
168  i;
169 
170  size_t
171  columns,
172  number_images,
173  rows;
174 
175  number_images=GetImageListLength(images);
176  rows=MagickMax(number_images,(size_t) GetMagickResourceLimit(ThreadResource));
177  pixels=(PixelChannels **) AcquireQuantumMemory(rows,sizeof(*pixels));
178  if (pixels == (PixelChannels **) NULL)
179  return((PixelChannels **) NULL);
180  (void) memset(pixels,0,rows*sizeof(*pixels));
181  columns=MagickMax(number_images,MaxPixelChannels);
182  for (next=images; next != (Image *) NULL; next=next->next)
183  columns=MagickMax(next->columns,columns);
184  for (i=0; i < (ssize_t) rows; i++)
185  {
186  ssize_t
187  j;
188 
189  pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels));
190  if (pixels[i] == (PixelChannels *) NULL)
191  return(DestroyPixelTLS(images,pixels));
192  for (j=0; j < (ssize_t) columns; j++)
193  {
194  ssize_t
195  k;
196 
197  for (k=0; k < MaxPixelChannels; k++)
198  pixels[i][j].channel[k]=0.0;
199  }
200  }
201  return(pixels);
202 }
203 
204 static inline double EvaluateMax(const double x,const double y)
205 {
206  if (x > y)
207  return(x);
208  return(y);
209 }
210 
211 #if defined(__cplusplus) || defined(c_plusplus)
212 extern "C" {
213 #endif
214 
215 static int IntensityCompare(const void *x,const void *y)
216 {
217  const PixelChannels
218  *color_1,
219  *color_2;
220 
221  double
222  distance;
223 
224  ssize_t
225  i;
226 
227  color_1=(const PixelChannels *) x;
228  color_2=(const PixelChannels *) y;
229  distance=0.0;
230  for (i=0; i < MaxPixelChannels; i++)
231  distance+=color_1->channel[i]-(double) color_2->channel[i];
232  return(distance < 0.0 ? -1 : distance > 0.0 ? 1 : 0);
233 }
234 
235 #if defined(__cplusplus) || defined(c_plusplus)
236 }
237 #endif
238 
239 static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel,
240  const MagickEvaluateOperator op,const double value)
241 {
242  double
243  result;
244 
245  ssize_t
246  i;
247 
248  result=0.0;
249  switch (op)
250  {
251  case UndefinedEvaluateOperator:
252  break;
253  case AbsEvaluateOperator:
254  {
255  result=(double) fabs((double) (pixel+value));
256  break;
257  }
258  case AddEvaluateOperator:
259  {
260  result=(double) (pixel+value);
261  break;
262  }
263  case AddModulusEvaluateOperator:
264  {
265  /*
266  This returns a 'floored modulus' of the addition which is a positive
267  result. It differs from % or fmod() that returns a 'truncated modulus'
268  result, where floor() is replaced by trunc() and could return a
269  negative result (which is clipped).
270  */
271  result=pixel+value;
272  result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0));
273  break;
274  }
275  case AndEvaluateOperator:
276  {
277  result=(double) ((ssize_t) pixel & (ssize_t) (value+0.5));
278  break;
279  }
280  case CosineEvaluateOperator:
281  {
282  result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI*
283  QuantumScale*pixel*value))+0.5));
284  break;
285  }
286  case DivideEvaluateOperator:
287  {
288  result=pixel/(value == 0.0 ? 1.0 : value);
289  break;
290  }
291  case ExponentialEvaluateOperator:
292  {
293  result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel)));
294  break;
295  }
296  case GaussianNoiseEvaluateOperator:
297  {
298  result=(double) GenerateDifferentialNoise(random_info,pixel,GaussianNoise,
299  value);
300  break;
301  }
302  case ImpulseNoiseEvaluateOperator:
303  {
304  result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise,
305  value);
306  break;
307  }
308  case InverseLogEvaluateOperator:
309  {
310  result=(QuantumRange*pow((value+1.0),QuantumScale*pixel)-1.0)*
311  PerceptibleReciprocal(value);
312  break;
313  }
314  case LaplacianNoiseEvaluateOperator:
315  {
316  result=(double) GenerateDifferentialNoise(random_info,pixel,
317  LaplacianNoise,value);
318  break;
319  }
320  case LeftShiftEvaluateOperator:
321  {
322  result=(double) pixel;
323  for (i=0; i < (ssize_t) value; i++)
324  result*=2.0;
325  break;
326  }
327  case LogEvaluateOperator:
328  {
329  if ((QuantumScale*pixel) >= MagickEpsilon)
330  result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+
331  1.0))/log((double) (value+1.0)));
332  break;
333  }
334  case MaxEvaluateOperator:
335  {
336  result=(double) EvaluateMax((double) pixel,value);
337  break;
338  }
339  case MeanEvaluateOperator:
340  {
341  result=(double) (pixel+value);
342  break;
343  }
344  case MedianEvaluateOperator:
345  {
346  result=(double) (pixel+value);
347  break;
348  }
349  case MinEvaluateOperator:
350  {
351  result=(double) MagickMin((double) pixel,value);
352  break;
353  }
354  case MultiplicativeNoiseEvaluateOperator:
355  {
356  result=(double) GenerateDifferentialNoise(random_info,pixel,
357  MultiplicativeGaussianNoise,value);
358  break;
359  }
360  case MultiplyEvaluateOperator:
361  {
362  result=(double) (value*pixel);
363  break;
364  }
365  case OrEvaluateOperator:
366  {
367  result=(double) ((ssize_t) pixel | (ssize_t) (value+0.5));
368  break;
369  }
370  case PoissonNoiseEvaluateOperator:
371  {
372  result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise,
373  value);
374  break;
375  }
376  case PowEvaluateOperator:
377  {
378  if (pixel < 0)
379  result=(double) -(QuantumRange*pow((double) -(QuantumScale*pixel),
380  (double) value));
381  else
382  result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),
383  (double) value));
384  break;
385  }
386  case RightShiftEvaluateOperator:
387  {
388  result=(double) pixel;
389  for (i=0; i < (ssize_t) value; i++)
390  result/=2.0;
391  break;
392  }
393  case RootMeanSquareEvaluateOperator:
394  {
395  result=((double) pixel*pixel+value);
396  break;
397  }
398  case SetEvaluateOperator:
399  {
400  result=value;
401  break;
402  }
403  case SineEvaluateOperator:
404  {
405  result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
406  QuantumScale*pixel*value))+0.5));
407  break;
408  }
409  case SubtractEvaluateOperator:
410  {
411  result=(double) (pixel-value);
412  break;
413  }
414  case SumEvaluateOperator:
415  {
416  result=(double) (pixel+value);
417  break;
418  }
419  case ThresholdEvaluateOperator:
420  {
421  result=(double) (((double) pixel <= value) ? 0 : QuantumRange);
422  break;
423  }
424  case ThresholdBlackEvaluateOperator:
425  {
426  result=(double) (((double) pixel <= value) ? 0 : pixel);
427  break;
428  }
429  case ThresholdWhiteEvaluateOperator:
430  {
431  result=(double) (((double) pixel > value) ? QuantumRange : pixel);
432  break;
433  }
434  case UniformNoiseEvaluateOperator:
435  {
436  result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise,
437  value);
438  break;
439  }
440  case XorEvaluateOperator:
441  {
442  result=(double) ((ssize_t) pixel ^ (ssize_t) (value+0.5));
443  break;
444  }
445  }
446  return(result);
447 }
448 
449 static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception)
450 {
451  const Image
452  *p,
453  *q;
454 
455  size_t
456  columns,
457  rows;
458 
459  q=images;
460  columns=images->columns;
461  rows=images->rows;
462  for (p=images; p != (Image *) NULL; p=p->next)
463  {
464  if (p->number_channels > q->number_channels)
465  q=p;
466  if (p->columns > columns)
467  columns=p->columns;
468  if (p->rows > rows)
469  rows=p->rows;
470  }
471  return(CloneImage(q,columns,rows,MagickTrue,exception));
472 }
473 
474 MagickExport Image *EvaluateImages(const Image *images,
475  const MagickEvaluateOperator op,ExceptionInfo *exception)
476 {
477 #define EvaluateImageTag "Evaluate/Image"
478 
479  CacheView
480  *evaluate_view,
481  **image_view;
482 
483  const Image
484  *view;
485 
486  Image
487  *image;
488 
489  MagickBooleanType
490  status;
491 
492  MagickOffsetType
493  progress;
494 
496  **magick_restrict evaluate_pixels;
497 
498  RandomInfo
499  **magick_restrict random_info;
500 
501  size_t
502  number_images;
503 
504  ssize_t
505  n,
506  y;
507 
508 #if defined(MAGICKCORE_OPENMP_SUPPORT)
509  unsigned long
510  key;
511 #endif
512 
513  assert(images != (Image *) NULL);
514  assert(images->signature == MagickCoreSignature);
515  assert(exception != (ExceptionInfo *) NULL);
516  assert(exception->signature == MagickCoreSignature);
517  if (IsEventLogging() != MagickFalse)
518  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
519  image=AcquireImageCanvas(images,exception);
520  if (image == (Image *) NULL)
521  return((Image *) NULL);
522  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
523  {
524  image=DestroyImage(image);
525  return((Image *) NULL);
526  }
527  number_images=GetImageListLength(images);
528  evaluate_pixels=AcquirePixelTLS(images);
529  if (evaluate_pixels == (PixelChannels **) NULL)
530  {
531  image=DestroyImage(image);
532  (void) ThrowMagickException(exception,GetMagickModule(),
533  ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
534  return((Image *) NULL);
535  }
536  image_view=(CacheView **) AcquireQuantumMemory(number_images,
537  sizeof(*image_view));
538  if (image_view == (CacheView **) NULL)
539  {
540  image=DestroyImage(image);
541  evaluate_pixels=DestroyPixelTLS(images,evaluate_pixels);
542  (void) ThrowMagickException(exception,GetMagickModule(),
543  ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
544  return(image);
545  }
546  view=images;
547  for (n=0; n < (ssize_t) number_images; n++)
548  {
549  image_view[n]=AcquireVirtualCacheView(view,exception);
550  view=GetNextImageInList(view);
551  }
552  /*
553  Evaluate image pixels.
554  */
555  status=MagickTrue;
556  progress=0;
557  random_info=AcquireRandomInfoTLS();
558  evaluate_view=AcquireAuthenticCacheView(image,exception);
559  if (op == MedianEvaluateOperator)
560  {
561 #if defined(MAGICKCORE_OPENMP_SUPPORT)
562  key=GetRandomSecretKey(random_info[0]);
563  #pragma omp parallel for schedule(static) shared(progress,status) \
564  magick_number_threads(image,images,image->rows,key == ~0UL)
565 #endif
566  for (y=0; y < (ssize_t) image->rows; y++)
567  {
568  const int
569  id = GetOpenMPThreadId();
570 
571  const Quantum
572  **p;
573 
575  *evaluate_pixel;
576 
577  Quantum
578  *magick_restrict q;
579 
580  ssize_t
581  x;
582 
583  ssize_t
584  j;
585 
586  if (status == MagickFalse)
587  continue;
588  p=(const Quantum **) AcquireQuantumMemory(number_images,sizeof(*p));
589  if (p == (const Quantum **) NULL)
590  {
591  status=MagickFalse;
592  (void) ThrowMagickException(exception,GetMagickModule(),
593  ResourceLimitError,"MemoryAllocationFailed","`%s'",
594  images->filename);
595  continue;
596  }
597  for (j=0; j < (ssize_t) number_images; j++)
598  {
599  p[j]=GetCacheViewVirtualPixels(image_view[j],0,y,image->columns,1,
600  exception);
601  if (p[j] == (const Quantum *) NULL)
602  break;
603  }
604  q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
605  exception);
606  if ((j < (ssize_t) number_images) || (q == (Quantum *) NULL))
607  {
608  status=MagickFalse;
609  continue;
610  }
611  evaluate_pixel=evaluate_pixels[id];
612  for (x=0; x < (ssize_t) image->columns; x++)
613  {
614  const Image
615  *next;
616 
617  ssize_t
618  i;
619 
620  next=images;
621  for (j=0; j < (ssize_t) number_images; j++)
622  {
623  for (i=0; i < MaxPixelChannels; i++)
624  evaluate_pixel[j].channel[i]=0.0;
625  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
626  {
627  PixelChannel channel = GetPixelChannelChannel(image,i);
628  PixelTrait traits = GetPixelChannelTraits(next,channel);
629  PixelTrait evaluate_traits = GetPixelChannelTraits(image,channel);
630  if ((traits == UndefinedPixelTrait) ||
631  (evaluate_traits == UndefinedPixelTrait) ||
632  ((traits & UpdatePixelTrait) == 0))
633  continue;
634  evaluate_pixel[j].channel[i]=ApplyEvaluateOperator(
635  random_info[id],GetPixelChannel(next,channel,p[j]),op,
636  evaluate_pixel[j].channel[i]);
637  }
638  p[j]+=GetPixelChannels(next);
639  next=GetNextImageInList(next);
640  }
641  qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
642  IntensityCompare);
643  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
644  {
645  PixelChannel channel = GetPixelChannelChannel(image,i);
646  PixelTrait traits = GetPixelChannelTraits(image,channel);
647  if ((traits == UndefinedPixelTrait) ||
648  ((traits & UpdatePixelTrait) == 0))
649  continue;
650  q[i]=ClampToQuantum(evaluate_pixel[number_images/2].channel[i]);
651  }
652  q+=GetPixelChannels(image);
653  }
654  p=(const Quantum **) RelinquishMagickMemory((void *) p);
655  if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
656  status=MagickFalse;
657  if (images->progress_monitor != (MagickProgressMonitor) NULL)
658  {
659  MagickBooleanType
660  proceed;
661 
662 #if defined(MAGICKCORE_OPENMP_SUPPORT)
663  #pragma omp atomic
664 #endif
665  progress++;
666  proceed=SetImageProgress(images,EvaluateImageTag,progress,
667  image->rows);
668  if (proceed == MagickFalse)
669  status=MagickFalse;
670  }
671  }
672  }
673  else
674  {
675 #if defined(MAGICKCORE_OPENMP_SUPPORT)
676  key=GetRandomSecretKey(random_info[0]);
677  #pragma omp parallel for schedule(static) shared(progress,status) \
678  magick_number_threads(image,images,image->rows,key == ~0UL)
679 #endif
680  for (y=0; y < (ssize_t) image->rows; y++)
681  {
682  const Image
683  *next;
684 
685  const int
686  id = GetOpenMPThreadId();
687 
688  const Quantum
689  **p;
690 
692  *evaluate_pixel;
693 
694  Quantum
695  *magick_restrict q;
696 
697  ssize_t
698  i,
699  x;
700 
701  ssize_t
702  j;
703 
704  if (status == MagickFalse)
705  continue;
706  p=(const Quantum **) AcquireQuantumMemory(number_images,sizeof(*p));
707  if (p == (const Quantum **) NULL)
708  {
709  status=MagickFalse;
710  (void) ThrowMagickException(exception,GetMagickModule(),
711  ResourceLimitError,"MemoryAllocationFailed","`%s'",
712  images->filename);
713  continue;
714  }
715  for (j=0; j < (ssize_t) number_images; j++)
716  {
717  p[j]=GetCacheViewVirtualPixels(image_view[j],0,y,image->columns,1,
718  exception);
719  if (p[j] == (const Quantum *) NULL)
720  break;
721  }
722  q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
723  exception);
724  if ((j < (ssize_t) number_images) || (q == (Quantum *) NULL))
725  {
726  status=MagickFalse;
727  continue;
728  }
729  evaluate_pixel=evaluate_pixels[id];
730  for (j=0; j < (ssize_t) image->columns; j++)
731  for (i=0; i < MaxPixelChannels; i++)
732  evaluate_pixel[j].channel[i]=0.0;
733  next=images;
734  for (j=0; j < (ssize_t) number_images; j++)
735  {
736  for (x=0; x < (ssize_t) image->columns; x++)
737  {
738  for (i=0; i < (ssize_t) GetPixelChannels(next); i++)
739  {
740  PixelChannel channel = GetPixelChannelChannel(image,i);
741  PixelTrait traits = GetPixelChannelTraits(next,channel);
742  PixelTrait evaluate_traits = GetPixelChannelTraits(image,channel);
743  if ((traits == UndefinedPixelTrait) ||
744  (evaluate_traits == UndefinedPixelTrait))
745  continue;
746  if ((traits & UpdatePixelTrait) == 0)
747  continue;
748  evaluate_pixel[x].channel[i]=ApplyEvaluateOperator(
749  random_info[id],GetPixelChannel(next,channel,p[j]),j == 0 ?
750  AddEvaluateOperator : op,evaluate_pixel[x].channel[i]);
751  }
752  p[j]+=GetPixelChannels(next);
753  }
754  next=GetNextImageInList(next);
755  }
756  for (x=0; x < (ssize_t) image->columns; x++)
757  {
758  switch (op)
759  {
760  case MeanEvaluateOperator:
761  {
762  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
763  evaluate_pixel[x].channel[i]/=(double) number_images;
764  break;
765  }
766  case MultiplyEvaluateOperator:
767  {
768  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
769  {
770  for (j=0; j < (ssize_t) (number_images-1); j++)
771  evaluate_pixel[x].channel[i]*=QuantumScale;
772  }
773  break;
774  }
775  case RootMeanSquareEvaluateOperator:
776  {
777  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
778  evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/
779  number_images);
780  break;
781  }
782  default:
783  break;
784  }
785  }
786  for (x=0; x < (ssize_t) image->columns; x++)
787  {
788  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
789  {
790  PixelChannel channel = GetPixelChannelChannel(image,i);
791  PixelTrait traits = GetPixelChannelTraits(image,channel);
792  if ((traits == UndefinedPixelTrait) ||
793  ((traits & UpdatePixelTrait) == 0))
794  continue;
795  q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]);
796  }
797  q+=GetPixelChannels(image);
798  }
799  p=(const Quantum **) RelinquishMagickMemory((void *) p);
800  if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
801  status=MagickFalse;
802  if (images->progress_monitor != (MagickProgressMonitor) NULL)
803  {
804  MagickBooleanType
805  proceed;
806 
807 #if defined(MAGICKCORE_OPENMP_SUPPORT)
808  #pragma omp atomic
809 #endif
810  progress++;
811  proceed=SetImageProgress(images,EvaluateImageTag,progress,
812  image->rows);
813  if (proceed == MagickFalse)
814  status=MagickFalse;
815  }
816  }
817  }
818  for (n=0; n < (ssize_t) number_images; n++)
819  image_view[n]=DestroyCacheView(image_view[n]);
820  image_view=(CacheView **) RelinquishMagickMemory(image_view);
821  evaluate_view=DestroyCacheView(evaluate_view);
822  evaluate_pixels=DestroyPixelTLS(images,evaluate_pixels);
823  random_info=DestroyRandomInfoTLS(random_info);
824  if (status == MagickFalse)
825  image=DestroyImage(image);
826  return(image);
827 }
828 
829 MagickExport MagickBooleanType EvaluateImage(Image *image,
830  const MagickEvaluateOperator op,const double value,ExceptionInfo *exception)
831 {
832  CacheView
833  *image_view;
834 
835  const char
836  *artifact;
837 
838  MagickBooleanType
839  clamp,
840  status;
841 
842  MagickOffsetType
843  progress;
844 
845  RandomInfo
846  **magick_restrict random_info;
847 
848  ssize_t
849  y;
850 
851 #if defined(MAGICKCORE_OPENMP_SUPPORT)
852  unsigned long
853  key;
854 #endif
855 
856  assert(image != (Image *) NULL);
857  assert(image->signature == MagickCoreSignature);
858  assert(exception != (ExceptionInfo *) NULL);
859  assert(exception->signature == MagickCoreSignature);
860  if (IsEventLogging() != MagickFalse)
861  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
862  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
863  return(MagickFalse);
864  status=MagickTrue;
865  progress=0;
866  clamp=MagickFalse;
867  artifact=GetImageArtifact(image,"evaluate:clamp");
868  if (artifact != (const char *) NULL)
869  clamp=IsStringTrue(artifact);
870  random_info=AcquireRandomInfoTLS();
871  image_view=AcquireAuthenticCacheView(image,exception);
872 #if defined(MAGICKCORE_OPENMP_SUPPORT)
873  key=GetRandomSecretKey(random_info[0]);
874  #pragma omp parallel for schedule(static) shared(progress,status) \
875  magick_number_threads(image,image,image->rows,key == ~0UL)
876 #endif
877  for (y=0; y < (ssize_t) image->rows; y++)
878  {
879  const int
880  id = GetOpenMPThreadId();
881 
882  Quantum
883  *magick_restrict q;
884 
885  ssize_t
886  x;
887 
888  if (status == MagickFalse)
889  continue;
890  q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
891  if (q == (Quantum *) NULL)
892  {
893  status=MagickFalse;
894  continue;
895  }
896  for (x=0; x < (ssize_t) image->columns; x++)
897  {
898  double
899  result;
900 
901  ssize_t
902  i;
903 
904  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
905  {
906  PixelChannel channel = GetPixelChannelChannel(image,i);
907  PixelTrait traits = GetPixelChannelTraits(image,channel);
908  if (traits == UndefinedPixelTrait)
909  continue;
910  if ((traits & CopyPixelTrait) != 0)
911  continue;
912  if ((traits & UpdatePixelTrait) == 0)
913  continue;
914  result=ApplyEvaluateOperator(random_info[id],q[i],op,value);
915  if (op == MeanEvaluateOperator)
916  result/=2.0;
917  q[i]=clamp != MagickFalse ? ClampPixel(result) : ClampToQuantum(result);
918  }
919  q+=GetPixelChannels(image);
920  }
921  if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
922  status=MagickFalse;
923  if (image->progress_monitor != (MagickProgressMonitor) NULL)
924  {
925  MagickBooleanType
926  proceed;
927 
928 #if defined(MAGICKCORE_OPENMP_SUPPORT)
929  #pragma omp atomic
930 #endif
931  progress++;
932  proceed=SetImageProgress(image,EvaluateImageTag,progress,image->rows);
933  if (proceed == MagickFalse)
934  status=MagickFalse;
935  }
936  }
937  image_view=DestroyCacheView(image_view);
938  random_info=DestroyRandomInfoTLS(random_info);
939  return(status);
940 }
941 ␌
942 /*
943 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
944 % %
945 % %
946 % %
947 % F u n c t i o n I m a g e %
948 % %
949 % %
950 % %
951 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
952 %
953 % FunctionImage() applies a value to the image with an arithmetic, relational,
954 % or logical operator to an image. Use these operations to lighten or darken
955 % an image, to increase or decrease contrast in an image, or to produce the
956 % "negative" of an image.
957 %
958 % The format of the FunctionImage method is:
959 %
960 % MagickBooleanType FunctionImage(Image *image,
961 % const MagickFunction function,const ssize_t number_parameters,
962 % const double *parameters,ExceptionInfo *exception)
963 %
964 % A description of each parameter follows:
965 %
966 % o image: the image.
967 %
968 % o function: A channel function.
969 %
970 % o parameters: one or more parameters.
971 %
972 % o exception: return any errors or warnings in this structure.
973 %
974 */
975 
976 static Quantum ApplyFunction(Quantum pixel,const MagickFunction function,
977  const size_t number_parameters,const double *parameters,
978  ExceptionInfo *exception)
979 {
980  double
981  result;
982 
983  ssize_t
984  i;
985 
986  (void) exception;
987  result=0.0;
988  switch (function)
989  {
990  case PolynomialFunction:
991  {
992  /*
993  Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+
994  c1*x^2+c2*x+c3).
995  */
996  result=0.0;
997  for (i=0; i < (ssize_t) number_parameters; i++)
998  result=result*QuantumScale*pixel+parameters[i];
999  result*=QuantumRange;
1000  break;
1001  }
1002  case SinusoidFunction:
1003  {
1004  double
1005  amplitude,
1006  bias,
1007  frequency,
1008  phase;
1009 
1010  /*
1011  Sinusoid: frequency, phase, amplitude, bias.
1012  */
1013  frequency=(number_parameters >= 1) ? parameters[0] : 1.0;
1014  phase=(number_parameters >= 2) ? parameters[1] : 0.0;
1015  amplitude=(number_parameters >= 3) ? parameters[2] : 0.5;
1016  bias=(number_parameters >= 4) ? parameters[3] : 0.5;
1017  result=(double) (QuantumRange*(amplitude*sin((double) (2.0*
1018  MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias));
1019  break;
1020  }
1021  case ArcsinFunction:
1022  {
1023  double
1024  bias,
1025  center,
1026  range,
1027  width;
1028 
1029  /*
1030  Arcsin (peged at range limits for invalid results): width, center,
1031  range, and bias.
1032  */
1033  width=(number_parameters >= 1) ? parameters[0] : 1.0;
1034  center=(number_parameters >= 2) ? parameters[1] : 0.5;
1035  range=(number_parameters >= 3) ? parameters[2] : 1.0;
1036  bias=(number_parameters >= 4) ? parameters[3] : 0.5;
1037  result=2.0*PerceptibleReciprocal(width)*(QuantumScale*pixel-center);
1038  if (result <= -1.0)
1039  result=bias-range/2.0;
1040  else
1041  if (result >= 1.0)
1042  result=bias+range/2.0;
1043  else
1044  result=(double) (range/MagickPI*asin((double) result)+bias);
1045  result*=QuantumRange;
1046  break;
1047  }
1048  case ArctanFunction:
1049  {
1050  double
1051  center,
1052  bias,
1053  range,
1054  slope;
1055 
1056  /*
1057  Arctan: slope, center, range, and bias.
1058  */
1059  slope=(number_parameters >= 1) ? parameters[0] : 1.0;
1060  center=(number_parameters >= 2) ? parameters[1] : 0.5;
1061  range=(number_parameters >= 3) ? parameters[2] : 1.0;
1062  bias=(number_parameters >= 4) ? parameters[3] : 0.5;
1063  result=(double) (MagickPI*slope*(QuantumScale*pixel-center));
1064  result=(double) (QuantumRange*(range/MagickPI*atan((double)
1065  result)+bias));
1066  break;
1067  }
1068  case UndefinedFunction:
1069  break;
1070  }
1071  return(ClampToQuantum(result));
1072 }
1073 
1074 MagickExport MagickBooleanType FunctionImage(Image *image,
1075  const MagickFunction function,const size_t number_parameters,
1076  const double *parameters,ExceptionInfo *exception)
1077 {
1078 #define FunctionImageTag "Function/Image "
1079 
1080  CacheView
1081  *image_view;
1082 
1083  MagickBooleanType
1084  status;
1085 
1086  MagickOffsetType
1087  progress;
1088 
1089  ssize_t
1090  y;
1091 
1092  assert(image != (Image *) NULL);
1093  assert(image->signature == MagickCoreSignature);
1094  assert(exception != (ExceptionInfo *) NULL);
1095  assert(exception->signature == MagickCoreSignature);
1096  if (IsEventLogging() != MagickFalse)
1097  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1098 #if defined(MAGICKCORE_OPENCL_SUPPORT)
1099  if (AccelerateFunctionImage(image,function,number_parameters,parameters,
1100  exception) != MagickFalse)
1101  return(MagickTrue);
1102 #endif
1103  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
1104  return(MagickFalse);
1105  status=MagickTrue;
1106  progress=0;
1107  image_view=AcquireAuthenticCacheView(image,exception);
1108 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1109  #pragma omp parallel for schedule(static) shared(progress,status) \
1110  magick_number_threads(image,image,image->rows,1)
1111 #endif
1112  for (y=0; y < (ssize_t) image->rows; y++)
1113  {
1114  Quantum
1115  *magick_restrict q;
1116 
1117  ssize_t
1118  x;
1119 
1120  if (status == MagickFalse)
1121  continue;
1122  q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1123  if (q == (Quantum *) NULL)
1124  {
1125  status=MagickFalse;
1126  continue;
1127  }
1128  for (x=0; x < (ssize_t) image->columns; x++)
1129  {
1130  ssize_t
1131  i;
1132 
1133  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1134  {
1135  PixelChannel channel = GetPixelChannelChannel(image,i);
1136  PixelTrait traits = GetPixelChannelTraits(image,channel);
1137  if (traits == UndefinedPixelTrait)
1138  continue;
1139  if ((traits & UpdatePixelTrait) == 0)
1140  continue;
1141  q[i]=ApplyFunction(q[i],function,number_parameters,parameters,
1142  exception);
1143  }
1144  q+=GetPixelChannels(image);
1145  }
1146  if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1147  status=MagickFalse;
1148  if (image->progress_monitor != (MagickProgressMonitor) NULL)
1149  {
1150  MagickBooleanType
1151  proceed;
1152 
1153 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1154  #pragma omp atomic
1155 #endif
1156  progress++;
1157  proceed=SetImageProgress(image,FunctionImageTag,progress,image->rows);
1158  if (proceed == MagickFalse)
1159  status=MagickFalse;
1160  }
1161  }
1162  image_view=DestroyCacheView(image_view);
1163  return(status);
1164 }
1165 ␌
1166 /*
1167 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1168 % %
1169 % %
1170 % %
1171 % G e t I m a g e E n t r o p y %
1172 % %
1173 % %
1174 % %
1175 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1176 %
1177 % GetImageEntropy() returns the entropy of one or more image channels.
1178 %
1179 % The format of the GetImageEntropy method is:
1180 %
1181 % MagickBooleanType GetImageEntropy(const Image *image,double *entropy,
1182 % ExceptionInfo *exception)
1183 %
1184 % A description of each parameter follows:
1185 %
1186 % o image: the image.
1187 %
1188 % o entropy: the average entropy of the selected channels.
1189 %
1190 % o exception: return any errors or warnings in this structure.
1191 %
1192 */
1193 MagickExport MagickBooleanType GetImageEntropy(const Image *image,
1194  double *entropy,ExceptionInfo *exception)
1195 {
1197  *channel_statistics;
1198 
1199  assert(image != (Image *) NULL);
1200  assert(image->signature == MagickCoreSignature);
1201  if (IsEventLogging() != MagickFalse)
1202  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1203  channel_statistics=GetImageStatistics(image,exception);
1204  if (channel_statistics == (ChannelStatistics *) NULL)
1205  return(MagickFalse);
1206  *entropy=channel_statistics[CompositePixelChannel].entropy;
1207  channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
1208  channel_statistics);
1209  return(MagickTrue);
1210 }
1211 ␌
1212 /*
1213 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1214 % %
1215 % %
1216 % %
1217 % G e t I m a g e E x t r e m a %
1218 % %
1219 % %
1220 % %
1221 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1222 %
1223 % GetImageExtrema() returns the extrema of one or more image channels.
1224 %
1225 % The format of the GetImageExtrema method is:
1226 %
1227 % MagickBooleanType GetImageExtrema(const Image *image,size_t *minima,
1228 % size_t *maxima,ExceptionInfo *exception)
1229 %
1230 % A description of each parameter follows:
1231 %
1232 % o image: the image.
1233 %
1234 % o minima: the minimum value in the channel.
1235 %
1236 % o maxima: the maximum value in the channel.
1237 %
1238 % o exception: return any errors or warnings in this structure.
1239 %
1240 */
1241 MagickExport MagickBooleanType GetImageExtrema(const Image *image,
1242  size_t *minima,size_t *maxima,ExceptionInfo *exception)
1243 {
1244  double
1245  max,
1246  min;
1247 
1248  MagickBooleanType
1249  status;
1250 
1251  assert(image != (Image *) NULL);
1252  assert(image->signature == MagickCoreSignature);
1253  if (IsEventLogging() != MagickFalse)
1254  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1255  status=GetImageRange(image,&min,&max,exception);
1256  *minima=(size_t) ceil(min-0.5);
1257  *maxima=(size_t) floor(max+0.5);
1258  return(status);
1259 }
1260 ␌
1261 /*
1262 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1263 % %
1264 % %
1265 % %
1266 % G e t I m a g e K u r t o s i s %
1267 % %
1268 % %
1269 % %
1270 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1271 %
1272 % GetImageKurtosis() returns the kurtosis and skewness of one or more image
1273 % channels.
1274 %
1275 % The format of the GetImageKurtosis method is:
1276 %
1277 % MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis,
1278 % double *skewness,ExceptionInfo *exception)
1279 %
1280 % A description of each parameter follows:
1281 %
1282 % o image: the image.
1283 %
1284 % o kurtosis: the kurtosis of the channel.
1285 %
1286 % o skewness: the skewness of the channel.
1287 %
1288 % o exception: return any errors or warnings in this structure.
1289 %
1290 */
1291 MagickExport MagickBooleanType GetImageKurtosis(const Image *image,
1292  double *kurtosis,double *skewness,ExceptionInfo *exception)
1293 {
1295  *channel_statistics;
1296 
1297  assert(image != (Image *) NULL);
1298  assert(image->signature == MagickCoreSignature);
1299  if (IsEventLogging() != MagickFalse)
1300  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1301  channel_statistics=GetImageStatistics(image,exception);
1302  if (channel_statistics == (ChannelStatistics *) NULL)
1303  return(MagickFalse);
1304  *kurtosis=channel_statistics[CompositePixelChannel].kurtosis;
1305  *skewness=channel_statistics[CompositePixelChannel].skewness;
1306  channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
1307  channel_statistics);
1308  return(MagickTrue);
1309 }
1310 ␌
1311 /*
1312 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1313 % %
1314 % %
1315 % %
1316 % G e t I m a g e M e a n %
1317 % %
1318 % %
1319 % %
1320 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1321 %
1322 % GetImageMean() returns the mean and standard deviation of one or more image
1323 % channels.
1324 %
1325 % The format of the GetImageMean method is:
1326 %
1327 % MagickBooleanType GetImageMean(const Image *image,double *mean,
1328 % double *standard_deviation,ExceptionInfo *exception)
1329 %
1330 % A description of each parameter follows:
1331 %
1332 % o image: the image.
1333 %
1334 % o mean: the average value in the channel.
1335 %
1336 % o standard_deviation: the standard deviation of the channel.
1337 %
1338 % o exception: return any errors or warnings in this structure.
1339 %
1340 */
1341 MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean,
1342  double *standard_deviation,ExceptionInfo *exception)
1343 {
1345  *channel_statistics;
1346 
1347  assert(image != (Image *) NULL);
1348  assert(image->signature == MagickCoreSignature);
1349  if (IsEventLogging() != MagickFalse)
1350  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1351  channel_statistics=GetImageStatistics(image,exception);
1352  if (channel_statistics == (ChannelStatistics *) NULL)
1353  return(MagickFalse);
1354  *mean=channel_statistics[CompositePixelChannel].mean;
1355  *standard_deviation=
1356  channel_statistics[CompositePixelChannel].standard_deviation;
1357  channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
1358  channel_statistics);
1359  return(MagickTrue);
1360 }
1361 ␌
1362 /*
1363 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1364 % %
1365 % %
1366 % %
1367 % G e t I m a g e M e d i a n %
1368 % %
1369 % %
1370 % %
1371 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1372 %
1373 % GetImageMedian() returns the median pixel of one or more image channels.
1374 %
1375 % The format of the GetImageMedian method is:
1376 %
1377 % MagickBooleanType GetImageMedian(const Image *image,double *median,
1378 % ExceptionInfo *exception)
1379 %
1380 % A description of each parameter follows:
1381 %
1382 % o image: the image.
1383 %
1384 % o median: the average value in the channel.
1385 %
1386 % o exception: return any errors or warnings in this structure.
1387 %
1388 */
1389 MagickExport MagickBooleanType GetImageMedian(const Image *image,double *median,
1390  ExceptionInfo *exception)
1391 {
1393  *channel_statistics;
1394 
1395  assert(image != (Image *) NULL);
1396  assert(image->signature == MagickCoreSignature);
1397  if (IsEventLogging() != MagickFalse)
1398  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1399  channel_statistics=GetImageStatistics(image,exception);
1400  if (channel_statistics == (ChannelStatistics *) NULL)
1401  return(MagickFalse);
1402  *median=channel_statistics[CompositePixelChannel].median;
1403  channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
1404  channel_statistics);
1405  return(MagickTrue);
1406 }
1407 ␌
1408 /*
1409 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1410 % %
1411 % %
1412 % %
1413 % G e t I m a g e M o m e n t s %
1414 % %
1415 % %
1416 % %
1417 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1418 %
1419 % GetImageMoments() returns the normalized moments of one or more image
1420 % channels.
1421 %
1422 % The format of the GetImageMoments method is:
1423 %
1424 % ChannelMoments *GetImageMoments(const Image *image,
1425 % ExceptionInfo *exception)
1426 %
1427 % A description of each parameter follows:
1428 %
1429 % o image: the image.
1430 %
1431 % o exception: return any errors or warnings in this structure.
1432 %
1433 */
1434 MagickExport ChannelMoments *GetImageMoments(const Image *image,
1435  ExceptionInfo *exception)
1436 {
1437 #define MaxNumberImageMoments 8
1438 
1439  CacheView
1440  *image_view;
1441 
1443  *channel_moments;
1444 
1445  double
1446  channels,
1447  M00[2*MaxPixelChannels+1],
1448  M01[2*MaxPixelChannels+1],
1449  M02[2*MaxPixelChannels+1],
1450  M03[2*MaxPixelChannels+1],
1451  M10[2*MaxPixelChannels+1],
1452  M11[2*MaxPixelChannels+1],
1453  M12[2*MaxPixelChannels+1],
1454  M20[2*MaxPixelChannels+1],
1455  M21[2*MaxPixelChannels+1],
1456  M22[2*MaxPixelChannels+1],
1457  M30[2*MaxPixelChannels+1];
1458 
1459  PointInfo
1460  centroid[2*MaxPixelChannels+1];
1461 
1462  ssize_t
1463  c,
1464  y;
1465 
1466  assert(image != (Image *) NULL);
1467  assert(image->signature == MagickCoreSignature);
1468  if (IsEventLogging() != MagickFalse)
1469  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1470  channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1,
1471  sizeof(*channel_moments));
1472  if (channel_moments == (ChannelMoments *) NULL)
1473  return(channel_moments);
1474  (void) memset(channel_moments,0,(MaxPixelChannels+1)*
1475  sizeof(*channel_moments));
1476  (void) memset(centroid,0,sizeof(centroid));
1477  (void) memset(M00,0,sizeof(M00));
1478  (void) memset(M01,0,sizeof(M01));
1479  (void) memset(M02,0,sizeof(M02));
1480  (void) memset(M03,0,sizeof(M03));
1481  (void) memset(M10,0,sizeof(M10));
1482  (void) memset(M11,0,sizeof(M11));
1483  (void) memset(M12,0,sizeof(M12));
1484  (void) memset(M20,0,sizeof(M20));
1485  (void) memset(M21,0,sizeof(M21));
1486  (void) memset(M22,0,sizeof(M22));
1487  (void) memset(M30,0,sizeof(M30));
1488  image_view=AcquireVirtualCacheView(image,exception);
1489  for (y=0; y < (ssize_t) image->rows; y++)
1490  {
1491  const Quantum
1492  *magick_restrict p;
1493 
1494  ssize_t
1495  x;
1496 
1497  /*
1498  Compute center of mass (centroid).
1499  */
1500  p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
1501  if (p == (const Quantum *) NULL)
1502  break;
1503  for (x=0; x < (ssize_t) image->columns; x++)
1504  {
1505  ssize_t
1506  i;
1507 
1508  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1509  {
1510  PixelChannel channel = GetPixelChannelChannel(image,i);
1511  PixelTrait traits = GetPixelChannelTraits(image,channel);
1512  if (traits == UndefinedPixelTrait)
1513  continue;
1514  if ((traits & UpdatePixelTrait) == 0)
1515  continue;
1516  M00[channel]+=QuantumScale*p[i];
1517  M00[MaxPixelChannels]+=QuantumScale*p[i];
1518  M10[channel]+=x*QuantumScale*p[i];
1519  M10[MaxPixelChannels]+=x*QuantumScale*p[i];
1520  M01[channel]+=y*QuantumScale*p[i];
1521  M01[MaxPixelChannels]+=y*QuantumScale*p[i];
1522  }
1523  p+=GetPixelChannels(image);
1524  }
1525  }
1526  for (c=0; c <= MaxPixelChannels; c++)
1527  {
1528  /*
1529  Compute center of mass (centroid).
1530  */
1531  centroid[c].x=M10[c]*PerceptibleReciprocal(M00[c]);
1532  centroid[c].y=M01[c]*PerceptibleReciprocal(M00[c]);
1533  }
1534  for (y=0; y < (ssize_t) image->rows; y++)
1535  {
1536  const Quantum
1537  *magick_restrict p;
1538 
1539  ssize_t
1540  x;
1541 
1542  /*
1543  Compute the image moments.
1544  */
1545  p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
1546  if (p == (const Quantum *) NULL)
1547  break;
1548  for (x=0; x < (ssize_t) image->columns; x++)
1549  {
1550  ssize_t
1551  i;
1552 
1553  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1554  {
1555  PixelChannel channel = GetPixelChannelChannel(image,i);
1556  PixelTrait traits = GetPixelChannelTraits(image,channel);
1557  if (traits == UndefinedPixelTrait)
1558  continue;
1559  if ((traits & UpdatePixelTrait) == 0)
1560  continue;
1561  M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
1562  QuantumScale*p[i];
1563  M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
1564  QuantumScale*p[i];
1565  M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1566  QuantumScale*p[i];
1567  M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1568  QuantumScale*p[i];
1569  M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
1570  QuantumScale*p[i];
1571  M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
1572  QuantumScale*p[i];
1573  M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1574  (y-centroid[channel].y)*QuantumScale*p[i];
1575  M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1576  (y-centroid[channel].y)*QuantumScale*p[i];
1577  M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
1578  (y-centroid[channel].y)*QuantumScale*p[i];
1579  M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)*
1580  (y-centroid[channel].y)*QuantumScale*p[i];
1581  M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1582  (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i];
1583  M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1584  (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i];
1585  M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1586  (x-centroid[channel].x)*QuantumScale*p[i];
1587  M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)*
1588  (x-centroid[channel].x)*QuantumScale*p[i];
1589  M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
1590  (y-centroid[channel].y)*QuantumScale*p[i];
1591  M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)*
1592  (y-centroid[channel].y)*QuantumScale*p[i];
1593  }
1594  p+=GetPixelChannels(image);
1595  }
1596  }
1597  channels=(double) GetImageChannels(image);
1598  M00[MaxPixelChannels]/=channels;
1599  M01[MaxPixelChannels]/=channels;
1600  M02[MaxPixelChannels]/=channels;
1601  M03[MaxPixelChannels]/=channels;
1602  M10[MaxPixelChannels]/=channels;
1603  M11[MaxPixelChannels]/=channels;
1604  M12[MaxPixelChannels]/=channels;
1605  M20[MaxPixelChannels]/=channels;
1606  M21[MaxPixelChannels]/=channels;
1607  M22[MaxPixelChannels]/=channels;
1608  M30[MaxPixelChannels]/=channels;
1609  for (c=0; c <= MaxPixelChannels; c++)
1610  {
1611  /*
1612  Compute elliptical angle, major and minor axes, eccentricity, & intensity.
1613  */
1614  channel_moments[c].centroid=centroid[c];
1615  channel_moments[c].ellipse_axis.x=sqrt((2.0*PerceptibleReciprocal(M00[c]))*
1616  ((M20[c]+M02[c])+sqrt(4.0*M11[c]*M11[c]+(M20[c]-M02[c])*(M20[c]-M02[c]))));
1617  channel_moments[c].ellipse_axis.y=sqrt((2.0*PerceptibleReciprocal(M00[c]))*
1618  ((M20[c]+M02[c])-sqrt(4.0*M11[c]*M11[c]+(M20[c]-M02[c])*(M20[c]-M02[c]))));
1619  channel_moments[c].ellipse_angle=RadiansToDegrees(1.0/2.0*atan(2.0*
1620  M11[c]*PerceptibleReciprocal(M20[c]-M02[c])));
1621  if (fabs(M11[c]) < 0.0)
1622  {
1623  if ((fabs(M20[c]-M02[c]) >= 0.0) &&
1624  ((M20[c]-M02[c]) < 0.0))
1625  channel_moments[c].ellipse_angle+=90.0;
1626  }
1627  else
1628  if (M11[c] < 0.0)
1629  {
1630  if (fabs(M20[c]-M02[c]) >= 0.0)
1631  {
1632  if ((M20[c]-M02[c]) < 0.0)
1633  channel_moments[c].ellipse_angle+=90.0;
1634  else
1635  channel_moments[c].ellipse_angle+=180.0;
1636  }
1637  }
1638  else
1639  if ((fabs(M20[c]-M02[c]) >= 0.0) && ((M20[c]-M02[c]) < 0.0))
1640  channel_moments[c].ellipse_angle+=90.0;
1641  channel_moments[c].ellipse_eccentricity=sqrt(1.0-(
1642  channel_moments[c].ellipse_axis.y*
1643  channel_moments[c].ellipse_axis.y*PerceptibleReciprocal(
1644  channel_moments[c].ellipse_axis.x*
1645  channel_moments[c].ellipse_axis.x)));
1646  channel_moments[c].ellipse_intensity=M00[c]*
1647  PerceptibleReciprocal(MagickPI*channel_moments[c].ellipse_axis.x*
1648  channel_moments[c].ellipse_axis.y+MagickEpsilon);
1649  }
1650  for (c=0; c <= MaxPixelChannels; c++)
1651  {
1652  /*
1653  Normalize image moments.
1654  */
1655  M10[c]=0.0;
1656  M01[c]=0.0;
1657  M11[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(1.0+1.0)/2.0));
1658  M20[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(2.0+0.0)/2.0));
1659  M02[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(0.0+2.0)/2.0));
1660  M21[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(2.0+1.0)/2.0));
1661  M12[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(1.0+2.0)/2.0));
1662  M22[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(2.0+2.0)/2.0));
1663  M30[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(3.0+0.0)/2.0));
1664  M03[c]*=PerceptibleReciprocal(pow(M00[c],1.0+(0.0+3.0)/2.0));
1665  M00[c]=1.0;
1666  }
1667  image_view=DestroyCacheView(image_view);
1668  for (c=0; c <= MaxPixelChannels; c++)
1669  {
1670  /*
1671  Compute Hu invariant moments.
1672  */
1673  channel_moments[c].invariant[0]=M20[c]+M02[c];
1674  channel_moments[c].invariant[1]=(M20[c]-M02[c])*(M20[c]-M02[c])+4.0*M11[c]*
1675  M11[c];
1676  channel_moments[c].invariant[2]=(M30[c]-3.0*M12[c])*(M30[c]-3.0*M12[c])+
1677  (3.0*M21[c]-M03[c])*(3.0*M21[c]-M03[c]);
1678  channel_moments[c].invariant[3]=(M30[c]+M12[c])*(M30[c]+M12[c])+
1679  (M21[c]+M03[c])*(M21[c]+M03[c]);
1680  channel_moments[c].invariant[4]=(M30[c]-3.0*M12[c])*(M30[c]+M12[c])*
1681  ((M30[c]+M12[c])*(M30[c]+M12[c])-3.0*(M21[c]+M03[c])*(M21[c]+M03[c]))+
1682  (3.0*M21[c]-M03[c])*(M21[c]+M03[c])*(3.0*(M30[c]+M12[c])*(M30[c]+M12[c])-
1683  (M21[c]+M03[c])*(M21[c]+M03[c]));
1684  channel_moments[c].invariant[5]=(M20[c]-M02[c])*((M30[c]+M12[c])*
1685  (M30[c]+M12[c])-(M21[c]+M03[c])*(M21[c]+M03[c]))+4.0*M11[c]*
1686  (M30[c]+M12[c])*(M21[c]+M03[c]);
1687  channel_moments[c].invariant[6]=(3.0*M21[c]-M03[c])*(M30[c]+M12[c])*
1688  ((M30[c]+M12[c])*(M30[c]+M12[c])-3.0*(M21[c]+M03[c])*(M21[c]+M03[c]))-
1689  (M30[c]-3*M12[c])*(M21[c]+M03[c])*(3.0*(M30[c]+M12[c])*(M30[c]+M12[c])-
1690  (M21[c]+M03[c])*(M21[c]+M03[c]));
1691  channel_moments[c].invariant[7]=M11[c]*((M30[c]+M12[c])*(M30[c]+M12[c])-
1692  (M03[c]+M21[c])*(M03[c]+M21[c]))-(M20[c]-M02[c])*(M30[c]+M12[c])*
1693  (M03[c]+M21[c]);
1694  }
1695  if (y < (ssize_t) image->rows)
1696  channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments);
1697  return(channel_moments);
1698 }
1699 ␌
1700 /*
1701 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1702 % %
1703 % %
1704 % %
1705 % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h %
1706 % %
1707 % %
1708 % %
1709 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1710 %
1711 % GetImagePerceptualHash() returns the perceptual hash of one or more
1712 % image channels.
1713 %
1714 % The format of the GetImagePerceptualHash method is:
1715 %
1716 % ChannelPerceptualHash *GetImagePerceptualHash(const Image *image,
1717 % ExceptionInfo *exception)
1718 %
1719 % A description of each parameter follows:
1720 %
1721 % o image: the image.
1722 %
1723 % o exception: return any errors or warnings in this structure.
1724 %
1725 */
1726 
1727 static inline double MagickLog10(const double x)
1728 {
1729 #define Log10Epsilon (1.0e-11)
1730 
1731  if (fabs(x) < Log10Epsilon)
1732  return(log10(Log10Epsilon));
1733  return(log10(fabs(x)));
1734 }
1735 
1736 MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image,
1737  ExceptionInfo *exception)
1738 {
1740  *perceptual_hash;
1741 
1742  char
1743  *colorspaces,
1744  *p,
1745  *q;
1746 
1747  const char
1748  *artifact;
1749 
1750  MagickBooleanType
1751  status;
1752 
1753  ssize_t
1754  i;
1755 
1756  perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory(
1757  MaxPixelChannels+1UL,sizeof(*perceptual_hash));
1758  if (perceptual_hash == (ChannelPerceptualHash *) NULL)
1759  return((ChannelPerceptualHash *) NULL);
1760  artifact=GetImageArtifact(image,"phash:colorspaces");
1761  if (artifact != NULL)
1762  colorspaces=AcquireString(artifact);
1763  else
1764  colorspaces=AcquireString("sRGB,HCLp");
1765  perceptual_hash[0].number_colorspaces=0;
1766  perceptual_hash[0].number_channels=0;
1767  q=colorspaces;
1768  for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++)
1769  {
1771  *moments;
1772 
1773  Image
1774  *hash_image;
1775 
1776  size_t
1777  j;
1778 
1779  ssize_t
1780  channel,
1781  colorspace;
1782 
1783  if (i >= MaximumNumberOfPerceptualColorspaces)
1784  break;
1785  colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p);
1786  if (colorspace < 0)
1787  break;
1788  perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace;
1789  hash_image=BlurImage(image,0.0,1.0,exception);
1790  if (hash_image == (Image *) NULL)
1791  break;
1792  hash_image->depth=8;
1793  status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace,
1794  exception);
1795  if (status == MagickFalse)
1796  break;
1797  moments=GetImageMoments(hash_image,exception);
1798  perceptual_hash[0].number_colorspaces++;
1799  perceptual_hash[0].number_channels+=GetImageChannels(hash_image);
1800  hash_image=DestroyImage(hash_image);
1801  if (moments == (ChannelMoments *) NULL)
1802  break;
1803  for (channel=0; channel <= MaxPixelChannels; channel++)
1804  for (j=0; j < MaximumNumberOfImageMoments; j++)
1805  perceptual_hash[channel].phash[i][j]=
1806  (-MagickLog10(moments[channel].invariant[j]));
1807  moments=(ChannelMoments *) RelinquishMagickMemory(moments);
1808  }
1809  colorspaces=DestroyString(colorspaces);
1810  return(perceptual_hash);
1811 }
1812 ␌
1813 /*
1814 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1815 % %
1816 % %
1817 % %
1818 % G e t I m a g e R a n g e %
1819 % %
1820 % %
1821 % %
1822 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1823 %
1824 % GetImageRange() returns the range of one or more image channels.
1825 %
1826 % The format of the GetImageRange method is:
1827 %
1828 % MagickBooleanType GetImageRange(const Image *image,double *minima,
1829 % double *maxima,ExceptionInfo *exception)
1830 %
1831 % A description of each parameter follows:
1832 %
1833 % o image: the image.
1834 %
1835 % o minima: the minimum value in the channel.
1836 %
1837 % o maxima: the maximum value in the channel.
1838 %
1839 % o exception: return any errors or warnings in this structure.
1840 %
1841 */
1842 MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima,
1843  double *maxima,ExceptionInfo *exception)
1844 {
1845  CacheView
1846  *image_view;
1847 
1848  MagickBooleanType
1849  initialize,
1850  status;
1851 
1852  ssize_t
1853  y;
1854 
1855  assert(image != (Image *) NULL);
1856  assert(image->signature == MagickCoreSignature);
1857  if (IsEventLogging() != MagickFalse)
1858  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1859  status=MagickTrue;
1860  initialize=MagickTrue;
1861  *maxima=0.0;
1862  *minima=0.0;
1863  image_view=AcquireVirtualCacheView(image,exception);
1864 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1865  #pragma omp parallel for schedule(static) shared(status,initialize) \
1866  magick_number_threads(image,image,image->rows,1)
1867 #endif
1868  for (y=0; y < (ssize_t) image->rows; y++)
1869  {
1870  double
1871  row_maxima = 0.0,
1872  row_minima = 0.0;
1873 
1874  MagickBooleanType
1875  row_initialize;
1876 
1877  const Quantum
1878  *magick_restrict p;
1879 
1880  ssize_t
1881  x;
1882 
1883  if (status == MagickFalse)
1884  continue;
1885  p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
1886  if (p == (const Quantum *) NULL)
1887  {
1888  status=MagickFalse;
1889  continue;
1890  }
1891  row_initialize=MagickTrue;
1892  for (x=0; x < (ssize_t) image->columns; x++)
1893  {
1894  ssize_t
1895  i;
1896 
1897  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1898  {
1899  PixelChannel channel = GetPixelChannelChannel(image,i);
1900  PixelTrait traits = GetPixelChannelTraits(image,channel);
1901  if (traits == UndefinedPixelTrait)
1902  continue;
1903  if ((traits & UpdatePixelTrait) == 0)
1904  continue;
1905  if (row_initialize != MagickFalse)
1906  {
1907  row_minima=(double) p[i];
1908  row_maxima=(double) p[i];
1909  row_initialize=MagickFalse;
1910  }
1911  else
1912  {
1913  if ((double) p[i] < row_minima)
1914  row_minima=(double) p[i];
1915  if ((double) p[i] > row_maxima)
1916  row_maxima=(double) p[i];
1917  }
1918  }
1919  p+=GetPixelChannels(image);
1920  }
1921 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1922 #pragma omp critical (MagickCore_GetImageRange)
1923 #endif
1924  {
1925  if (initialize != MagickFalse)
1926  {
1927  *minima=row_minima;
1928  *maxima=row_maxima;
1929  initialize=MagickFalse;
1930  }
1931  else
1932  {
1933  if (row_minima < *minima)
1934  *minima=row_minima;
1935  if (row_maxima > *maxima)
1936  *maxima=row_maxima;
1937  }
1938  }
1939  }
1940  image_view=DestroyCacheView(image_view);
1941  return(status);
1942 }
1943 ␌
1944 /*
1945 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1946 % %
1947 % %
1948 % %
1949 % G e t I m a g e S t a t i s t i c s %
1950 % %
1951 % %
1952 % %
1953 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1954 %
1955 % GetImageStatistics() returns statistics for each channel in the image. The
1956 % statistics include the channel depth, its minima, maxima, mean, standard
1957 % deviation, kurtosis and skewness. You can access the red channel mean, for
1958 % example, like this:
1959 %
1960 % channel_statistics=GetImageStatistics(image,exception);
1961 % red_mean=channel_statistics[RedPixelChannel].mean;
1962 %
1963 % Use MagickRelinquishMemory() to free the statistics buffer.
1964 %
1965 % The format of the GetImageStatistics method is:
1966 %
1967 % ChannelStatistics *GetImageStatistics(const Image *image,
1968 % ExceptionInfo *exception)
1969 %
1970 % A description of each parameter follows:
1971 %
1972 % o image: the image.
1973 %
1974 % o exception: return any errors or warnings in this structure.
1975 %
1976 */
1977 
1978 static ssize_t GetMedianPixel(Quantum *pixels,const size_t n)
1979 {
1980 #define SwapPixels(alpha,beta) \
1981 { \
1982  Quantum gamma=(alpha); \
1983  (alpha)=(beta);(beta)=gamma; \
1984 }
1985 
1986  ssize_t
1987  low = 0,
1988  high = (ssize_t) n-1,
1989  median = (low+high)/2;
1990 
1991  for ( ; ; )
1992  {
1993  ssize_t
1994  l = low+1,
1995  h = high,
1996  mid = (low+high)/2;
1997 
1998  if (high <= low)
1999  return(median);
2000  if (high == (low+1))
2001  {
2002  if (pixels[low] > pixels[high])
2003  SwapPixels(pixels[low],pixels[high]);
2004  return(median);
2005  }
2006  if (pixels[mid] > pixels[high])
2007  SwapPixels(pixels[mid],pixels[high]);
2008  if (pixels[low] > pixels[high])
2009  SwapPixels(pixels[low], pixels[high]);
2010  if (pixels[mid] > pixels[low])
2011  SwapPixels(pixels[mid],pixels[low]);
2012  SwapPixels(pixels[mid],pixels[low+1]);
2013  for ( ; ; )
2014  {
2015  do l++; while (pixels[low] > pixels[l]);
2016  do h--; while (pixels[h] > pixels[low]);
2017  if (h < l)
2018  break;
2019  SwapPixels(pixels[l],pixels[h]);
2020  }
2021  SwapPixels(pixels[low],pixels[h]);
2022  if (h <= median)
2023  low=l;
2024  if (h >= median)
2025  high=h-1;
2026  }
2027 }
2028 
2029 MagickExport ChannelStatistics *GetImageStatistics(const Image *image,
2030  ExceptionInfo *exception)
2031 {
2033  *channel_statistics;
2034 
2035  double
2036  area,
2037  channels,
2038  *histogram,
2039  standard_deviation;
2040 
2041  MagickStatusType
2042  status;
2043 
2044  MemoryInfo
2045  *median_info;
2046 
2047  Quantum
2048  *median;
2049 
2050  QuantumAny
2051  range;
2052 
2053  size_t
2054  depth;
2055 
2056  ssize_t
2057  i,
2058  y;
2059 
2060  assert(image != (Image *) NULL);
2061  assert(image->signature == MagickCoreSignature);
2062  if (IsEventLogging() != MagickFalse)
2063  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2064  histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)*
2065  sizeof(*histogram));
2066  channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(
2067  MaxPixelChannels+1,sizeof(*channel_statistics));
2068  if ((channel_statistics == (ChannelStatistics *) NULL) ||
2069  (histogram == (double *) NULL))
2070  {
2071  if (histogram != (double *) NULL)
2072  histogram=(double *) RelinquishMagickMemory(histogram);
2073  if (channel_statistics != (ChannelStatistics *) NULL)
2074  channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
2075  channel_statistics);
2076  return(channel_statistics);
2077  }
2078  (void) memset(channel_statistics,0,(MaxPixelChannels+1)*
2079  sizeof(*channel_statistics));
2080  for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
2081  {
2082  channel_statistics[i].depth=1;
2083  channel_statistics[i].maxima=(-MagickMaximumValue);
2084  channel_statistics[i].minima=MagickMaximumValue;
2085  }
2086  (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
2087  sizeof(*histogram));
2088  for (y=0; y < (ssize_t) image->rows; y++)
2089  {
2090  const Quantum
2091  *magick_restrict p;
2092 
2093  ssize_t
2094  x;
2095 
2096  /*
2097  Compute pixel statistics.
2098  */
2099  p=GetVirtualPixels(image,0,y,image->columns,1,exception);
2100  if (p == (const Quantum *) NULL)
2101  break;
2102  for (x=0; x < (ssize_t) image->columns; x++)
2103  {
2104  if (GetPixelReadMask(image,p) <= (QuantumRange/2))
2105  {
2106  p+=GetPixelChannels(image);
2107  continue;
2108  }
2109  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2110  {
2111  PixelChannel channel = GetPixelChannelChannel(image,i);
2112  PixelTrait traits = GetPixelChannelTraits(image,channel);
2113  if (traits == UndefinedPixelTrait)
2114  continue;
2115  if ((traits & UpdatePixelTrait) == 0)
2116  continue;
2117  if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH)
2118  {
2119  depth=channel_statistics[channel].depth;
2120  range=GetQuantumRange(depth);
2121  status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range),
2122  range) ? MagickTrue : MagickFalse;
2123  if (status != MagickFalse)
2124  {
2125  channel_statistics[channel].depth++;
2126  if (channel_statistics[channel].depth >
2127  channel_statistics[CompositePixelChannel].depth)
2128  channel_statistics[CompositePixelChannel].depth=
2129  channel_statistics[channel].depth;
2130  i--;
2131  continue;
2132  }
2133  }
2134  if ((double) p[i] < channel_statistics[channel].minima)
2135  channel_statistics[channel].minima=(double) p[i];
2136  if ((double) p[i] > channel_statistics[channel].maxima)
2137  channel_statistics[channel].maxima=(double) p[i];
2138  channel_statistics[channel].sum+=p[i];
2139  channel_statistics[channel].sum_squared+=(double) p[i]*p[i];
2140  channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i];
2141  channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*
2142  p[i];
2143  channel_statistics[channel].area++;
2144  if ((double) p[i] < channel_statistics[CompositePixelChannel].minima)
2145  channel_statistics[CompositePixelChannel].minima=(double) p[i];
2146  if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima)
2147  channel_statistics[CompositePixelChannel].maxima=(double) p[i];
2148  histogram[GetPixelChannels(image)*ScaleQuantumToMap(
2149  ClampToQuantum((double) p[i]))+i]++;
2150  channel_statistics[CompositePixelChannel].sum+=(double) p[i];
2151  channel_statistics[CompositePixelChannel].sum_squared+=(double)
2152  p[i]*p[i];
2153  channel_statistics[CompositePixelChannel].sum_cubed+=(double)
2154  p[i]*p[i]*p[i];
2155  channel_statistics[CompositePixelChannel].sum_fourth_power+=(double)
2156  p[i]*p[i]*p[i]*p[i];
2157  channel_statistics[CompositePixelChannel].area++;
2158  }
2159  p+=GetPixelChannels(image);
2160  }
2161  }
2162  for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
2163  {
2164  /*
2165  Normalize pixel statistics.
2166  */
2167  area=PerceptibleReciprocal(channel_statistics[i].area);
2168  channel_statistics[i].sum*=area;
2169  channel_statistics[i].sum_squared*=area;
2170  channel_statistics[i].sum_cubed*=area;
2171  channel_statistics[i].sum_fourth_power*=area;
2172  channel_statistics[i].mean=channel_statistics[i].sum;
2173  channel_statistics[i].variance=channel_statistics[i].sum_squared;
2174  standard_deviation=sqrt(channel_statistics[i].variance-
2175  (channel_statistics[i].mean*channel_statistics[i].mean));
2176  standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area-
2177  1.0)*channel_statistics[i].area*standard_deviation*standard_deviation);
2178  channel_statistics[i].standard_deviation=standard_deviation;
2179  }
2180  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2181  {
2182  double
2183  number_bins;
2184 
2185  ssize_t
2186  j;
2187 
2188  /*
2189  Compute pixel entropy.
2190  */
2191  PixelChannel channel = GetPixelChannelChannel(image,i);
2192  number_bins=0.0;
2193  for (j=0; j <= (ssize_t) MaxMap; j++)
2194  if (histogram[GetPixelChannels(image)*j+i] > 0.0)
2195  number_bins++;
2196  area=PerceptibleReciprocal(channel_statistics[channel].area);
2197  for (j=0; j <= (ssize_t) MaxMap; j++)
2198  {
2199  double
2200  count;
2201 
2202  count=area*histogram[GetPixelChannels(image)*j+i];
2203  channel_statistics[channel].entropy+=-count*MagickLog10(count)*
2204  PerceptibleReciprocal(MagickLog10(number_bins));
2205  channel_statistics[CompositePixelChannel].entropy+=-count*
2206  MagickLog10(count)*PerceptibleReciprocal(MagickLog10(number_bins))/
2207  GetPixelChannels(image);
2208  }
2209  }
2210  histogram=(double *) RelinquishMagickMemory(histogram);
2211  for (i=0; i <= (ssize_t) MaxPixelChannels; i++)
2212  {
2213  /*
2214  Compute kurtosis & skewness statistics.
2215  */
2216  standard_deviation=PerceptibleReciprocal(
2217  channel_statistics[i].standard_deviation);
2218  channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0*
2219  channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0*
2220  channel_statistics[i].mean*channel_statistics[i].mean*
2221  channel_statistics[i].mean)*(standard_deviation*standard_deviation*
2222  standard_deviation);
2223  channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0*
2224  channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0*
2225  channel_statistics[i].mean*channel_statistics[i].mean*
2226  channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean*
2227  channel_statistics[i].mean*1.0*channel_statistics[i].mean*
2228  channel_statistics[i].mean)*(standard_deviation*standard_deviation*
2229  standard_deviation*standard_deviation)-3.0;
2230  }
2231  median_info=AcquireVirtualMemory(image->columns,image->rows*sizeof(*median));
2232  if (median_info == (MemoryInfo *) NULL)
2233  (void) ThrowMagickException(exception,GetMagickModule(),
2234  ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
2235  else
2236  {
2237  median=(Quantum *) GetVirtualMemoryBlob(median_info);
2238  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2239  {
2240  size_t
2241  n = 0;
2242 
2243  /*
2244  Compute median statistics for each channel.
2245  */
2246  PixelChannel channel = GetPixelChannelChannel(image,i);
2247  PixelTrait traits = GetPixelChannelTraits(image,channel);
2248  if (traits == UndefinedPixelTrait)
2249  continue;
2250  if ((traits & UpdatePixelTrait) == 0)
2251  continue;
2252  for (y=0; y < (ssize_t) image->rows; y++)
2253  {
2254  const Quantum
2255  *magick_restrict p;
2256 
2257  ssize_t
2258  x;
2259 
2260  p=GetVirtualPixels(image,0,y,image->columns,1,exception);
2261  if (p == (const Quantum *) NULL)
2262  break;
2263  for (x=0; x < (ssize_t) image->columns; x++)
2264  {
2265  if (GetPixelReadMask(image,p) <= (QuantumRange/2))
2266  {
2267  p+=GetPixelChannels(image);
2268  continue;
2269  }
2270  median[n++]=p[i];
2271  }
2272  p+=GetPixelChannels(image);
2273  }
2274  channel_statistics[channel].median=(double) median[
2275  GetMedianPixel(median,n)];
2276  }
2277  median_info=RelinquishVirtualMemory(median_info);
2278  }
2279  channel_statistics[CompositePixelChannel].mean=0.0;
2280  channel_statistics[CompositePixelChannel].median=0.0;
2281  channel_statistics[CompositePixelChannel].standard_deviation=0.0;
2282  channel_statistics[CompositePixelChannel].entropy=0.0;
2283  for (i=0; i < (ssize_t) MaxPixelChannels; i++)
2284  {
2285  channel_statistics[CompositePixelChannel].mean+=
2286  channel_statistics[i].mean;
2287  channel_statistics[CompositePixelChannel].median+=
2288  channel_statistics[i].median;
2289  channel_statistics[CompositePixelChannel].standard_deviation+=
2290  channel_statistics[i].standard_deviation;
2291  channel_statistics[CompositePixelChannel].entropy+=
2292  channel_statistics[i].entropy;
2293  }
2294  channels=(double) GetImageChannels(image);
2295  channel_statistics[CompositePixelChannel].mean/=channels;
2296  channel_statistics[CompositePixelChannel].median/=channels;
2297  channel_statistics[CompositePixelChannel].standard_deviation/=channels;
2298  channel_statistics[CompositePixelChannel].entropy/=channels;
2299  if (y < (ssize_t) image->rows)
2300  channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
2301  channel_statistics);
2302  return(channel_statistics);
2303 }
2304 ␌
2305 /*
2306 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2307 % %
2308 % %
2309 % %
2310 % P o l y n o m i a l I m a g e %
2311 % %
2312 % %
2313 % %
2314 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2315 %
2316 % PolynomialImage() returns a new image where each pixel is the sum of the
2317 % pixels in the image sequence after applying its corresponding terms
2318 % (coefficient and degree pairs).
2319 %
2320 % The format of the PolynomialImage method is:
2321 %
2322 % Image *PolynomialImage(const Image *images,const size_t number_terms,
2323 % const double *terms,ExceptionInfo *exception)
2324 %
2325 % A description of each parameter follows:
2326 %
2327 % o images: the image sequence.
2328 %
2329 % o number_terms: the number of terms in the list. The actual list length
2330 % is 2 x number_terms + 1 (the constant).
2331 %
2332 % o terms: the list of polynomial coefficients and degree pairs and a
2333 % constant.
2334 %
2335 % o exception: return any errors or warnings in this structure.
2336 %
2337 */
2338 MagickExport Image *PolynomialImage(const Image *images,
2339  const size_t number_terms,const double *terms,ExceptionInfo *exception)
2340 {
2341 #define PolynomialImageTag "Polynomial/Image"
2342 
2343  CacheView
2344  *polynomial_view;
2345 
2346  Image
2347  *image;
2348 
2349  MagickBooleanType
2350  status;
2351 
2352  MagickOffsetType
2353  progress;
2354 
2356  **magick_restrict polynomial_pixels;
2357 
2358  size_t
2359  number_images;
2360 
2361  ssize_t
2362  y;
2363 
2364  assert(images != (Image *) NULL);
2365  assert(images->signature == MagickCoreSignature);
2366  if (IsEventLogging() != MagickFalse)
2367  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2368  assert(exception != (ExceptionInfo *) NULL);
2369  assert(exception->signature == MagickCoreSignature);
2370  image=AcquireImageCanvas(images,exception);
2371  if (image == (Image *) NULL)
2372  return((Image *) NULL);
2373  if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2374  {
2375  image=DestroyImage(image);
2376  return((Image *) NULL);
2377  }
2378  number_images=GetImageListLength(images);
2379  polynomial_pixels=AcquirePixelTLS(images);
2380  if (polynomial_pixels == (PixelChannels **) NULL)
2381  {
2382  image=DestroyImage(image);
2383  (void) ThrowMagickException(exception,GetMagickModule(),
2384  ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2385  return((Image *) NULL);
2386  }
2387  /*
2388  Polynomial image pixels.
2389  */
2390  status=MagickTrue;
2391  progress=0;
2392  polynomial_view=AcquireAuthenticCacheView(image,exception);
2393 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2394  #pragma omp parallel for schedule(static) shared(progress,status) \
2395  magick_number_threads(image,image,image->rows,1)
2396 #endif
2397  for (y=0; y < (ssize_t) image->rows; y++)
2398  {
2399  CacheView
2400  *image_view;
2401 
2402  const Image
2403  *next;
2404 
2405  const int
2406  id = GetOpenMPThreadId();
2407 
2409  *polynomial_pixel;
2410 
2411  Quantum
2412  *magick_restrict q;
2413 
2414  ssize_t
2415  i,
2416  j,
2417  x;
2418 
2419  if (status == MagickFalse)
2420  continue;
2421  q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1,
2422  exception);
2423  if (q == (Quantum *) NULL)
2424  {
2425  status=MagickFalse;
2426  continue;
2427  }
2428  polynomial_pixel=polynomial_pixels[id];
2429  for (j=0; j < (ssize_t) image->columns; j++)
2430  for (i=0; i < MaxPixelChannels; i++)
2431  polynomial_pixel[j].channel[i]=0.0;
2432  next=images;
2433  for (j=0; j < (ssize_t) number_images; j++)
2434  {
2435  const Quantum
2436  *p;
2437 
2438  if (j >= (ssize_t) number_terms)
2439  continue;
2440  image_view=AcquireVirtualCacheView(next,exception);
2441  p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2442  if (p == (const Quantum *) NULL)
2443  {
2444  image_view=DestroyCacheView(image_view);
2445  break;
2446  }
2447  for (x=0; x < (ssize_t) image->columns; x++)
2448  {
2449  for (i=0; i < (ssize_t) GetPixelChannels(next); i++)
2450  {
2451  MagickRealType
2452  coefficient,
2453  degree;
2454 
2455  PixelChannel channel = GetPixelChannelChannel(image,i);
2456  PixelTrait traits = GetPixelChannelTraits(next,channel);
2457  PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel);
2458  if ((traits == UndefinedPixelTrait) ||
2459  (polynomial_traits == UndefinedPixelTrait))
2460  continue;
2461  if ((traits & UpdatePixelTrait) == 0)
2462  continue;
2463  coefficient=(MagickRealType) terms[2*j];
2464  degree=(MagickRealType) terms[(j << 1)+1];
2465  polynomial_pixel[x].channel[i]+=coefficient*
2466  pow(QuantumScale*GetPixelChannel(image,channel,p),degree);
2467  }
2468  p+=GetPixelChannels(next);
2469  }
2470  image_view=DestroyCacheView(image_view);
2471  next=GetNextImageInList(next);
2472  }
2473  for (x=0; x < (ssize_t) image->columns; x++)
2474  {
2475  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2476  {
2477  PixelChannel channel = GetPixelChannelChannel(image,i);
2478  PixelTrait traits = GetPixelChannelTraits(image,channel);
2479  if (traits == UndefinedPixelTrait)
2480  continue;
2481  if ((traits & UpdatePixelTrait) == 0)
2482  continue;
2483  q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]);
2484  }
2485  q+=GetPixelChannels(image);
2486  }
2487  if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse)
2488  status=MagickFalse;
2489  if (images->progress_monitor != (MagickProgressMonitor) NULL)
2490  {
2491  MagickBooleanType
2492  proceed;
2493 
2494 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2495  #pragma omp atomic
2496 #endif
2497  progress++;
2498  proceed=SetImageProgress(images,PolynomialImageTag,progress,
2499  image->rows);
2500  if (proceed == MagickFalse)
2501  status=MagickFalse;
2502  }
2503  }
2504  polynomial_view=DestroyCacheView(polynomial_view);
2505  polynomial_pixels=DestroyPixelTLS(images,polynomial_pixels);
2506  if (status == MagickFalse)
2507  image=DestroyImage(image);
2508  return(image);
2509 }
2510 ␌
2511 /*
2512 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2513 % %
2514 % %
2515 % %
2516 % S t a t i s t i c I m a g e %
2517 % %
2518 % %
2519 % %
2520 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2521 %
2522 % StatisticImage() makes each pixel the min / max / median / mode / etc. of
2523 % the neighborhood of the specified width and height.
2524 %
2525 % The format of the StatisticImage method is:
2526 %
2527 % Image *StatisticImage(const Image *image,const StatisticType type,
2528 % const size_t width,const size_t height,ExceptionInfo *exception)
2529 %
2530 % A description of each parameter follows:
2531 %
2532 % o image: the image.
2533 %
2534 % o type: the statistic type (median, mode, etc.).
2535 %
2536 % o width: the width of the pixel neighborhood.
2537 %
2538 % o height: the height of the pixel neighborhood.
2539 %
2540 % o exception: return any errors or warnings in this structure.
2541 %
2542 */
2543 
2544 typedef struct _SkipNode
2545 {
2546  size_t
2547  next[9],
2548  count,
2549  signature;
2550 } SkipNode;
2551 
2552 typedef struct _SkipList
2553 {
2554  ssize_t
2555  level;
2556 
2557  SkipNode
2558  *nodes;
2559 } SkipList;
2560 
2561 typedef struct _PixelList
2562 {
2563  size_t
2564  length,
2565  seed;
2566 
2567  SkipList
2568  skip_list;
2569 
2570  size_t
2571  signature;
2572 } PixelList;
2573 
2574 static PixelList *DestroyPixelList(PixelList *pixel_list)
2575 {
2576  if (pixel_list == (PixelList *) NULL)
2577  return((PixelList *) NULL);
2578  if (pixel_list->skip_list.nodes != (SkipNode *) NULL)
2579  pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory(
2580  pixel_list->skip_list.nodes);
2581  pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
2582  return(pixel_list);
2583 }
2584 
2585 static PixelList **DestroyPixelListTLS(PixelList **pixel_list)
2586 {
2587  ssize_t
2588  i;
2589 
2590  assert(pixel_list != (PixelList **) NULL);
2591  for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
2592  if (pixel_list[i] != (PixelList *) NULL)
2593  pixel_list[i]=DestroyPixelList(pixel_list[i]);
2594  pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list);
2595  return(pixel_list);
2596 }
2597 
2598 static PixelList *AcquirePixelList(const size_t width,const size_t height)
2599 {
2600  PixelList
2601  *pixel_list;
2602 
2603  pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list));
2604  if (pixel_list == (PixelList *) NULL)
2605  return(pixel_list);
2606  (void) memset((void *) pixel_list,0,sizeof(*pixel_list));
2607  pixel_list->length=width*height;
2608  pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL,
2609  sizeof(*pixel_list->skip_list.nodes));
2610  if (pixel_list->skip_list.nodes == (SkipNode *) NULL)
2611  return(DestroyPixelList(pixel_list));
2612  (void) memset(pixel_list->skip_list.nodes,0,65537UL*
2613  sizeof(*pixel_list->skip_list.nodes));
2614  pixel_list->signature=MagickCoreSignature;
2615  return(pixel_list);
2616 }
2617 
2618 static PixelList **AcquirePixelListTLS(const size_t width,
2619  const size_t height)
2620 {
2621  PixelList
2622  **pixel_list;
2623 
2624  ssize_t
2625  i;
2626 
2627  size_t
2628  number_threads;
2629 
2630  number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
2631  pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
2632  sizeof(*pixel_list));
2633  if (pixel_list == (PixelList **) NULL)
2634  return((PixelList **) NULL);
2635  (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list));
2636  for (i=0; i < (ssize_t) number_threads; i++)
2637  {
2638  pixel_list[i]=AcquirePixelList(width,height);
2639  if (pixel_list[i] == (PixelList *) NULL)
2640  return(DestroyPixelListTLS(pixel_list));
2641  }
2642  return(pixel_list);
2643 }
2644 
2645 static void AddNodePixelList(PixelList *pixel_list,const size_t color)
2646 {
2647  SkipList
2648  *p;
2649 
2650  ssize_t
2651  level;
2652 
2653  size_t
2654  search,
2655  update[9];
2656 
2657  /*
2658  Initialize the node.
2659  */
2660  p=(&pixel_list->skip_list);
2661  p->nodes[color].signature=pixel_list->signature;
2662  p->nodes[color].count=1;
2663  /*
2664  Determine where it belongs in the list.
2665  */
2666  search=65536UL;
2667  for (level=p->level; level >= 0; level--)
2668  {
2669  while (p->nodes[search].next[level] < color)
2670  search=p->nodes[search].next[level];
2671  update[level]=search;
2672  }
2673  /*
2674  Generate a pseudo-random level for this node.
2675  */
2676  for (level=0; ; level++)
2677  {
2678  pixel_list->seed=(pixel_list->seed*42893621L)+1L;
2679  if ((pixel_list->seed & 0x300) != 0x300)
2680  break;
2681  }
2682  if (level > 8)
2683  level=8;
2684  if (level > (p->level+2))
2685  level=p->level+2;
2686  /*
2687  If we're raising the list's level, link back to the root node.
2688  */
2689  while (level > p->level)
2690  {
2691  p->level++;
2692  update[p->level]=65536UL;
2693  }
2694  /*
2695  Link the node into the skip-list.
2696  */
2697  do
2698  {
2699  p->nodes[color].next[level]=p->nodes[update[level]].next[level];
2700  p->nodes[update[level]].next[level]=color;
2701  } while (level-- > 0);
2702 }
2703 
2704 static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel)
2705 {
2706  SkipList
2707  *p;
2708 
2709  size_t
2710  color;
2711 
2712  ssize_t
2713  count;
2714 
2715  /*
2716  Find the median value for each of the color.
2717  */
2718  p=(&pixel_list->skip_list);
2719  color=65536L;
2720  count=0;
2721  do
2722  {
2723  color=p->nodes[color].next[0];
2724  count+=p->nodes[color].count;
2725  } while (count <= (ssize_t) (pixel_list->length >> 1));
2726  *pixel=ScaleShortToQuantum((unsigned short) color);
2727 }
2728 
2729 static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel)
2730 {
2731  SkipList
2732  *p;
2733 
2734  size_t
2735  color,
2736  max_count,
2737  mode;
2738 
2739  ssize_t
2740  count;
2741 
2742  /*
2743  Make each pixel the 'predominant color' of the specified neighborhood.
2744  */
2745  p=(&pixel_list->skip_list);
2746  color=65536L;
2747  mode=color;
2748  max_count=p->nodes[mode].count;
2749  count=0;
2750  do
2751  {
2752  color=p->nodes[color].next[0];
2753  if (p->nodes[color].count > max_count)
2754  {
2755  mode=color;
2756  max_count=p->nodes[mode].count;
2757  }
2758  count+=p->nodes[color].count;
2759  } while (count < (ssize_t) pixel_list->length);
2760  *pixel=ScaleShortToQuantum((unsigned short) mode);
2761 }
2762 
2763 static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel)
2764 {
2765  SkipList
2766  *p;
2767 
2768  size_t
2769  color,
2770  next,
2771  previous;
2772 
2773  ssize_t
2774  count;
2775 
2776  /*
2777  Finds the non peak value for each of the colors.
2778  */
2779  p=(&pixel_list->skip_list);
2780  color=65536L;
2781  next=p->nodes[color].next[0];
2782  count=0;
2783  do
2784  {
2785  previous=color;
2786  color=next;
2787  next=p->nodes[color].next[0];
2788  count+=p->nodes[color].count;
2789  } while (count <= (ssize_t) (pixel_list->length >> 1));
2790  if ((previous == 65536UL) && (next != 65536UL))
2791  color=next;
2792  else
2793  if ((previous != 65536UL) && (next == 65536UL))
2794  color=previous;
2795  *pixel=ScaleShortToQuantum((unsigned short) color);
2796 }
2797 
2798 static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list)
2799 {
2800  size_t
2801  signature;
2802 
2803  unsigned short
2804  index;
2805 
2806  index=ScaleQuantumToShort(pixel);
2807  signature=pixel_list->skip_list.nodes[index].signature;
2808  if (signature == pixel_list->signature)
2809  {
2810  pixel_list->skip_list.nodes[index].count++;
2811  return;
2812  }
2813  AddNodePixelList(pixel_list,index);
2814 }
2815 
2816 static void ResetPixelList(PixelList *pixel_list)
2817 {
2818  int
2819  level;
2820 
2821  SkipNode
2822  *root;
2823 
2824  SkipList
2825  *p;
2826 
2827  /*
2828  Reset the skip-list.
2829  */
2830  p=(&pixel_list->skip_list);
2831  root=p->nodes+65536UL;
2832  p->level=0;
2833  for (level=0; level < 9; level++)
2834  root->next[level]=65536UL;
2835  pixel_list->seed=pixel_list->signature++;
2836 }
2837 
2838 MagickExport Image *StatisticImage(const Image *image,const StatisticType type,
2839  const size_t width,const size_t height,ExceptionInfo *exception)
2840 {
2841 #define StatisticImageTag "Statistic/Image"
2842 
2843  CacheView
2844  *image_view,
2845  *statistic_view;
2846 
2847  Image
2848  *statistic_image;
2849 
2850  MagickBooleanType
2851  status;
2852 
2853  MagickOffsetType
2854  progress;
2855 
2856  PixelList
2857  **magick_restrict pixel_list;
2858 
2859  ssize_t
2860  center,
2861  y;
2862 
2863  /*
2864  Initialize statistics image attributes.
2865  */
2866  assert(image != (Image *) NULL);
2867  assert(image->signature == MagickCoreSignature);
2868  if (IsEventLogging() != MagickFalse)
2869  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2870  assert(exception != (ExceptionInfo *) NULL);
2871  assert(exception->signature == MagickCoreSignature);
2872  statistic_image=CloneImage(image,0,0,MagickTrue,
2873  exception);
2874  if (statistic_image == (Image *) NULL)
2875  return((Image *) NULL);
2876  status=SetImageStorageClass(statistic_image,DirectClass,exception);
2877  if (status == MagickFalse)
2878  {
2879  statistic_image=DestroyImage(statistic_image);
2880  return((Image *) NULL);
2881  }
2882  pixel_list=AcquirePixelListTLS(MagickMax(width,1),MagickMax(height,1));
2883  if (pixel_list == (PixelList **) NULL)
2884  {
2885  statistic_image=DestroyImage(statistic_image);
2886  ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
2887  }
2888  /*
2889  Make each pixel the min / max / median / mode / etc. of the neighborhood.
2890  */
2891  center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))*
2892  (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L);
2893  status=MagickTrue;
2894  progress=0;
2895  image_view=AcquireVirtualCacheView(image,exception);
2896  statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
2897 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2898  #pragma omp parallel for schedule(static) shared(progress,status) \
2899  magick_number_threads(image,statistic_image,statistic_image->rows,1)
2900 #endif
2901  for (y=0; y < (ssize_t) statistic_image->rows; y++)
2902  {
2903  const int
2904  id = GetOpenMPThreadId();
2905 
2906  const Quantum
2907  *magick_restrict p;
2908 
2909  Quantum
2910  *magick_restrict q;
2911 
2912  ssize_t
2913  x;
2914 
2915  if (status == MagickFalse)
2916  continue;
2917  p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y-
2918  (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1),
2919  MagickMax(height,1),exception);
2920  q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
2921  if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2922  {
2923  status=MagickFalse;
2924  continue;
2925  }
2926  for (x=0; x < (ssize_t) statistic_image->columns; x++)
2927  {
2928  ssize_t
2929  i;
2930 
2931  for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2932  {
2933  double
2934  area,
2935  maximum,
2936  minimum,
2937  sum,
2938  sum_squared;
2939 
2940  Quantum
2941  pixel;
2942 
2943  const Quantum
2944  *magick_restrict pixels;
2945 
2946  ssize_t
2947  u;
2948 
2949  ssize_t
2950  v;
2951 
2952  PixelChannel channel = GetPixelChannelChannel(image,i);
2953  PixelTrait traits = GetPixelChannelTraits(image,channel);
2954  PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image,
2955  channel);
2956  if ((traits == UndefinedPixelTrait) ||
2957  (statistic_traits == UndefinedPixelTrait))
2958  continue;
2959  if (((statistic_traits & CopyPixelTrait) != 0) ||
2960  (GetPixelWriteMask(image,p) <= (QuantumRange/2)))
2961  {
2962  SetPixelChannel(statistic_image,channel,p[center+i],q);
2963  continue;
2964  }
2965  if ((statistic_traits & UpdatePixelTrait) == 0)
2966  continue;
2967  pixels=p;
2968  area=0.0;
2969  minimum=pixels[i];
2970  maximum=pixels[i];
2971  sum=0.0;
2972  sum_squared=0.0;
2973  ResetPixelList(pixel_list[id]);
2974  for (v=0; v < (ssize_t) MagickMax(height,1); v++)
2975  {
2976  for (u=0; u < (ssize_t) MagickMax(width,1); u++)
2977  {
2978  if ((type == MedianStatistic) || (type == ModeStatistic) ||
2979  (type == NonpeakStatistic))
2980  {
2981  InsertPixelList(pixels[i],pixel_list[id]);
2982  pixels+=GetPixelChannels(image);
2983  continue;
2984  }
2985  area++;
2986  if (pixels[i] < minimum)
2987  minimum=(double) pixels[i];
2988  if (pixels[i] > maximum)
2989  maximum=(double) pixels[i];
2990  sum+=(double) pixels[i];
2991  sum_squared+=(double) pixels[i]*pixels[i];
2992  pixels+=GetPixelChannels(image);
2993  }
2994  pixels+=GetPixelChannels(image)*image->columns;
2995  }
2996  switch (type)
2997  {
2998  case ContrastStatistic:
2999  {
3000  pixel=ClampToQuantum(MagickAbsoluteValue((maximum-minimum)*
3001  PerceptibleReciprocal(maximum+minimum)));
3002  break;
3003  }
3004  case GradientStatistic:
3005  {
3006  pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum));
3007  break;
3008  }
3009  case MaximumStatistic:
3010  {
3011  pixel=ClampToQuantum(maximum);
3012  break;
3013  }
3014  case MeanStatistic:
3015  default:
3016  {
3017  pixel=ClampToQuantum(sum/area);
3018  break;
3019  }
3020  case MedianStatistic:
3021  {
3022  GetMedianPixelList(pixel_list[id],&pixel);
3023  break;
3024  }
3025  case MinimumStatistic:
3026  {
3027  pixel=ClampToQuantum(minimum);
3028  break;
3029  }
3030  case ModeStatistic:
3031  {
3032  GetModePixelList(pixel_list[id],&pixel);
3033  break;
3034  }
3035  case NonpeakStatistic:
3036  {
3037  GetNonpeakPixelList(pixel_list[id],&pixel);
3038  break;
3039  }
3040  case RootMeanSquareStatistic:
3041  {
3042  pixel=ClampToQuantum(sqrt(sum_squared/area));
3043  break;
3044  }
3045  case StandardDeviationStatistic:
3046  {
3047  pixel=ClampToQuantum(sqrt(sum_squared/area-(sum/area*sum/area)));
3048  break;
3049  }
3050  }
3051  SetPixelChannel(statistic_image,channel,pixel,q);
3052  }
3053  p+=GetPixelChannels(image);
3054  q+=GetPixelChannels(statistic_image);
3055  }
3056  if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
3057  status=MagickFalse;
3058  if (image->progress_monitor != (MagickProgressMonitor) NULL)
3059  {
3060  MagickBooleanType
3061  proceed;
3062 
3063 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3064  #pragma omp atomic
3065 #endif
3066  progress++;
3067  proceed=SetImageProgress(image,StatisticImageTag,progress,image->rows);
3068  if (proceed == MagickFalse)
3069  status=MagickFalse;
3070  }
3071  }
3072  statistic_view=DestroyCacheView(statistic_view);
3073  image_view=DestroyCacheView(image_view);
3074  pixel_list=DestroyPixelListTLS(pixel_list);
3075  if (status == MagickFalse)
3076  statistic_image=DestroyImage(statistic_image);
3077  return(statistic_image);
3078 }
Definition: image.h:152