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.0;
2095 cs->depth=1.0;
2096 cs->maxima=(-MagickMaximumValue);
2097 cs->minima=MagickMaximumValue;
2098 cs->sum=0.0;
2099 cs->sumLD=0.0;
2100 cs->mean=0.0;
2101 cs->standard_deviation=0.0;
2102 cs->variance=0.0;
2103 cs->skewness=0.0;
2104 cs->kurtosis=0.0;
2105 cs->entropy=0.0;
2106 }
2107 (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
2108 sizeof(*histogram));
2109 for (y=0; y < (ssize_t) image->rows; y++)
2110 {
2111 const Quantum
2112 *magick_restrict p;
2113
2114 ssize_t
2115 x;
2116
2117 /*
2118 Compute pixel statistics.
2119 */
2120 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
2121 if (p == (const Quantum *) NULL)
2122 break;
2123 for (x=0; x < (ssize_t) image->columns; x++)
2124 {
2125 if (GetPixelReadMask(image,p) <= (QuantumRange/2))
2126 {
2127 p+=GetPixelChannels(image);
2128 continue;
2129 }
2130 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2131 {
2133 *cs;
2134
2135 PixelChannel channel = GetPixelChannelChannel(image,i);
2136 PixelTrait traits = GetPixelChannelTraits(image,channel);
2137 if (traits == UndefinedPixelTrait)
2138 continue;
2139 cs=channel_statistics+channel;
2140 if (cs->depth != MAGICKCORE_QUANTUM_DEPTH)
2141 {
2142 depth=cs->depth;
2143 range=GetQuantumRange(depth);
2144 status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range),range) ?
2145 MagickTrue : MagickFalse;
2146 if (status != MagickFalse)
2147 {
2148 cs->depth++;
2149 if (cs->depth > channel_statistics[CompositePixelChannel].depth)
2150 channel_statistics[CompositePixelChannel].depth=cs->depth;
2151 i--;
2152 continue;
2153 }
2154 }
2155 cs->area++;
2156 if ((double) p[i] < cs->minima)
2157 cs->minima=(double) p[i];
2158 if ((double) p[i] > cs->maxima)
2159 cs->maxima=(double) p[i];
2160 histogram[(ssize_t) GetPixelChannels(image)*ScaleQuantumToMap(
2161 ClampToQuantum((double) p[i]))+i]++;
2162 cs->sumLD+=(long double) p[i];
2163 /*
2164 sum_squared, sum_cubed and sum_fourth_power are not used in
2165 MagickCore or MagickWand, but are made available in
2166 Magick++/lib/Statistic.cpp, so we need to calculate these.
2167 */
2168 cs->sum_squared+=(double) p[i]*(double) p[i];
2169 cs->sum_cubed+=(double) p[i]*(double) p[i]*(double) p[i];
2170 cs->sum_fourth_power+=(double) p[i]*(double) p[i]*(double) p[i]*
2171 (double) p[i];
2172 {
2173 /* Calculate running totals for Welford's method.
2174 */
2175 double
2176 n = cs->area,
2177 n1 = cs->area-1;
2178
2179 long double
2180 delta,
2181 delta_n,
2182 delta_n2,
2183 term1;
2184
2185 delta=(double) p[i]-cs->M1;
2186 delta_n=delta/n;
2187 delta_n2=delta_n*delta_n;
2188 term1=delta*delta_n*n1;
2189 cs->M4+=term1*delta_n2*(n*n-3.0*n+3.0)+6.0*delta_n2*cs->M2-4.0*
2190 delta_n*cs->M3;
2191 cs->M3+=term1*delta_n*(n-2.0)-3.0*delta_n*cs->M2;
2192 cs->M2+=term1;
2193 cs->M1+=delta_n;
2194 }
2195 }
2196 p+=GetPixelChannels(image);
2197 }
2198 }
2199 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2200 {
2202 *cs;
2203
2204 PixelChannel channel = GetPixelChannelChannel(image,i);
2205 PixelTrait traits = GetPixelChannelTraits(image,channel);
2206 double AdjArea = 1.0;
2207 if (traits == UndefinedPixelTrait)
2208 continue;
2209 cs=channel_statistics+channel;
2210 cs->mean=0.0;
2211 if (cs->area > 0)
2212 {
2213 cs->mean=cs->sumLD/(long double) cs->area;
2214 if (cs->area > 1.0)
2215 AdjArea=cs->area/(cs->area-1.0);
2216 }
2217 cs->sum=(double) cs->sum;
2218 if (cs->M2 == 0.0)
2219 {
2220 cs->standard_deviation=0.0;
2221 cs->variance=0.0;
2222 cs->skewness=0.0;
2223 cs->kurtosis=0.0;
2224 }
2225 else
2226 {
2227 if (cs->area > 1.0)
2228 cs->standard_deviation=sqrtl(cs->M2/((long double) cs->area-1.0));
2229 else
2230 cs->standard_deviation=sqrtl(cs->M2/((long double) cs->area));
2231 cs->variance=cs->standard_deviation*cs->standard_deviation;
2232 cs->skewness=sqrtl(cs->area)*cs->M3/powl(cs->M2*AdjArea,1.5);
2233 cs->kurtosis=cs->area*cs->M4/(cs->M2*cs->M2*AdjArea*AdjArea)-3.0;
2234 }
2235 }
2236
2237 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2238 {
2239 double
2240 number_bins;
2241
2242 ssize_t
2243 j;
2244
2245 PixelChannel channel = GetPixelChannelChannel(image,i);
2246 ChannelStatistics *cs = channel_statistics+channel;
2247 if (cs->area > 0.0)
2248 {
2249 cs->sum/=cs->area;
2250 cs->sum_squared/=cs->area;
2251 cs->sum_cubed/=cs->area;
2252 cs->sum_fourth_power/=cs->area;
2253 }
2254 /*
2255 Compute pixel entropy.
2256 */
2257 number_bins=0.0;
2258 for (j=0; j <= (ssize_t) MaxMap; j++)
2259 if (histogram[(ssize_t) GetPixelChannels(image)*j+i] > 0.0)
2260 number_bins++;
2261 area=PerceptibleReciprocalLD(channel_statistics[channel].area);
2262 for (j=0; j <= (ssize_t) MaxMap; j++)
2263 {
2264 double
2265 count;
2266
2267 count=area*histogram[(ssize_t) GetPixelChannels(image)*j+i];
2268 channel_statistics[channel].entropy+=((long double) -count*
2269 MagickLog10(count)*PerceptibleReciprocalLD((long double)
2270 MagickLog10(number_bins)));
2271 channel_statistics[CompositePixelChannel].entropy+=((long double) -count*
2272 MagickLog10(count)*PerceptibleReciprocalLD((long double)
2273 MagickLog10(number_bins))/GetPixelChannels(image));
2274 }
2275 }
2276 histogram=(double *) RelinquishMagickMemory(histogram);
2277 median_info=AcquireVirtualMemory(image->columns,image->rows*sizeof(*median));
2278 if (median_info == (MemoryInfo *) NULL)
2279 (void) ThrowMagickException(exception,GetMagickModule(),
2280 ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
2281 else
2282 {
2283 median=(Quantum *) GetVirtualMemoryBlob(median_info);
2284 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2285 {
2286 size_t
2287 n = 0;
2288
2289 /*
2290 Compute median statistics for each channel.
2291 */
2292 PixelChannel channel = GetPixelChannelChannel(image,i);
2293 PixelTrait traits = GetPixelChannelTraits(image,channel);
2294 if (traits == UndefinedPixelTrait)
2295 continue;
2296 if ((traits & UpdatePixelTrait) == 0)
2297 continue;
2298 for (y=0; y < (ssize_t) image->rows; y++)
2299 {
2300 const Quantum
2301 *magick_restrict p;
2302
2303 ssize_t
2304 x;
2305
2306 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
2307 if (p == (const Quantum *) NULL)
2308 break;
2309 for (x=0; x < (ssize_t) image->columns; x++)
2310 {
2311 if (GetPixelReadMask(image,p) <= (QuantumRange/2))
2312 {
2313 p+=GetPixelChannels(image);
2314 continue;
2315 }
2316 median[n++]=p[i];
2317 p+=GetPixelChannels(image);
2318 }
2319 }
2320 channel_statistics[channel].median=(double) median[
2321 GetMedianPixel(median,n)];
2322 }
2323 median_info=RelinquishVirtualMemory(median_info);
2324 }
2325 {
2326 ChannelStatistics *csComp = channel_statistics+CompositePixelChannel;
2327 csComp->sum=0.0;
2328 csComp->sum_squared=0.0;
2329 csComp->sum_cubed=0.0;
2330 csComp->sum_fourth_power=0.0;
2331 csComp->maxima=(-MagickMaximumValue);
2332 csComp->minima=MagickMaximumValue;
2333 csComp->area=0.0;
2334 csComp->mean=0.0;
2335 csComp->median=0.0;
2336 csComp->variance=0.0;
2337 csComp->standard_deviation=0.0;
2338 csComp->entropy=0.0;
2339 csComp->skewness=0.0;
2340 csComp->kurtosis=0.0;
2341 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2342 {
2344 *cs;
2345
2346 PixelChannel channel = GetPixelChannelChannel(image,i);
2347 PixelTrait traits = GetPixelChannelTraits(image,channel);
2348 if (traits == UndefinedPixelTrait)
2349 continue;
2350 if ((traits & UpdatePixelTrait) == 0)
2351 continue;
2352 cs=channel_statistics+channel;
2353 if (csComp->maxima < cs->maxima)
2354 csComp->maxima=cs->maxima;
2355 if (csComp->minima > cs->minima)
2356 csComp->minima=cs->minima;
2357 csComp->sum+=cs->sum;
2358 csComp->sum_squared+=cs->sum_squared;
2359 csComp->sum_cubed+=cs->sum_cubed;
2360 csComp->sum_fourth_power+=cs->sum_fourth_power;
2361 csComp->median+=cs->median;
2362 csComp->area+=cs->area;
2363 csComp->mean+=cs->mean;
2364 csComp->variance+=cs->variance;
2365 csComp->standard_deviation+=cs->standard_deviation;
2366 csComp->skewness+=cs->skewness;
2367 csComp->kurtosis+=cs->kurtosis;
2368 csComp->entropy+=cs->entropy;
2369 }
2370 channels=(double) GetImageChannels(image);
2371 csComp->sum/=channels;
2372 csComp->sum_squared/=channels;
2373 csComp->sum_cubed/=channels;
2374 csComp->sum_fourth_power/=channels;
2375 csComp->median/=channels;
2376 csComp->area/=channels;
2377 csComp->mean/=channels;
2378 csComp->variance/=channels;
2379 csComp->standard_deviation/=channels;
2380 csComp->skewness/=channels;
2381 csComp->kurtosis/=channels;
2382 csComp->entropy/=channels;
2383 }
2384 if (y < (ssize_t) image->rows)
2385 channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
2386 channel_statistics);
2387 return(channel_statistics);
2388}
2389
2390/*
2391%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2392% %
2393% %
2394% %
2395% P o l y n o m i a l I m a g e %
2396% %
2397% %
2398% %
2399%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2400%
2401% PolynomialImage() returns a new image where each pixel is the sum of the
2402% pixels in the image sequence after applying its corresponding terms
2403% (coefficient and degree pairs).
2404%
2405% The format of the PolynomialImage method is:
2406%
2407% Image *PolynomialImage(const Image *images,const size_t number_terms,
2408% const double *terms,ExceptionInfo *exception)
2409%
2410% A description of each parameter follows:
2411%
2412% o images: the image sequence.
2413%
2414% o number_terms: the number of terms in the list. The actual list length
2415% is 2 x number_terms + 1 (the constant).
2416%
2417% o terms: the list of polynomial coefficients and degree pairs and a
2418% constant.
2419%
2420% o exception: return any errors or warnings in this structure.
2421%
2422*/
2423MagickExport Image *PolynomialImage(const Image *images,
2424 const size_t number_terms,const double *terms,ExceptionInfo *exception)
2425{
2426#define PolynomialImageTag "Polynomial/Image"
2427
2428 CacheView
2429 *polynomial_view;
2430
2431 Image
2432 *image;
2433
2434 MagickBooleanType
2435 status;
2436
2437 MagickOffsetType
2438 progress;
2439
2441 **magick_restrict polynomial_pixels;
2442
2443 size_t
2444 number_images;
2445
2446 ssize_t
2447 y;
2448
2449 assert(images != (Image *) NULL);
2450 assert(images->signature == MagickCoreSignature);
2451 if (IsEventLogging() != MagickFalse)
2452 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
2453 assert(exception != (ExceptionInfo *) NULL);
2454 assert(exception->signature == MagickCoreSignature);
2455 image=AcquireImageCanvas(images,exception);
2456 if (image == (Image *) NULL)
2457 return((Image *) NULL);
2458 if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2459 {
2460 image=DestroyImage(image);
2461 return((Image *) NULL);
2462 }
2463 number_images=GetImageListLength(images);
2464 polynomial_pixels=AcquirePixelTLS(images);
2465 if (polynomial_pixels == (PixelChannels **) NULL)
2466 {
2467 image=DestroyImage(image);
2468 (void) ThrowMagickException(exception,GetMagickModule(),
2469 ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
2470 return((Image *) NULL);
2471 }
2472 /*
2473 Polynomial image pixels.
2474 */
2475 status=MagickTrue;
2476 progress=0;
2477 polynomial_view=AcquireAuthenticCacheView(image,exception);
2478#if defined(MAGICKCORE_OPENMP_SUPPORT)
2479 #pragma omp parallel for schedule(static) shared(progress,status) \
2480 magick_number_threads(image,image,image->rows,1)
2481#endif
2482 for (y=0; y < (ssize_t) image->rows; y++)
2483 {
2484 CacheView
2485 *image_view;
2486
2487 const Image
2488 *next;
2489
2490 const int
2491 id = GetOpenMPThreadId();
2492
2494 *polynomial_pixel;
2495
2496 Quantum
2497 *magick_restrict q;
2498
2499 ssize_t
2500 i,
2501 j,
2502 x;
2503
2504 if (status == MagickFalse)
2505 continue;
2506 q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1,
2507 exception);
2508 if (q == (Quantum *) NULL)
2509 {
2510 status=MagickFalse;
2511 continue;
2512 }
2513 polynomial_pixel=polynomial_pixels[id];
2514 for (j=0; j < (ssize_t) image->columns; j++)
2515 for (i=0; i < MaxPixelChannels; i++)
2516 polynomial_pixel[j].channel[i]=0.0;
2517 next=images;
2518 for (j=0; j < (ssize_t) number_images; j++)
2519 {
2520 const Quantum
2521 *p;
2522
2523 if (j >= (ssize_t) number_terms)
2524 continue;
2525 image_view=AcquireVirtualCacheView(next,exception);
2526 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2527 if (p == (const Quantum *) NULL)
2528 {
2529 image_view=DestroyCacheView(image_view);
2530 break;
2531 }
2532 for (x=0; x < (ssize_t) image->columns; x++)
2533 {
2534 for (i=0; i < (ssize_t) GetPixelChannels(next); i++)
2535 {
2536 MagickRealType
2537 coefficient,
2538 degree;
2539
2540 PixelChannel channel = GetPixelChannelChannel(image,i);
2541 PixelTrait traits = GetPixelChannelTraits(next,channel);
2542 PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel);
2543 if ((traits == UndefinedPixelTrait) ||
2544 (polynomial_traits == UndefinedPixelTrait))
2545 continue;
2546 if ((traits & UpdatePixelTrait) == 0)
2547 continue;
2548 coefficient=(MagickRealType) terms[2*j];
2549 degree=(MagickRealType) terms[(j << 1)+1];
2550 polynomial_pixel[x].channel[i]+=coefficient*
2551 pow(QuantumScale*(double) GetPixelChannel(image,channel,p),degree);
2552 }
2553 p+=GetPixelChannels(next);
2554 }
2555 image_view=DestroyCacheView(image_view);
2556 next=GetNextImageInList(next);
2557 }
2558 for (x=0; x < (ssize_t) image->columns; x++)
2559 {
2560 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2561 {
2562 PixelChannel channel = GetPixelChannelChannel(image,i);
2563 PixelTrait traits = GetPixelChannelTraits(image,channel);
2564 if (traits == UndefinedPixelTrait)
2565 continue;
2566 if ((traits & UpdatePixelTrait) == 0)
2567 continue;
2568 q[i]=ClampToQuantum((double) QuantumRange*
2569 polynomial_pixel[x].channel[i]);
2570 }
2571 q+=GetPixelChannels(image);
2572 }
2573 if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse)
2574 status=MagickFalse;
2575 if (images->progress_monitor != (MagickProgressMonitor) NULL)
2576 {
2577 MagickBooleanType
2578 proceed;
2579
2580#if defined(MAGICKCORE_OPENMP_SUPPORT)
2581 #pragma omp atomic
2582#endif
2583 progress++;
2584 proceed=SetImageProgress(images,PolynomialImageTag,progress,
2585 image->rows);
2586 if (proceed == MagickFalse)
2587 status=MagickFalse;
2588 }
2589 }
2590 polynomial_view=DestroyCacheView(polynomial_view);
2591 polynomial_pixels=DestroyPixelTLS(images,polynomial_pixels);
2592 if (status == MagickFalse)
2593 image=DestroyImage(image);
2594 return(image);
2595}
2596
2597/*
2598%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2599% %
2600% %
2601% %
2602% S t a t i s t i c I m a g e %
2603% %
2604% %
2605% %
2606%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2607%
2608% StatisticImage() makes each pixel the min / max / median / mode / etc. of
2609% the neighborhood of the specified width and height.
2610%
2611% The format of the StatisticImage method is:
2612%
2613% Image *StatisticImage(const Image *image,const StatisticType type,
2614% const size_t width,const size_t height,ExceptionInfo *exception)
2615%
2616% A description of each parameter follows:
2617%
2618% o image: the image.
2619%
2620% o type: the statistic type (median, mode, etc.).
2621%
2622% o width: the width of the pixel neighborhood.
2623%
2624% o height: the height of the pixel neighborhood.
2625%
2626% o exception: return any errors or warnings in this structure.
2627%
2628*/
2629
2630typedef struct _SkipNode
2631{
2632 size_t
2633 next[9],
2634 count,
2635 signature;
2636} SkipNode;
2637
2638typedef struct _SkipList
2639{
2640 ssize_t
2641 level;
2642
2643 SkipNode
2644 *nodes;
2645} SkipList;
2646
2647typedef struct _PixelList
2648{
2649 size_t
2650 length,
2651 seed;
2652
2653 SkipList
2654 skip_list;
2655
2656 size_t
2657 signature;
2658} PixelList;
2659
2660static PixelList *DestroyPixelList(PixelList *pixel_list)
2661{
2662 if (pixel_list == (PixelList *) NULL)
2663 return((PixelList *) NULL);
2664 if (pixel_list->skip_list.nodes != (SkipNode *) NULL)
2665 pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory(
2666 pixel_list->skip_list.nodes);
2667 pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
2668 return(pixel_list);
2669}
2670
2671static PixelList **DestroyPixelListTLS(PixelList **pixel_list)
2672{
2673 ssize_t
2674 i;
2675
2676 assert(pixel_list != (PixelList **) NULL);
2677 for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
2678 if (pixel_list[i] != (PixelList *) NULL)
2679 pixel_list[i]=DestroyPixelList(pixel_list[i]);
2680 pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list);
2681 return(pixel_list);
2682}
2683
2684static PixelList *AcquirePixelList(const size_t width,const size_t height)
2685{
2686 PixelList
2687 *pixel_list;
2688
2689 pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list));
2690 if (pixel_list == (PixelList *) NULL)
2691 return(pixel_list);
2692 (void) memset((void *) pixel_list,0,sizeof(*pixel_list));
2693 pixel_list->length=width*height;
2694 pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL,
2695 sizeof(*pixel_list->skip_list.nodes));
2696 if (pixel_list->skip_list.nodes == (SkipNode *) NULL)
2697 return(DestroyPixelList(pixel_list));
2698 (void) memset(pixel_list->skip_list.nodes,0,65537UL*
2699 sizeof(*pixel_list->skip_list.nodes));
2700 pixel_list->signature=MagickCoreSignature;
2701 return(pixel_list);
2702}
2703
2704static PixelList **AcquirePixelListTLS(const size_t width,
2705 const size_t height)
2706{
2707 PixelList
2708 **pixel_list;
2709
2710 ssize_t
2711 i;
2712
2713 size_t
2714 number_threads;
2715
2716 number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
2717 pixel_list=(PixelList **) AcquireQuantumMemory(number_threads,
2718 sizeof(*pixel_list));
2719 if (pixel_list == (PixelList **) NULL)
2720 return((PixelList **) NULL);
2721 (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list));
2722 for (i=0; i < (ssize_t) number_threads; i++)
2723 {
2724 pixel_list[i]=AcquirePixelList(width,height);
2725 if (pixel_list[i] == (PixelList *) NULL)
2726 return(DestroyPixelListTLS(pixel_list));
2727 }
2728 return(pixel_list);
2729}
2730
2731static void AddNodePixelList(PixelList *pixel_list,const size_t color)
2732{
2733 SkipList
2734 *p;
2735
2736 ssize_t
2737 level;
2738
2739 size_t
2740 search,
2741 update[9];
2742
2743 /*
2744 Initialize the node.
2745 */
2746 p=(&pixel_list->skip_list);
2747 p->nodes[color].signature=pixel_list->signature;
2748 p->nodes[color].count=1;
2749 /*
2750 Determine where it belongs in the list.
2751 */
2752 search=65536UL;
2753 (void) memset(update,0,sizeof(update));
2754 for (level=p->level; level >= 0; level--)
2755 {
2756 while (p->nodes[search].next[level] < color)
2757 search=p->nodes[search].next[level];
2758 update[level]=search;
2759 }
2760 /*
2761 Generate a pseudo-random level for this node.
2762 */
2763 for (level=0; ; level++)
2764 {
2765 pixel_list->seed=(pixel_list->seed*42893621L)+1L;
2766 if ((pixel_list->seed & 0x300) != 0x300)
2767 break;
2768 }
2769 if (level > 8)
2770 level=8;
2771 if (level > (p->level+2))
2772 level=p->level+2;
2773 /*
2774 If we're raising the list's level, link back to the root node.
2775 */
2776 while (level > p->level)
2777 {
2778 p->level++;
2779 update[p->level]=65536UL;
2780 }
2781 /*
2782 Link the node into the skip-list.
2783 */
2784 do
2785 {
2786 p->nodes[color].next[level]=p->nodes[update[level]].next[level];
2787 p->nodes[update[level]].next[level]=color;
2788 } while (level-- > 0);
2789}
2790
2791static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel)
2792{
2793 SkipList
2794 *p;
2795
2796 size_t
2797 color;
2798
2799 ssize_t
2800 count;
2801
2802 /*
2803 Find the median value for each of the color.
2804 */
2805 p=(&pixel_list->skip_list);
2806 color=65536L;
2807 count=0;
2808 do
2809 {
2810 color=p->nodes[color].next[0];
2811 count+=(ssize_t) p->nodes[color].count;
2812 } while (count <= (ssize_t) (pixel_list->length >> 1));
2813 *pixel=ScaleShortToQuantum((unsigned short) color);
2814}
2815
2816static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel)
2817{
2818 SkipList
2819 *p;
2820
2821 size_t
2822 color,
2823 max_count,
2824 mode;
2825
2826 ssize_t
2827 count;
2828
2829 /*
2830 Make each pixel the 'predominant color' of the specified neighborhood.
2831 */
2832 p=(&pixel_list->skip_list);
2833 color=65536L;
2834 mode=color;
2835 max_count=p->nodes[mode].count;
2836 count=0;
2837 do
2838 {
2839 color=p->nodes[color].next[0];
2840 if (p->nodes[color].count > max_count)
2841 {
2842 mode=color;
2843 max_count=p->nodes[mode].count;
2844 }
2845 count+=(ssize_t) p->nodes[color].count;
2846 } while (count < (ssize_t) pixel_list->length);
2847 *pixel=ScaleShortToQuantum((unsigned short) mode);
2848}
2849
2850static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel)
2851{
2852 SkipList
2853 *p;
2854
2855 size_t
2856 color,
2857 next,
2858 previous;
2859
2860 ssize_t
2861 count;
2862
2863 /*
2864 Finds the non peak value for each of the colors.
2865 */
2866 p=(&pixel_list->skip_list);
2867 color=65536L;
2868 next=p->nodes[color].next[0];
2869 count=0;
2870 do
2871 {
2872 previous=color;
2873 color=next;
2874 next=p->nodes[color].next[0];
2875 count+=(ssize_t) p->nodes[color].count;
2876 } while (count <= (ssize_t) (pixel_list->length >> 1));
2877 if ((previous == 65536UL) && (next != 65536UL))
2878 color=next;
2879 else
2880 if ((previous != 65536UL) && (next == 65536UL))
2881 color=previous;
2882 *pixel=ScaleShortToQuantum((unsigned short) color);
2883}
2884
2885static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list)
2886{
2887 size_t
2888 signature;
2889
2890 unsigned short
2891 index;
2892
2893 index=ScaleQuantumToShort(pixel);
2894 signature=pixel_list->skip_list.nodes[index].signature;
2895 if (signature == pixel_list->signature)
2896 {
2897 pixel_list->skip_list.nodes[index].count++;
2898 return;
2899 }
2900 AddNodePixelList(pixel_list,index);
2901}
2902
2903static void ResetPixelList(PixelList *pixel_list)
2904{
2905 int
2906 level;
2907
2908 SkipNode
2909 *root;
2910
2911 SkipList
2912 *p;
2913
2914 /*
2915 Reset the skip-list.
2916 */
2917 p=(&pixel_list->skip_list);
2918 root=p->nodes+65536UL;
2919 p->level=0;
2920 for (level=0; level < 9; level++)
2921 root->next[level]=65536UL;
2922 pixel_list->seed=pixel_list->signature++;
2923}
2924
2925MagickExport Image *StatisticImage(const Image *image,const StatisticType type,
2926 const size_t width,const size_t height,ExceptionInfo *exception)
2927{
2928#define StatisticImageTag "Statistic/Image"
2929
2930 CacheView
2931 *image_view,
2932 *statistic_view;
2933
2934 Image
2935 *statistic_image;
2936
2937 MagickBooleanType
2938 status;
2939
2940 MagickOffsetType
2941 progress;
2942
2943 PixelList
2944 **magick_restrict pixel_list;
2945
2946 ssize_t
2947 center,
2948 y;
2949
2950 /*
2951 Initialize statistics image attributes.
2952 */
2953 assert(image != (Image *) NULL);
2954 assert(image->signature == MagickCoreSignature);
2955 if (IsEventLogging() != MagickFalse)
2956 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2957 assert(exception != (ExceptionInfo *) NULL);
2958 assert(exception->signature == MagickCoreSignature);
2959 statistic_image=CloneImage(image,0,0,MagickTrue,
2960 exception);
2961 if (statistic_image == (Image *) NULL)
2962 return((Image *) NULL);
2963 status=SetImageStorageClass(statistic_image,DirectClass,exception);
2964 if (status == MagickFalse)
2965 {
2966 statistic_image=DestroyImage(statistic_image);
2967 return((Image *) NULL);
2968 }
2969 pixel_list=AcquirePixelListTLS(MagickMax(width,1),MagickMax(height,1));
2970 if (pixel_list == (PixelList **) NULL)
2971 {
2972 statistic_image=DestroyImage(statistic_image);
2973 ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
2974 }
2975 /*
2976 Make each pixel the min / max / median / mode / etc. of the neighborhood.
2977 */
2978 center=(ssize_t) GetPixelChannels(image)*((ssize_t) image->columns+
2979 MagickMax((ssize_t) width,1L))*(MagickMax((ssize_t) height,1)/2L)+(ssize_t)
2980 GetPixelChannels(image)*(MagickMax((ssize_t) width,1L)/2L);
2981 status=MagickTrue;
2982 progress=0;
2983 image_view=AcquireVirtualCacheView(image,exception);
2984 statistic_view=AcquireAuthenticCacheView(statistic_image,exception);
2985#if defined(MAGICKCORE_OPENMP_SUPPORT)
2986 #pragma omp parallel for schedule(static) shared(progress,status) \
2987 magick_number_threads(image,statistic_image,statistic_image->rows,1)
2988#endif
2989 for (y=0; y < (ssize_t) statistic_image->rows; y++)
2990 {
2991 const int
2992 id = GetOpenMPThreadId();
2993
2994 const Quantum
2995 *magick_restrict p;
2996
2997 Quantum
2998 *magick_restrict q;
2999
3000 ssize_t
3001 x;
3002
3003 if (status == MagickFalse)
3004 continue;
3005 p=GetCacheViewVirtualPixels(image_view,-((ssize_t) MagickMax(width,1)/2L),y-
3006 (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1),
3007 MagickMax(height,1),exception);
3008 q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
3009 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3010 {
3011 status=MagickFalse;
3012 continue;
3013 }
3014 for (x=0; x < (ssize_t) statistic_image->columns; x++)
3015 {
3016 ssize_t
3017 i;
3018
3019 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
3020 {
3021 double
3022 area,
3023 maximum,
3024 minimum,
3025 sum,
3026 sum_squared;
3027
3028 Quantum
3029 pixel;
3030
3031 const Quantum
3032 *magick_restrict pixels;
3033
3034 ssize_t
3035 u;
3036
3037 ssize_t
3038 v;
3039
3040 PixelChannel channel = GetPixelChannelChannel(image,i);
3041 PixelTrait traits = GetPixelChannelTraits(image,channel);
3042 PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image,
3043 channel);
3044 if ((traits == UndefinedPixelTrait) ||
3045 (statistic_traits == UndefinedPixelTrait))
3046 continue;
3047 if (((statistic_traits & CopyPixelTrait) != 0) ||
3048 (GetPixelWriteMask(image,p) <= (QuantumRange/2)))
3049 {
3050 SetPixelChannel(statistic_image,channel,p[center+i],q);
3051 continue;
3052 }
3053 if ((statistic_traits & UpdatePixelTrait) == 0)
3054 continue;
3055 pixels=p;
3056 area=0.0;
3057 minimum=pixels[i];
3058 maximum=pixels[i];
3059 sum=0.0;
3060 sum_squared=0.0;
3061 ResetPixelList(pixel_list[id]);
3062 for (v=0; v < (ssize_t) MagickMax(height,1); v++)
3063 {
3064 for (u=0; u < (ssize_t) MagickMax(width,1); u++)
3065 {
3066 if ((type == MedianStatistic) || (type == ModeStatistic) ||
3067 (type == NonpeakStatistic))
3068 {
3069 InsertPixelList(pixels[i],pixel_list[id]);
3070 pixels+=GetPixelChannels(image);
3071 continue;
3072 }
3073 area++;
3074 if ((double) pixels[i] < minimum)
3075 minimum=(double) pixels[i];
3076 if ((double) pixels[i] > maximum)
3077 maximum=(double) pixels[i];
3078 sum+=(double) pixels[i];
3079 sum_squared+=(double) pixels[i]*(double) pixels[i];
3080 pixels+=GetPixelChannels(image);
3081 }
3082 pixels+=GetPixelChannels(image)*image->columns;
3083 }
3084 switch (type)
3085 {
3086 case ContrastStatistic:
3087 {
3088 pixel=ClampToQuantum(MagickAbsoluteValue((maximum-minimum)*
3089 PerceptibleReciprocal(maximum+minimum)));
3090 break;
3091 }
3092 case GradientStatistic:
3093 {
3094 pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum));
3095 break;
3096 }
3097 case MaximumStatistic:
3098 {
3099 pixel=ClampToQuantum(maximum);
3100 break;
3101 }
3102 case MeanStatistic:
3103 default:
3104 {
3105 pixel=ClampToQuantum(sum/area);
3106 break;
3107 }
3108 case MedianStatistic:
3109 {
3110 GetMedianPixelList(pixel_list[id],&pixel);
3111 break;
3112 }
3113 case MinimumStatistic:
3114 {
3115 pixel=ClampToQuantum(minimum);
3116 break;
3117 }
3118 case ModeStatistic:
3119 {
3120 GetModePixelList(pixel_list[id],&pixel);
3121 break;
3122 }
3123 case NonpeakStatistic:
3124 {
3125 GetNonpeakPixelList(pixel_list[id],&pixel);
3126 break;
3127 }
3128 case RootMeanSquareStatistic:
3129 {
3130 pixel=ClampToQuantum(sqrt(sum_squared/area));
3131 break;
3132 }
3133 case StandardDeviationStatistic:
3134 {
3135 pixel=ClampToQuantum(sqrt(sum_squared/area-(sum/area*sum/area)));
3136 break;
3137 }
3138 }
3139 SetPixelChannel(statistic_image,channel,pixel,q);
3140 }
3141 p+=GetPixelChannels(image);
3142 q+=GetPixelChannels(statistic_image);
3143 }
3144 if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
3145 status=MagickFalse;
3146 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3147 {
3148 MagickBooleanType
3149 proceed;
3150
3151#if defined(MAGICKCORE_OPENMP_SUPPORT)
3152 #pragma omp atomic
3153#endif
3154 progress++;
3155 proceed=SetImageProgress(image,StatisticImageTag,progress,image->rows);
3156 if (proceed == MagickFalse)
3157 status=MagickFalse;
3158 }
3159 }
3160 statistic_view=DestroyCacheView(statistic_view);
3161 image_view=DestroyCacheView(image_view);
3162 pixel_list=DestroyPixelListTLS(pixel_list);
3163 if (status == MagickFalse)
3164 statistic_image=DestroyImage(statistic_image);
3165 return(statistic_image);
3166}