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