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