MagickCore 7.1.2-37
Convert, Edit, Or Compose Bitmap Images
Loading...
Searching...
No Matches
enhance.c
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% %
6% EEEEE N N H H AAA N N CCCC EEEEE %
7% E NN N H H A A NN N C E %
8% EEE N N N HHHHH AAAAA N N N C EEE %
9% E N NN H H A A N NN C E %
10% EEEEE N N H H A A N N CCCC EEEEE %
11% %
12% %
13% MagickCore Image Enhancement 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/license/ %
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/artifact.h"
46#include "MagickCore/attribute.h"
47#include "MagickCore/cache.h"
48#include "MagickCore/cache-private.h"
49#include "MagickCore/cache-view.h"
50#include "MagickCore/channel.h"
51#include "MagickCore/color.h"
52#include "MagickCore/color-private.h"
53#include "MagickCore/colorspace.h"
54#include "MagickCore/colorspace-private.h"
55#include "MagickCore/composite-private.h"
56#include "MagickCore/enhance.h"
57#include "MagickCore/exception.h"
58#include "MagickCore/exception-private.h"
59#include "MagickCore/fx.h"
60#include "MagickCore/gem.h"
61#include "MagickCore/gem-private.h"
62#include "MagickCore/geometry.h"
63#include "MagickCore/histogram.h"
64#include "MagickCore/image.h"
65#include "MagickCore/image-private.h"
66#include "MagickCore/memory_.h"
67#include "MagickCore/monitor.h"
68#include "MagickCore/monitor-private.h"
69#include "MagickCore/option.h"
70#include "MagickCore/pixel.h"
71#include "MagickCore/pixel-accessor.h"
72#include "MagickCore/pixel-private.h"
73#include "MagickCore/property.h"
74#include "MagickCore/quantum.h"
75#include "MagickCore/quantum-private.h"
76#include "MagickCore/resample.h"
77#include "MagickCore/resample-private.h"
78#include "MagickCore/resource_.h"
79#include "MagickCore/statistic.h"
80#include "MagickCore/string_.h"
81#include "MagickCore/string-private.h"
82#include "MagickCore/thread-private.h"
83#include "MagickCore/threshold.h"
84#include "MagickCore/token.h"
85#include "MagickCore/xml-tree.h"
86#include "MagickCore/xml-tree-private.h"
87␌
88/*
89%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
90% %
91% %
92% %
93% A u t o G a m m a I m a g e %
94% %
95% %
96% %
97%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
98%
99% AutoGammaImage() extract the 'mean' from the image and adjust the image
100% to try make set its gamma appropriately.
101%
102% The format of the AutoGammaImage method is:
103%
104% MagickBooleanType AutoGammaImage(Image *image,ExceptionInfo *exception)
105%
106% A description of each parameter follows:
107%
108% o image: The image to auto-level
109%
110% o exception: return any errors or warnings in this structure.
111%
112*/
113MagickExport MagickBooleanType AutoGammaImage(Image *image,
114 ExceptionInfo *exception)
115{
116 double
117 gamma,
118 log_mean,
119 mean,
120 sans;
121
122 MagickStatusType
123 status;
124
125 ssize_t
126 i;
127
128 log_mean=log(0.5);
129 if (image->channel_mask == AllChannels)
130 {
131 /*
132 Apply gamma correction equally across all given channels.
133 */
134 (void) GetImageMean(image,&mean,&sans,exception);
135 gamma=log(mean*QuantumScale)/log_mean;
136 return(LevelImage(image,0.0,(double) QuantumRange,gamma,exception));
137 }
138 /*
139 Auto-gamma each channel separately.
140 */
141 status=MagickTrue;
142 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
143 {
144 ChannelType
145 channel_mask;
146
147 PixelChannel channel = GetPixelChannelChannel(image,i);
148 PixelTrait traits = GetPixelChannelTraits(image,channel);
149 if ((traits & UpdatePixelTrait) == 0)
150 continue;
151 channel_mask=SetImageChannelMask(image,(ChannelType) (1UL << i));
152 status=GetImageMean(image,&mean,&sans,exception);
153 gamma=log(mean*QuantumScale)/log_mean;
154 status&=(MagickStatusType) LevelImage(image,0.0,(double) QuantumRange,gamma,
155 exception);
156 (void) SetImageChannelMask(image,channel_mask);
157 if (status == MagickFalse)
158 break;
159 }
160 return(status != 0 ? MagickTrue : MagickFalse);
161}
162␌
163/*
164%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
165% %
166% %
167% %
168% A u t o L e v e l I m a g e %
169% %
170% %
171% %
172%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
173%
174% AutoLevelImage() adjusts the levels of a particular image channel by
175% scaling the minimum and maximum values to the full quantum range.
176%
177% The format of the LevelImage method is:
178%
179% MagickBooleanType AutoLevelImage(Image *image,ExceptionInfo *exception)
180%
181% A description of each parameter follows:
182%
183% o image: The image to auto-level
184%
185% o exception: return any errors or warnings in this structure.
186%
187*/
188MagickExport MagickBooleanType AutoLevelImage(Image *image,
189 ExceptionInfo *exception)
190{
191 return(MinMaxStretchImage(image,0.0,0.0,1.0,exception));
192}
193␌
194/*
195%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
196% %
197% %
198% %
199% B r i g h t n e s s C o n t r a s t I m a g e %
200% %
201% %
202% %
203%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
204%
205% BrightnessContrastImage() changes the brightness and/or contrast of an
206% image. It converts the brightness and contrast parameters into slope and
207% intercept and calls a polynomial function to apply to the image.
208%
209% The format of the BrightnessContrastImage method is:
210%
211% MagickBooleanType BrightnessContrastImage(Image *image,
212% const double brightness,const double contrast,ExceptionInfo *exception)
213%
214% A description of each parameter follows:
215%
216% o image: the image.
217%
218% o brightness: the brightness percent (-100 .. 100).
219%
220% o contrast: the contrast percent (-100 .. 100).
221%
222% o exception: return any errors or warnings in this structure.
223%
224*/
225MagickExport MagickBooleanType BrightnessContrastImage(Image *image,
226 const double brightness,const double contrast,ExceptionInfo *exception)
227{
228#define BrightnessContrastImageTag "BrightnessContrast/Image"
229
230 double
231 coefficients[2],
232 intercept,
233 slope;
234
235 MagickBooleanType
236 status;
237
238 /*
239 Compute slope and intercept.
240 */
241 assert(image != (Image *) NULL);
242 assert(image->signature == MagickCoreSignature);
243 if (IsEventLogging() != MagickFalse)
244 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
245 slope=100.0*MagickSafeReciprocal(100.0-contrast);
246 if (contrast < 0.0)
247 slope=0.01*contrast+1.0;
248 intercept=(0.01*brightness-0.5)*slope+0.5;
249 coefficients[0]=slope;
250 coefficients[1]=intercept;
251 status=FunctionImage(image,PolynomialFunction,2,coefficients,exception);
252 return(status);
253}
254␌
255/*
256%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
257% %
258% %
259% %
260% C L A H E I m a g e %
261% %
262% %
263% %
264%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
265%
266% CLAHEImage() is a variant of adaptive histogram equalization in which the
267% contrast amplification is limited, so as to reduce this problem of noise
268% amplification.
269%
270% Adapted from implementation by Karel Zuiderveld, karel@cv.ruu.nl in
271% "Graphics Gems IV", Academic Press, 1994.
272%
273% The format of the CLAHEImage method is:
274%
275% MagickBooleanType CLAHEImage(Image *image,const size_t width,
276% const size_t height,const size_t number_bins,const double clip_limit,
277% ExceptionInfo *exception)
278%
279% A description of each parameter follows:
280%
281% o image: the image.
282%
283% o width: the width of the tile divisions to use in horizontal direction.
284%
285% o height: the height of the tile divisions to use in vertical direction.
286%
287% o number_bins: number of bins for histogram ("dynamic range").
288%
289% o clip_limit: contrast limit for localised changes in contrast. A limit
290% less than 1 results in standard non-contrast limited AHE.
291%
292% o exception: return any errors or warnings in this structure.
293%
294*/
295
296typedef struct _RangeInfo
297{
298 unsigned short
299 min,
300 max;
301} RangeInfo;
302
303static void ClipCLAHEHistogram(const double clip_limit,const size_t number_bins,
304 size_t *histogram)
305{
306#define NumberCLAHEGrays (65536)
307
308 ssize_t
309 cumulative_excess,
310 excess,
311 i,
312 previous_excess,
313 step;
314
315 /*
316 Compute total number of excess pixels.
317 */
318 if (number_bins == 0)
319 return;
320 cumulative_excess=0;
321 for (i=0; i < (ssize_t) number_bins; i++)
322 if (histogram[i] > clip_limit)
323 cumulative_excess+=(ssize_t) (histogram[i]-clip_limit);
324 /*
325 Clip histogram and redistribute excess pixels across all bins.
326 */
327 step=cumulative_excess/(ssize_t) number_bins;
328 excess=(ssize_t) (clip_limit-step);
329 for (i=0; i < (ssize_t) number_bins; i++)
330 {
331 if ((double) histogram[i] > clip_limit)
332 histogram[i]=(size_t) clip_limit;
333 else
334 if ((ssize_t) histogram[i] > excess)
335 {
336 cumulative_excess-=(ssize_t) histogram[i]-excess;
337 histogram[i]=(size_t) clip_limit;
338 }
339 else
340 {
341 cumulative_excess-=step;
342 histogram[i]+=(size_t) step;
343 }
344 }
345 /*
346 Redistribute remaining excess.
347 */
348 do
349 {
350 size_t
351 *p;
352
353 size_t
354 *q;
355
356 previous_excess=cumulative_excess;
357 p=histogram;
358 q=histogram+number_bins;
359 while ((cumulative_excess != 0) && (p < q))
360 {
361 step=(ssize_t) number_bins/cumulative_excess;
362 if (step < 1)
363 step=1;
364 for (p=histogram; (p < q) && (cumulative_excess != 0); p+=(ptrdiff_t) step)
365 if ((double) *p < clip_limit)
366 {
367 (*p)++;
368 cumulative_excess--;
369 }
370 p++;
371 }
372 } while ((cumulative_excess != 0) && (cumulative_excess < previous_excess));
373}
374
375static void GenerateCLAHEHistogram(const RectangleInfo *clahe_info,
376 const RectangleInfo *tile_info,const size_t number_bins,
377 const unsigned short *lut,const unsigned short *pixels,size_t *histogram)
378{
379 const unsigned short
380 *p;
381
382 ssize_t
383 i;
384
385 /*
386 Classify the pixels into a gray histogram.
387 */
388 for (i=0; i < (ssize_t) number_bins; i++)
389 histogram[i]=0L;
390 p=pixels;
391 for (i=0; i < (ssize_t) tile_info->height; i++)
392 {
393 const unsigned short
394 *q;
395
396 q=p+tile_info->width;
397 while (p < q)
398 histogram[lut[*p++]]++;
399 q+=(ptrdiff_t) clahe_info->width;
400 p=q-tile_info->width;
401 }
402}
403
404static void InterpolateCLAHE(const RectangleInfo *clahe_info,const size_t *Q12,
405 const size_t *Q22,const size_t *Q11,const size_t *Q21,
406 const RectangleInfo *tile,const unsigned short *lut,unsigned short *pixels)
407{
408 ssize_t
409 y;
410
411 unsigned short
412 intensity;
413
414 /*
415 Bilinear interpolate four tiles to eliminate boundary artifacts.
416 */
417 for (y=(ssize_t) tile->height; y > 0; y--)
418 {
419 ssize_t
420 x;
421
422 for (x=(ssize_t) tile->width; x > 0; x--)
423 {
424 intensity=lut[*pixels];
425 *pixels++=(unsigned short) (MagickSafeReciprocal((double) tile->width*
426 tile->height)*(y*((double) x*Q12[intensity]+((double) tile->width-x)*
427 Q22[intensity])+((double) tile->height-y)*((double) x*Q11[intensity]+
428 ((double) tile->width-x)*Q21[intensity])));
429 }
430 pixels+=(clahe_info->width-tile->width);
431 }
432}
433
434static void GenerateCLAHELut(const RangeInfo *range_info,
435 const size_t number_bins,unsigned short *lut)
436{
437 ssize_t
438 i;
439
440 unsigned short
441 delta;
442
443 /*
444 Scale input image [intensity min,max] to [0,number_bins-1].
445 */
446 delta=(unsigned short) ((range_info->max-range_info->min)/number_bins+1);
447 for (i=(ssize_t) range_info->min; i <= (ssize_t) range_info->max; i++)
448 lut[i]=(unsigned short) ((i-range_info->min)/delta);
449}
450
451static void MapCLAHEHistogram(const RangeInfo *range_info,
452 const size_t number_bins,const size_t number_pixels,size_t *histogram)
453{
454 double
455 scale,
456 sum;
457
458 ssize_t
459 i;
460
461 /*
462 Rescale histogram to range [min-intensity .. max-intensity].
463 */
464 scale=(double) (range_info->max-range_info->min)/number_pixels;
465 sum=0.0;
466 for (i=0; i < (ssize_t) number_bins; i++)
467 {
468 sum+=histogram[i];
469 histogram[i]=(size_t) (range_info->min+scale*sum);
470 if (histogram[i] > range_info->max)
471 histogram[i]=range_info->max;
472 }
473}
474
475static MagickBooleanType CLAHE(const RectangleInfo *clahe_info,
476 const RectangleInfo *tile_info,const RangeInfo *range_info,
477 const size_t number_bins,const double clip_limit,unsigned short *pixels)
478{
479 MemoryInfo
480 *tile_cache;
481
482 size_t
483 limit,
484 *tiles;
485
486 ssize_t
487 y;
488
489 unsigned short
490 *lut,
491 *p;
492
493 /*
494 Contrast limited adapted histogram equalization.
495 */
496 if (clip_limit == 1.0)
497 return(MagickTrue);
498 tile_cache=AcquireVirtualMemory((size_t) clahe_info->x*number_bins,(size_t)
499 clahe_info->y*sizeof(*tiles));
500 if (tile_cache == (MemoryInfo *) NULL)
501 return(MagickFalse);
502 lut=(unsigned short *) AcquireQuantumMemory(NumberCLAHEGrays,sizeof(*lut));
503 if (lut == (unsigned short *) NULL)
504 {
505 tile_cache=RelinquishVirtualMemory(tile_cache);
506 return(MagickFalse);
507 }
508 tiles=(size_t *) GetVirtualMemoryBlob(tile_cache);
509 limit=(size_t) (clip_limit*((double) tile_info->width*tile_info->height)/
510 number_bins);
511 if (limit < 1UL)
512 limit=1UL;
513 /*
514 Generate greylevel mappings for each tile.
515 */
516 GenerateCLAHELut(range_info,number_bins,lut);
517 p=pixels;
518 for (y=0; y < (ssize_t) clahe_info->y; y++)
519 {
520 ssize_t
521 x;
522
523 for (x=0; x < (ssize_t) clahe_info->x; x++)
524 {
525 size_t
526 *histogram;
527
528 histogram=tiles+((ssize_t) number_bins*(y*clahe_info->x+x));
529 GenerateCLAHEHistogram(clahe_info,tile_info,number_bins,lut,p,histogram);
530 ClipCLAHEHistogram((double) limit,number_bins,histogram);
531 MapCLAHEHistogram(range_info,number_bins,tile_info->width*
532 tile_info->height,histogram);
533 p+=(ptrdiff_t) tile_info->width;
534 }
535 p+=CastDoubleToPtrdiffT((double) clahe_info->width*(tile_info->height-1));
536 }
537 /*
538 Interpolate greylevel mappings to get CLAHE image.
539 */
540 p=pixels;
541 for (y=0; y <= (ssize_t) clahe_info->y; y++)
542 {
543 OffsetInfo
544 offset;
545
546 RectangleInfo
547 tile;
548
549 ssize_t
550 x;
551
552 tile.height=tile_info->height;
553 tile.y=y-1;
554 offset.y=tile.y+1;
555 if (y == 0)
556 {
557 /*
558 Top row.
559 */
560 tile.height=tile_info->height >> 1;
561 tile.y=0;
562 offset.y=0;
563 }
564 else
565 if (y == (ssize_t) clahe_info->y)
566 {
567 /*
568 Bottom row.
569 */
570 tile.height=(tile_info->height+1) >> 1;
571 tile.y=clahe_info->y-1;
572 offset.y=tile.y;
573 }
574 for (x=0; x <= (ssize_t) clahe_info->x; x++)
575 {
576 double
577 Q11,
578 Q12,
579 Q21,
580 Q22;
581
582 tile.width=tile_info->width;
583 tile.x=x-1;
584 offset.x=tile.x+1;
585 if (x == 0)
586 {
587 /*
588 Left column.
589 */
590 tile.width=tile_info->width >> 1;
591 tile.x=0;
592 offset.x=0;
593 }
594 else
595 if (x == (ssize_t) clahe_info->x)
596 {
597 /*
598 Right column.
599 */
600 tile.width=(tile_info->width+1) >> 1;
601 tile.x=clahe_info->x-1;
602 offset.x=tile.x;
603 }
604 Q12=(double) number_bins*(tile.y*clahe_info->x+tile.x);
605 Q22=(double) number_bins*(tile.y*clahe_info->x+offset.x);
606 Q11=(double) number_bins*(offset.y*clahe_info->x+tile.x);
607 Q21=(double) number_bins*(offset.y*clahe_info->x+offset.x);
608 InterpolateCLAHE(clahe_info,tiles+CastDoubleToPtrdiffT(Q12),
609 tiles+CastDoubleToPtrdiffT(Q22),tiles+CastDoubleToPtrdiffT(Q11),
610 tiles+CastDoubleToPtrdiffT(Q21),&tile,lut,p);
611 p+=(ptrdiff_t) tile.width;
612 }
613 p+=CastDoubleToPtrdiffT((double) clahe_info->width*(tile.height-1));
614 }
615 lut=(unsigned short *) RelinquishMagickMemory(lut);
616 tile_cache=RelinquishVirtualMemory(tile_cache);
617 return(MagickTrue);
618}
619
620MagickExport MagickBooleanType CLAHEImage(Image *image,const size_t width,
621 const size_t height,const size_t number_bins,const double clip_limit,
622 ExceptionInfo *exception)
623{
624#define CLAHEImageTag "CLAHE/Image"
625
626 CacheView
627 *image_view;
628
629 ColorspaceType
630 colorspace;
631
632 MagickBooleanType
633 status;
634
635 MagickOffsetType
636 progress;
637
638 MemoryInfo
639 *pixel_cache;
640
641 RangeInfo
642 range_info;
643
644 RectangleInfo
645 clahe_info,
646 tile_info;
647
648 size_t
649 n;
650
651 ssize_t
652 y;
653
654 unsigned short
655 *pixels;
656
657 /*
658 Configure CLAHE parameters.
659 */
660 assert(image != (Image *) NULL);
661 assert(image->signature == MagickCoreSignature);
662 if (IsEventLogging() != MagickFalse)
663 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
664 range_info.min=0;
665 range_info.max=NumberCLAHEGrays-1;
666 tile_info.width=width;
667 if (tile_info.width == 0)
668 tile_info.width=image->columns >> 3;
669 if (tile_info.width < 2)
670 tile_info.width=2;
671 tile_info.height=height;
672 if (tile_info.height == 0)
673 tile_info.height=image->rows >> 3;
674 if (tile_info.height < 2)
675 tile_info.height=2;
676 tile_info.x=0;
677 if ((image->columns % tile_info.width) != 0)
678 tile_info.x=(ssize_t) (tile_info.width-(image->columns % tile_info.width));
679 tile_info.y=0;
680 if ((image->rows % tile_info.height) != 0)
681 tile_info.y=(ssize_t) (tile_info.height-(image->rows % tile_info.height));
682 clahe_info.width=(size_t) ((ssize_t) image->columns+tile_info.x);
683 clahe_info.height=(size_t) ((ssize_t) image->rows+tile_info.y);
684 clahe_info.x=(ssize_t) (clahe_info.width/tile_info.width);
685 clahe_info.y=(ssize_t) (clahe_info.height/tile_info.height);
686 pixel_cache=AcquireVirtualMemory(clahe_info.width,clahe_info.height*
687 sizeof(*pixels));
688 if (pixel_cache == (MemoryInfo *) NULL)
689 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
690 image->filename);
691 pixels=(unsigned short *) GetVirtualMemoryBlob(pixel_cache);
692 colorspace=image->colorspace;
693 if (TransformImageColorspace(image,LabColorspace,exception) == MagickFalse)
694 {
695 pixel_cache=RelinquishVirtualMemory(pixel_cache);
696 return(MagickFalse);
697 }
698 /*
699 Initialize CLAHE pixels.
700 */
701 image_view=AcquireVirtualCacheView(image,exception);
702 progress=0;
703 status=MagickTrue;
704 n=0;
705 for (y=0; y < (ssize_t) clahe_info.height; y++)
706 {
707 const Quantum
708 *magick_restrict p;
709
710 ssize_t
711 x;
712
713 if (status == MagickFalse)
714 continue;
715 p=GetCacheViewVirtualPixels(image_view,-(tile_info.x >> 1),y-
716 (tile_info.y >> 1),clahe_info.width,1,exception);
717 if (p == (const Quantum *) NULL)
718 {
719 status=MagickFalse;
720 continue;
721 }
722 for (x=0; x < (ssize_t) clahe_info.width; x++)
723 {
724 pixels[n++]=ScaleQuantumToShort(p[0]);
725 p+=(ptrdiff_t) GetPixelChannels(image);
726 }
727 if (image->progress_monitor != (MagickProgressMonitor) NULL)
728 {
729 MagickBooleanType
730 proceed;
731
732 progress++;
733 proceed=SetImageProgress(image,CLAHEImageTag,progress,2*
734 GetPixelChannels(image));
735 if (proceed == MagickFalse)
736 status=MagickFalse;
737 }
738 }
739 image_view=DestroyCacheView(image_view);
740 status=CLAHE(&clahe_info,&tile_info,&range_info,number_bins == 0 ?
741 (size_t) 128 : MagickMin(number_bins,256),clip_limit,pixels);
742 if (status == MagickFalse)
743 (void) ThrowMagickException(exception,GetMagickModule(),
744 ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
745 /*
746 Push CLAHE pixels to CLAHE image.
747 */
748 image_view=AcquireAuthenticCacheView(image,exception);
749 n=clahe_info.width*(size_t) (tile_info.y/2);
750 for (y=0; y < (ssize_t) image->rows; y++)
751 {
752 Quantum
753 *magick_restrict q;
754
755 ssize_t
756 x;
757
758 if (status == MagickFalse)
759 continue;
760 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
761 if (q == (Quantum *) NULL)
762 {
763 status=MagickFalse;
764 continue;
765 }
766 n+=(size_t) (tile_info.x/2);
767 for (x=0; x < (ssize_t) image->columns; x++)
768 {
769 q[0]=ScaleShortToQuantum(pixels[n++]);
770 q+=(ptrdiff_t) GetPixelChannels(image);
771 }
772 n+=(size_t) ((ssize_t) clahe_info.width-(ssize_t) image->columns-
773 (tile_info.x/2));
774 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
775 status=MagickFalse;
776 if (image->progress_monitor != (MagickProgressMonitor) NULL)
777 {
778 MagickBooleanType
779 proceed;
780
781 progress++;
782 proceed=SetImageProgress(image,CLAHEImageTag,progress,2*
783 GetPixelChannels(image));
784 if (proceed == MagickFalse)
785 status=MagickFalse;
786 }
787 }
788 image_view=DestroyCacheView(image_view);
789 pixel_cache=RelinquishVirtualMemory(pixel_cache);
790 if (TransformImageColorspace(image,colorspace,exception) == MagickFalse)
791 status=MagickFalse;
792 return(status);
793}
794␌
795/*
796%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
797% %
798% %
799% %
800% C l u t I m a g e %
801% %
802% %
803% %
804%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
805%
806% ClutImage() replaces each color value in the given image, by using it as an
807% index to lookup a replacement color value in a Color Look UP Table in the
808% form of an image. The values are extracted along a diagonal of the CLUT
809% image so either a horizontal or vertical gradient image can be used.
810%
811% Typically this is used to either re-color a gray-scale image according to a
812% color gradient in the CLUT image, or to perform a freeform histogram
813% (level) adjustment according to the (typically gray-scale) gradient in the
814% CLUT image.
815%
816% When the 'channel' mask includes the matte/alpha transparency channel but
817% one image has no such channel it is assumed that image is a simple
818% gray-scale image that will effect the alpha channel values, either for
819% gray-scale coloring (with transparent or semi-transparent colors), or
820% a histogram adjustment of existing alpha channel values. If both images
821% have matte channels, direct and normal indexing is applied, which is rarely
822% used.
823%
824% The format of the ClutImage method is:
825%
826% MagickBooleanType ClutImage(Image *image,Image *clut_image,
827% const PixelInterpolateMethod method,ExceptionInfo *exception)
828%
829% A description of each parameter follows:
830%
831% o image: the image, which is replaced by indexed CLUT values
832%
833% o clut_image: the color lookup table image for replacement color values.
834%
835% o method: the pixel interpolation method.
836%
837% o exception: return any errors or warnings in this structure.
838%
839*/
840MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image,
841 const PixelInterpolateMethod method,ExceptionInfo *exception)
842{
843#define ClutImageTag "Clut/Image"
844
845 CacheView
846 *clut_view,
847 *image_view;
848
849 MagickBooleanType
850 status;
851
852 MagickOffsetType
853 progress;
854
855 PixelInfo
856 *clut_map;
857
858 ssize_t
859 adjust,
860 i,
861 y;
862
863 assert(image != (Image *) NULL);
864 assert(image->signature == MagickCoreSignature);
865 assert(clut_image != (Image *) NULL);
866 assert(clut_image->signature == MagickCoreSignature);
867 if (IsEventLogging() != MagickFalse)
868 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
869 if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
870 return(MagickFalse);
871 if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
872 (IsGrayColorspace(clut_image->colorspace) == MagickFalse))
873 (void) SetImageColorspace(image,sRGBColorspace,exception);
874 clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map));
875 if (clut_map == (PixelInfo *) NULL)
876 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
877 image->filename);
878 /*
879 Clut image.
880 */
881 status=MagickTrue;
882 progress=0;
883 adjust=(ssize_t) (method == IntegerInterpolatePixel ? 0 : 1);
884 clut_view=AcquireVirtualCacheView(clut_image,exception);
885 for (i=0; i <= (ssize_t) MaxMap; i++)
886 {
887 GetPixelInfo(clut_image,clut_map+i);
888 status=InterpolatePixelInfo(clut_image,clut_view,method,(double) i*
889 ((double) clut_image->columns-adjust)/MaxMap,(double) i*
890 ((double) clut_image->rows-adjust)/MaxMap,clut_map+i,exception);
891 if (status == MagickFalse)
892 break;
893 }
894 clut_view=DestroyCacheView(clut_view);
895 image_view=AcquireAuthenticCacheView(image,exception);
896#if defined(MAGICKCORE_OPENMP_SUPPORT)
897 #pragma omp parallel for schedule(static) shared(progress,status) \
898 magick_number_threads(image,image,image->rows,1)
899#endif
900 for (y=0; y < (ssize_t) image->rows; y++)
901 {
902 PixelInfo
903 pixel;
904
905 Quantum
906 *magick_restrict q;
907
908 ssize_t
909 x;
910
911 if (status == MagickFalse)
912 continue;
913 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
914 if (q == (Quantum *) NULL)
915 {
916 status=MagickFalse;
917 continue;
918 }
919 GetPixelInfo(image,&pixel);
920 for (x=0; x < (ssize_t) image->columns; x++)
921 {
922 PixelTrait
923 traits;
924
925 GetPixelInfoPixel(image,q,&pixel);
926 traits=GetPixelChannelTraits(image,RedPixelChannel);
927 if ((traits & UpdatePixelTrait) != 0)
928 pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum(
929 pixel.red))].red;
930 traits=GetPixelChannelTraits(image,GreenPixelChannel);
931 if ((traits & UpdatePixelTrait) != 0)
932 pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum(
933 pixel.green))].green;
934 traits=GetPixelChannelTraits(image,BluePixelChannel);
935 if ((traits & UpdatePixelTrait) != 0)
936 pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum(
937 pixel.blue))].blue;
938 traits=GetPixelChannelTraits(image,BlackPixelChannel);
939 if ((traits & UpdatePixelTrait) != 0)
940 pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum(
941 pixel.black))].black;
942 traits=GetPixelChannelTraits(image,AlphaPixelChannel);
943 if ((traits & UpdatePixelTrait) != 0)
944 pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum(
945 pixel.alpha))].alpha;
946 SetPixelViaPixelInfo(image,&pixel,q);
947 q+=(ptrdiff_t) GetPixelChannels(image);
948 }
949 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
950 status=MagickFalse;
951 if (image->progress_monitor != (MagickProgressMonitor) NULL)
952 {
953 MagickBooleanType
954 proceed;
955
956#if defined(MAGICKCORE_OPENMP_SUPPORT)
957 #pragma omp atomic
958#endif
959 progress++;
960 proceed=SetImageProgress(image,ClutImageTag,progress,image->rows);
961 if (proceed == MagickFalse)
962 status=MagickFalse;
963 }
964 }
965 image_view=DestroyCacheView(image_view);
966 clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map);
967 if ((clut_image->alpha_trait != UndefinedPixelTrait) &&
968 ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0))
969 (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception);
970 return(status);
971}
972␌
973/*
974%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
975% %
976% %
977% %
978% C o l o r D e c i s i o n L i s t I m a g e %
979% %
980% %
981% %
982%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
983%
984% ColorDecisionListImage() accepts a lightweight Color Correction Collection
985% (CCC) file which solely contains one or more color corrections and applies
986% the correction to the image. Here is a sample CCC file:
987%
988% <ColorCorrectionCollection xmlns="urn:ASC:CDL:v1.2">
989% <ColorCorrection id="cc03345">
990% <SOPNode>
991% <Slope> 0.9 1.2 0.5 </Slope>
992% <Offset> 0.4 -0.5 0.6 </Offset>
993% <Power> 1.0 0.8 1.5 </Power>
994% </SOPNode>
995% <SATNode>
996% <Saturation> 0.85 </Saturation>
997% </SATNode>
998% </ColorCorrection>
999% </ColorCorrectionCollection>
1000%
1001% which includes the slop, offset, and power for each of the RGB channels
1002% as well as the saturation.
1003%
1004% The format of the ColorDecisionListImage method is:
1005%
1006% MagickBooleanType ColorDecisionListImage(Image *image,
1007% const char *color_correction_collection,ExceptionInfo *exception)
1008%
1009% A description of each parameter follows:
1010%
1011% o image: the image.
1012%
1013% o color_correction_collection: the color correction collection in XML.
1014%
1015% o exception: return any errors or warnings in this structure.
1016%
1017*/
1018MagickExport MagickBooleanType ColorDecisionListImage(Image *image,
1019 const char *color_correction_collection,ExceptionInfo *exception)
1020{
1021#define ColorDecisionListCorrectImageTag "ColorDecisionList/Image"
1022
1023 typedef struct _Correction
1024 {
1025 double
1026 slope,
1027 offset,
1028 power;
1029 } Correction;
1030
1031 typedef struct _ColorCorrection
1032 {
1033 Correction
1034 red,
1035 green,
1036 blue;
1037
1038 double
1039 saturation;
1040 } ColorCorrection;
1041
1042 CacheView
1043 *image_view;
1044
1045 char
1046 token[MagickPathExtent];
1047
1048 ColorCorrection
1049 color_correction;
1050
1051 const char
1052 *content,
1053 *p;
1054
1055 MagickBooleanType
1056 status;
1057
1058 MagickOffsetType
1059 progress;
1060
1061 PixelInfo
1062 *cdl_map;
1063
1064 ssize_t
1065 i;
1066
1067 ssize_t
1068 y;
1069
1070 XMLTreeInfo
1071 *cc,
1072 *ccc,
1073 *sat,
1074 *sop;
1075
1076 /*
1077 Allocate and initialize cdl maps.
1078 */
1079 assert(image != (Image *) NULL);
1080 assert(image->signature == MagickCoreSignature);
1081 if (IsEventLogging() != MagickFalse)
1082 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1083 if (color_correction_collection == (const char *) NULL)
1084 return(MagickFalse);
1085 ccc=NewXMLTree((const char *) color_correction_collection,exception);
1086 if (ccc == (XMLTreeInfo *) NULL)
1087 return(MagickFalse);
1088 cc=GetXMLTreeChild(ccc,"ColorCorrection");
1089 if (cc == (XMLTreeInfo *) NULL)
1090 {
1091 ccc=DestroyXMLTree(ccc);
1092 return(MagickFalse);
1093 }
1094 color_correction.red.slope=1.0;
1095 color_correction.red.offset=0.0;
1096 color_correction.red.power=1.0;
1097 color_correction.green.slope=1.0;
1098 color_correction.green.offset=0.0;
1099 color_correction.green.power=1.0;
1100 color_correction.blue.slope=1.0;
1101 color_correction.blue.offset=0.0;
1102 color_correction.blue.power=1.0;
1103 color_correction.saturation=0.0;
1104 sop=GetXMLTreeChild(cc,"SOPNode");
1105 if (sop != (XMLTreeInfo *) NULL)
1106 {
1107 XMLTreeInfo
1108 *offset,
1109 *power,
1110 *slope;
1111
1112 slope=GetXMLTreeChild(sop,"Slope");
1113 if (slope != (XMLTreeInfo *) NULL)
1114 {
1115 content=GetXMLTreeContent(slope);
1116 p=(const char *) content;
1117 for (i=0; (*p != '\0') && (i < 3); i++)
1118 {
1119 (void) GetNextToken(p,&p,MagickPathExtent,token);
1120 if (*token == ',')
1121 (void) GetNextToken(p,&p,MagickPathExtent,token);
1122 switch (i)
1123 {
1124 case 0:
1125 {
1126 color_correction.red.slope=StringToDouble(token,(char **) NULL);
1127 break;
1128 }
1129 case 1:
1130 {
1131 color_correction.green.slope=StringToDouble(token,
1132 (char **) NULL);
1133 break;
1134 }
1135 case 2:
1136 {
1137 color_correction.blue.slope=StringToDouble(token,
1138 (char **) NULL);
1139 break;
1140 }
1141 }
1142 }
1143 }
1144 offset=GetXMLTreeChild(sop,"Offset");
1145 if (offset != (XMLTreeInfo *) NULL)
1146 {
1147 content=GetXMLTreeContent(offset);
1148 p=(const char *) content;
1149 for (i=0; (*p != '\0') && (i < 3); i++)
1150 {
1151 (void) GetNextToken(p,&p,MagickPathExtent,token);
1152 if (*token == ',')
1153 (void) GetNextToken(p,&p,MagickPathExtent,token);
1154 switch (i)
1155 {
1156 case 0:
1157 {
1158 color_correction.red.offset=StringToDouble(token,
1159 (char **) NULL);
1160 break;
1161 }
1162 case 1:
1163 {
1164 color_correction.green.offset=StringToDouble(token,
1165 (char **) NULL);
1166 break;
1167 }
1168 case 2:
1169 {
1170 color_correction.blue.offset=StringToDouble(token,
1171 (char **) NULL);
1172 break;
1173 }
1174 }
1175 }
1176 }
1177 power=GetXMLTreeChild(sop,"Power");
1178 if (power != (XMLTreeInfo *) NULL)
1179 {
1180 content=GetXMLTreeContent(power);
1181 p=(const char *) content;
1182 for (i=0; (*p != '\0') && (i < 3); i++)
1183 {
1184 (void) GetNextToken(p,&p,MagickPathExtent,token);
1185 if (*token == ',')
1186 (void) GetNextToken(p,&p,MagickPathExtent,token);
1187 switch (i)
1188 {
1189 case 0:
1190 {
1191 color_correction.red.power=StringToDouble(token,(char **) NULL);
1192 break;
1193 }
1194 case 1:
1195 {
1196 color_correction.green.power=StringToDouble(token,
1197 (char **) NULL);
1198 break;
1199 }
1200 case 2:
1201 {
1202 color_correction.blue.power=StringToDouble(token,
1203 (char **) NULL);
1204 break;
1205 }
1206 }
1207 }
1208 }
1209 }
1210 sat=GetXMLTreeChild(cc,"SATNode");
1211 if (sat != (XMLTreeInfo *) NULL)
1212 {
1213 XMLTreeInfo
1214 *saturation;
1215
1216 saturation=GetXMLTreeChild(sat,"Saturation");
1217 if (saturation != (XMLTreeInfo *) NULL)
1218 {
1219 content=GetXMLTreeContent(saturation);
1220 p=(const char *) content;
1221 (void) GetNextToken(p,&p,MagickPathExtent,token);
1222 color_correction.saturation=StringToDouble(token,(char **) NULL);
1223 }
1224 }
1225 ccc=DestroyXMLTree(ccc);
1226 if (image->debug != MagickFalse)
1227 {
1228 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1229 " Color Correction Collection:");
1230 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1231 " color_correction.red.slope: %g",color_correction.red.slope);
1232 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1233 " color_correction.red.offset: %g",color_correction.red.offset);
1234 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1235 " color_correction.red.power: %g",color_correction.red.power);
1236 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1237 " color_correction.green.slope: %g",color_correction.green.slope);
1238 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1239 " color_correction.green.offset: %g",color_correction.green.offset);
1240 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1241 " color_correction.green.power: %g",color_correction.green.power);
1242 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1243 " color_correction.blue.slope: %g",color_correction.blue.slope);
1244 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1245 " color_correction.blue.offset: %g",color_correction.blue.offset);
1246 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1247 " color_correction.blue.power: %g",color_correction.blue.power);
1248 (void) LogMagickEvent(TransformEvent,GetMagickModule(),
1249 " color_correction.saturation: %g",color_correction.saturation);
1250 }
1251 cdl_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*cdl_map));
1252 if (cdl_map == (PixelInfo *) NULL)
1253 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
1254 image->filename);
1255 for (i=0; i <= (ssize_t) MaxMap; i++)
1256 {
1257 cdl_map[i].red=(double) ScaleMapToQuantum((double)
1258 (MaxMap*(pow(color_correction.red.slope*i/MaxMap+
1259 color_correction.red.offset,color_correction.red.power))));
1260 cdl_map[i].green=(double) ScaleMapToQuantum((double)
1261 (MaxMap*(pow(color_correction.green.slope*i/MaxMap+
1262 color_correction.green.offset,color_correction.green.power))));
1263 cdl_map[i].blue=(double) ScaleMapToQuantum((double)
1264 (MaxMap*(pow(color_correction.blue.slope*i/MaxMap+
1265 color_correction.blue.offset,color_correction.blue.power))));
1266 }
1267 if (image->storage_class == PseudoClass)
1268 {
1269 for (i=0; i < (ssize_t) image->colors; i++)
1270 {
1271 /*
1272 Apply transfer function to colormap.
1273 */
1274 double
1275 luma;
1276
1277 luma=0.21267*image->colormap[i].red+0.71526*image->colormap[i].green+
1278 0.07217*image->colormap[i].blue;
1279 image->colormap[i].red=luma+color_correction.saturation*cdl_map[
1280 ScaleQuantumToMap(ClampToQuantum(image->colormap[i].red))].red-luma;
1281 image->colormap[i].green=luma+color_correction.saturation*cdl_map[
1282 ScaleQuantumToMap(ClampToQuantum(image->colormap[i].green))].green-
1283 luma;
1284 image->colormap[i].blue=luma+color_correction.saturation*cdl_map[
1285 ScaleQuantumToMap(ClampToQuantum(image->colormap[i].blue))].blue-luma;
1286 }
1287 cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map);
1288 (void) SyncImage(image, exception);
1289 return(MagickTrue);
1290 }
1291 /*
1292 Apply transfer function to image.
1293 */
1294 status=MagickTrue;
1295 progress=0;
1296 image_view=AcquireAuthenticCacheView(image,exception);
1297#if defined(MAGICKCORE_OPENMP_SUPPORT)
1298 #pragma omp parallel for schedule(static) shared(progress,status) \
1299 magick_number_threads(image,image,image->rows,1)
1300#endif
1301 for (y=0; y < (ssize_t) image->rows; y++)
1302 {
1303 double
1304 luma;
1305
1306 Quantum
1307 *magick_restrict q;
1308
1309 ssize_t
1310 x;
1311
1312 if (status == MagickFalse)
1313 continue;
1314 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1315 if (q == (Quantum *) NULL)
1316 {
1317 status=MagickFalse;
1318 continue;
1319 }
1320 for (x=0; x < (ssize_t) image->columns; x++)
1321 {
1322 luma=0.21267*(double) GetPixelRed(image,q)+0.71526*(double)
1323 GetPixelGreen(image,q)+0.07217*(double) GetPixelBlue(image,q);
1324 SetPixelRed(image,ClampToQuantum(luma+color_correction.saturation*
1325 (cdl_map[ScaleQuantumToMap(GetPixelRed(image,q))].red-luma)),q);
1326 SetPixelGreen(image,ClampToQuantum(luma+color_correction.saturation*
1327 (cdl_map[ScaleQuantumToMap(GetPixelGreen(image,q))].green-luma)),q);
1328 SetPixelBlue(image,ClampToQuantum(luma+color_correction.saturation*
1329 (cdl_map[ScaleQuantumToMap(GetPixelBlue(image,q))].blue-luma)),q);
1330 q+=(ptrdiff_t) GetPixelChannels(image);
1331 }
1332 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1333 status=MagickFalse;
1334 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1335 {
1336 MagickBooleanType
1337 proceed;
1338
1339#if defined(MAGICKCORE_OPENMP_SUPPORT)
1340 #pragma omp atomic
1341#endif
1342 progress++;
1343 proceed=SetImageProgress(image,ColorDecisionListCorrectImageTag,
1344 progress,image->rows);
1345 if (proceed == MagickFalse)
1346 status=MagickFalse;
1347 }
1348 }
1349 image_view=DestroyCacheView(image_view);
1350 cdl_map=(PixelInfo *) RelinquishMagickMemory(cdl_map);
1351 return(status);
1352}
1353␌
1354/*
1355%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1356% %
1357% %
1358% %
1359% C o n t r a s t I m a g e %
1360% %
1361% %
1362% %
1363%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1364%
1365% ContrastImage() enhances the intensity differences between the lighter and
1366% darker elements of the image. Set sharpen to a MagickTrue to increase the
1367% image contrast otherwise the contrast is reduced.
1368%
1369% The format of the ContrastImage method is:
1370%
1371% MagickBooleanType ContrastImage(Image *image,
1372% const MagickBooleanType sharpen,ExceptionInfo *exception)
1373%
1374% A description of each parameter follows:
1375%
1376% o image: the image.
1377%
1378% o sharpen: Increase or decrease image contrast.
1379%
1380% o exception: return any errors or warnings in this structure.
1381%
1382*/
1383
1384static inline void Contrast(const int sign,double *red,double *green,
1385 double *blue)
1386{
1387 double
1388 brightness = 0.0,
1389 hue = 0.0,
1390 saturation = 0.0;
1391
1392 /*
1393 Enhance contrast: dark color become darker, light color become lighter.
1394 */
1395 ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
1396 brightness+=0.5*sign*(0.5*(sin((double) (MagickPI*(brightness-0.5)))+1.0)-
1397 brightness);
1398 if (brightness > 1.0)
1399 brightness=1.0;
1400 else
1401 if (brightness < 0.0)
1402 brightness=0.0;
1403 ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
1404}
1405
1406MagickExport MagickBooleanType ContrastImage(Image *image,
1407 const MagickBooleanType sharpen,ExceptionInfo *exception)
1408{
1409#define ContrastImageTag "Contrast/Image"
1410
1411 CacheView
1412 *image_view;
1413
1414 int
1415 sign;
1416
1417 MagickBooleanType
1418 status;
1419
1420 MagickOffsetType
1421 progress;
1422
1423 ssize_t
1424 i;
1425
1426 ssize_t
1427 y;
1428
1429 assert(image != (Image *) NULL);
1430 assert(image->signature == MagickCoreSignature);
1431#if defined(MAGICKCORE_OPENCL_SUPPORT)
1432 if (AccelerateContrastImage(image,sharpen,exception) != MagickFalse)
1433 return(MagickTrue);
1434#endif
1435 if (IsEventLogging() != MagickFalse)
1436 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1437 sign=sharpen != MagickFalse ? 1 : -1;
1438 if (image->storage_class == PseudoClass)
1439 {
1440 /*
1441 Contrast enhance colormap.
1442 */
1443 for (i=0; i < (ssize_t) image->colors; i++)
1444 {
1445 double
1446 blue,
1447 green,
1448 red;
1449
1450 red=(double) image->colormap[i].red;
1451 green=(double) image->colormap[i].green;
1452 blue=(double) image->colormap[i].blue;
1453 Contrast(sign,&red,&green,&blue);
1454 image->colormap[i].red=(MagickRealType) red;
1455 image->colormap[i].green=(MagickRealType) green;
1456 image->colormap[i].blue=(MagickRealType) blue;
1457 }
1458 }
1459 /*
1460 Contrast enhance image.
1461 */
1462 status=MagickTrue;
1463 progress=0;
1464 image_view=AcquireAuthenticCacheView(image,exception);
1465#if defined(MAGICKCORE_OPENMP_SUPPORT)
1466 #pragma omp parallel for schedule(static) shared(progress,status) \
1467 magick_number_threads(image,image,image->rows,1)
1468#endif
1469 for (y=0; y < (ssize_t) image->rows; y++)
1470 {
1471 double
1472 blue,
1473 green,
1474 red;
1475
1476 Quantum
1477 *magick_restrict q;
1478
1479 ssize_t
1480 x;
1481
1482 if (status == MagickFalse)
1483 continue;
1484 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1485 if (q == (Quantum *) NULL)
1486 {
1487 status=MagickFalse;
1488 continue;
1489 }
1490 for (x=0; x < (ssize_t) image->columns; x++)
1491 {
1492 red=(double) GetPixelRed(image,q);
1493 green=(double) GetPixelGreen(image,q);
1494 blue=(double) GetPixelBlue(image,q);
1495 Contrast(sign,&red,&green,&blue);
1496 SetPixelRed(image,ClampToQuantum(red),q);
1497 SetPixelGreen(image,ClampToQuantum(green),q);
1498 SetPixelBlue(image,ClampToQuantum(blue),q);
1499 q+=(ptrdiff_t) GetPixelChannels(image);
1500 }
1501 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1502 status=MagickFalse;
1503 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1504 {
1505 MagickBooleanType
1506 proceed;
1507
1508#if defined(MAGICKCORE_OPENMP_SUPPORT)
1509 #pragma omp atomic
1510#endif
1511 progress++;
1512 proceed=SetImageProgress(image,ContrastImageTag,progress,image->rows);
1513 if (proceed == MagickFalse)
1514 status=MagickFalse;
1515 }
1516 }
1517 image_view=DestroyCacheView(image_view);
1518 return(status);
1519}
1520␌
1521/*
1522%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1523% %
1524% %
1525% %
1526% C o n t r a s t S t r e t c h I m a g e %
1527% %
1528% %
1529% %
1530%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1531%
1532% ContrastStretchImage() is a simple image enhancement technique that attempts
1533% to improve the contrast in an image by 'stretching' the range of intensity
1534% values it contains to span a desired range of values. It differs from the
1535% more sophisticated histogram equalization in that it can only apply a
1536% linear scaling function to the image pixel values. As a result the
1537% 'enhancement' is less harsh.
1538%
1539% The format of the ContrastStretchImage method is:
1540%
1541% MagickBooleanType ContrastStretchImage(Image *image,
1542% const char *levels,ExceptionInfo *exception)
1543%
1544% A description of each parameter follows:
1545%
1546% o image: the image.
1547%
1548% o black_point: the black point.
1549%
1550% o white_point: the white point.
1551%
1552% o levels: Specify the levels where the black and white points have the
1553% range of 0 to number-of-pixels (e.g. 1%, 10x90%, etc.).
1554%
1555% o exception: return any errors or warnings in this structure.
1556%
1557*/
1558MagickExport MagickBooleanType ContrastStretchImage(Image *image,
1559 const double black_point,const double white_point,ExceptionInfo *exception)
1560{
1561#define ContrastStretchImageTag "ContrastStretch/Image"
1562
1563 CacheView
1564 *image_view;
1565
1566 char
1567 property[MagickPathExtent];
1568
1569 double
1570 *histogram;
1571
1572 ImageType
1573 type;
1574
1575 MagickBooleanType
1576 status;
1577
1578 MagickOffsetType
1579 progress;
1580
1581 Quantum
1582 *black,
1583 *stretch_map,
1584 *white;
1585
1586 ssize_t
1587 i;
1588
1589 ssize_t
1590 y;
1591
1592 /*
1593 Allocate histogram and stretch map.
1594 */
1595 assert(image != (Image *) NULL);
1596 assert(image->signature == MagickCoreSignature);
1597 if (IsEventLogging() != MagickFalse)
1598 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1599 type=IdentifyImageType(image,exception);
1600 if (IsGrayImageType(type) != MagickFalse)
1601 (void) SetImageColorspace(image,GRAYColorspace,exception);
1602 black=(Quantum *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*black));
1603 white=(Quantum *) AcquireQuantumMemory(MaxPixelChannels,sizeof(*white));
1604 stretch_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
1605 sizeof(*stretch_map));
1606 histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
1607 sizeof(*histogram));
1608 if ((black == (Quantum *) NULL) || (white == (Quantum *) NULL) ||
1609 (stretch_map == (Quantum *) NULL) || (histogram == (double *) NULL))
1610 {
1611 if (histogram != (double *) NULL)
1612 histogram=(double *) RelinquishMagickMemory(histogram);
1613 if (stretch_map != (Quantum *) NULL)
1614 stretch_map=(Quantum *) RelinquishMagickMemory(stretch_map);
1615 if (white != (Quantum *) NULL)
1616 white=(Quantum *) RelinquishMagickMemory(white);
1617 if (black != (Quantum *) NULL)
1618 black=(Quantum *) RelinquishMagickMemory(black);
1619 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
1620 image->filename);
1621 }
1622 /*
1623 Form histogram.
1624 */
1625 status=MagickTrue;
1626 (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
1627 sizeof(*histogram));
1628 image_view=AcquireVirtualCacheView(image,exception);
1629 for (y=0; y < (ssize_t) image->rows; y++)
1630 {
1631 const Quantum
1632 *magick_restrict p;
1633
1634 ssize_t
1635 x;
1636
1637 if (status == MagickFalse)
1638 continue;
1639 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
1640 if (p == (const Quantum *) NULL)
1641 {
1642 status=MagickFalse;
1643 continue;
1644 }
1645 for (x=0; x < (ssize_t) image->columns; x++)
1646 {
1647 double
1648 pixel;
1649
1650 pixel=GetPixelIntensity(image,p);
1651 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1652 {
1653 if (image->channel_mask != AllChannels)
1654 pixel=(double) p[i];
1655 histogram[GetPixelChannels(image)*ScaleQuantumToMap(
1656 ClampToQuantum(pixel))+(size_t) i]++;
1657 }
1658 p+=(ptrdiff_t) GetPixelChannels(image);
1659 }
1660 }
1661 image_view=DestroyCacheView(image_view);
1662 /*
1663 Find the histogram boundaries by locating the black/white levels.
1664 */
1665 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1666 {
1667 double
1668 intensity;
1669
1670 ssize_t
1671 j;
1672
1673 black[i]=(Quantum) 0;
1674 white[i]=(Quantum) ScaleQuantumToMap(QuantumRange);
1675 intensity=0.0;
1676 for (j=0; j <= (ssize_t) MaxMap; j++)
1677 {
1678 intensity+=histogram[(ssize_t) GetPixelChannels(image)*j+i];
1679 if (intensity > black_point)
1680 break;
1681 }
1682 black[i]=(Quantum) j;
1683 intensity=0.0;
1684 for (j=(ssize_t) MaxMap; j != 0; j--)
1685 {
1686 intensity+=histogram[(ssize_t) GetPixelChannels(image)*j+i];
1687 if (intensity > ((double) image->columns*image->rows-white_point))
1688 break;
1689 }
1690 white[i]=(Quantum) j;
1691 }
1692 histogram=(double *) RelinquishMagickMemory(histogram);
1693 /*
1694 Stretch the histogram to create the stretched image mapping.
1695 */
1696 (void) memset(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)*
1697 sizeof(*stretch_map));
1698 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
1699 {
1700 ssize_t
1701 j;
1702
1703 for (j=0; j <= (ssize_t) MaxMap; j++)
1704 {
1705 double
1706 gamma;
1707
1708 gamma=MagickSafeReciprocal(white[i]-black[i]);
1709 if (j < (ssize_t) black[i])
1710 stretch_map[(ssize_t) GetPixelChannels(image)*j+i]=(Quantum) 0;
1711 else
1712 if (j > (ssize_t) white[i])
1713 stretch_map[(ssize_t) GetPixelChannels(image)*j+i]=QuantumRange;
1714 else
1715 if (black[i] != white[i])
1716 stretch_map[(ssize_t) GetPixelChannels(image)*j+i]=
1717 ScaleMapToQuantum((double) (MaxMap*gamma*(j-(double) black[i])));
1718 }
1719 }
1720 if (image->storage_class == PseudoClass)
1721 {
1722 ssize_t
1723 j;
1724
1725 /*
1726 Stretch-contrast colormap.
1727 */
1728 for (j=0; j < (ssize_t) image->colors; j++)
1729 {
1730 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
1731 {
1732 i=GetPixelChannelOffset(image,RedPixelChannel);
1733 image->colormap[j].red=(MagickRealType) stretch_map[
1734 GetPixelChannels(image)*ScaleQuantumToMap(ClampToQuantum(
1735 image->colormap[j].red))+(size_t) i];
1736 }
1737 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
1738 {
1739 i=GetPixelChannelOffset(image,GreenPixelChannel);
1740 image->colormap[j].green=(MagickRealType) stretch_map[
1741 GetPixelChannels(image)*ScaleQuantumToMap(ClampToQuantum(
1742 image->colormap[j].green))+(size_t) i];
1743 }
1744 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
1745 {
1746 i=GetPixelChannelOffset(image,BluePixelChannel);
1747 image->colormap[j].blue=(MagickRealType) stretch_map[
1748 GetPixelChannels(image)*ScaleQuantumToMap(ClampToQuantum(
1749 image->colormap[j].blue))+(size_t) i];
1750 }
1751 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
1752 {
1753 i=GetPixelChannelOffset(image,AlphaPixelChannel);
1754 image->colormap[j].alpha=(MagickRealType) stretch_map[
1755 GetPixelChannels(image)*ScaleQuantumToMap(ClampToQuantum(
1756 image->colormap[j].alpha))+(size_t) i];
1757 }
1758 }
1759 }
1760 /*
1761 Stretch-contrast image.
1762 */
1763 status=MagickTrue;
1764 progress=0;
1765 image_view=AcquireAuthenticCacheView(image,exception);
1766#if defined(MAGICKCORE_OPENMP_SUPPORT)
1767 #pragma omp parallel for schedule(static) shared(progress,status) \
1768 magick_number_threads(image,image,image->rows,1)
1769#endif
1770 for (y=0; y < (ssize_t) image->rows; y++)
1771 {
1772 Quantum
1773 *magick_restrict q;
1774
1775 ssize_t
1776 x;
1777
1778 if (status == MagickFalse)
1779 continue;
1780 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
1781 if (q == (Quantum *) NULL)
1782 {
1783 status=MagickFalse;
1784 continue;
1785 }
1786 for (x=0; x < (ssize_t) image->columns; x++)
1787 {
1788 ssize_t
1789 j;
1790
1791 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
1792 {
1793 PixelChannel channel = GetPixelChannelChannel(image,j);
1794 PixelTrait traits = GetPixelChannelTraits(image,channel);
1795 if ((traits & UpdatePixelTrait) == 0)
1796 continue;
1797 if (black[j] == white[j])
1798 continue;
1799 q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)*
1800 ScaleQuantumToMap(q[j])+(size_t) j]);
1801 }
1802 q+=(ptrdiff_t) GetPixelChannels(image);
1803 }
1804 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1805 status=MagickFalse;
1806 if (image->progress_monitor != (MagickProgressMonitor) NULL)
1807 {
1808 MagickBooleanType
1809 proceed;
1810
1811#if defined(MAGICKCORE_OPENMP_SUPPORT)
1812 #pragma omp atomic
1813#endif
1814 progress++;
1815 proceed=SetImageProgress(image,ContrastStretchImageTag,progress,
1816 image->rows);
1817 if (proceed == MagickFalse)
1818 status=MagickFalse;
1819 }
1820 }
1821 image_view=DestroyCacheView(image_view);
1822 (void) FormatLocaleString(property,MagickPathExtent,"%gx%g%%",100.0*
1823 QuantumScale*GetPixelIntensity(image,black),100.0*QuantumScale*
1824 GetPixelIntensity(image,white));
1825 (void) SetImageProperty(image,"histogram:contrast-stretch",property,
1826 exception);
1827 white=(Quantum *) RelinquishMagickMemory(white);
1828 black=(Quantum *) RelinquishMagickMemory(black);
1829 stretch_map=(Quantum *) RelinquishMagickMemory(stretch_map);
1830 return(status);
1831}
1832␌
1833/*
1834%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1835% %
1836% %
1837% %
1838% E n h a n c e I m a g e %
1839% %
1840% %
1841% %
1842%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1843%
1844% EnhanceImage() applies a digital filter that improves the quality of a
1845% noisy image.
1846%
1847% The format of the EnhanceImage method is:
1848%
1849% Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
1850%
1851% A description of each parameter follows:
1852%
1853% o image: the image.
1854%
1855% o exception: return any errors or warnings in this structure.
1856%
1857*/
1858MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
1859{
1860#define EnhanceImageTag "Enhance/Image"
1861#define EnhancePixel(weight) \
1862 mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
1863 distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
1864 distance_squared=(4.0+mean)*distance*distance; \
1865 mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
1866 distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
1867 distance_squared+=(7.0-mean)*distance*distance; \
1868 mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
1869 distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
1870 distance_squared+=(5.0-mean)*distance*distance; \
1871 mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
1872 distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
1873 distance_squared+=(5.0-mean)*distance*distance; \
1874 mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
1875 distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
1876 distance_squared+=(5.0-mean)*distance*distance; \
1877 if (distance_squared < 0.069) \
1878 { \
1879 aggregate.red+=(weight)*(double) GetPixelRed(image,r); \
1880 aggregate.green+=(weight)*(double) GetPixelGreen(image,r); \
1881 aggregate.blue+=(weight)*(double) GetPixelBlue(image,r); \
1882 aggregate.black+=(weight)*(double) GetPixelBlack(image,r); \
1883 aggregate.alpha+=(weight)*(double) GetPixelAlpha(image,r); \
1884 total_weight+=(weight); \
1885 } \
1886 r+=(ptrdiff_t) GetPixelChannels(image);
1887
1888 CacheView
1889 *enhance_view,
1890 *image_view;
1891
1892 Image
1893 *enhance_image;
1894
1895 MagickBooleanType
1896 status;
1897
1898 MagickOffsetType
1899 progress;
1900
1901 ssize_t
1902 y;
1903
1904 /*
1905 Initialize enhanced image attributes.
1906 */
1907 assert(image != (const Image *) NULL);
1908 assert(image->signature == MagickCoreSignature);
1909 if (IsEventLogging() != MagickFalse)
1910 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1911 assert(exception != (ExceptionInfo *) NULL);
1912 assert(exception->signature == MagickCoreSignature);
1913 enhance_image=CloneImage(image,0,0,MagickTrue,
1914 exception);
1915 if (enhance_image == (Image *) NULL)
1916 return((Image *) NULL);
1917 if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
1918 {
1919 enhance_image=DestroyImage(enhance_image);
1920 return((Image *) NULL);
1921 }
1922 /*
1923 Enhance image.
1924 */
1925 status=MagickTrue;
1926 progress=0;
1927 image_view=AcquireVirtualCacheView(image,exception);
1928 enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
1929#if defined(MAGICKCORE_OPENMP_SUPPORT)
1930 #pragma omp parallel for schedule(static) shared(progress,status) \
1931 magick_number_threads(image,enhance_image,image->rows,1)
1932#endif
1933 for (y=0; y < (ssize_t) image->rows; y++)
1934 {
1935 PixelInfo
1936 pixel;
1937
1938 const Quantum
1939 *magick_restrict p;
1940
1941 Quantum
1942 *magick_restrict q;
1943
1944 ssize_t
1945 x;
1946
1947 ssize_t
1948 center;
1949
1950 if (status == MagickFalse)
1951 continue;
1952 p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
1953 q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
1954 exception);
1955 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
1956 {
1957 status=MagickFalse;
1958 continue;
1959 }
1960 center=(ssize_t) GetPixelChannels(image)*(2*((ssize_t) image->columns+4)+2);
1961 GetPixelInfo(image,&pixel);
1962 for (x=0; x < (ssize_t) image->columns; x++)
1963 {
1964 double
1965 distance,
1966 distance_squared,
1967 mean,
1968 total_weight;
1969
1970 PixelInfo
1971 aggregate;
1972
1973 const Quantum
1974 *magick_restrict r;
1975
1976 GetPixelInfo(image,&aggregate);
1977 total_weight=0.0;
1978 GetPixelInfoPixel(image,p+center,&pixel);
1979 r=p;
1980 EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
1981 EnhancePixel(8.0); EnhancePixel(5.0);
1982 r=p+GetPixelChannels(image)*(image->columns+4);
1983 EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
1984 EnhancePixel(20.0); EnhancePixel(8.0);
1985 r=p+2*GetPixelChannels(image)*(image->columns+4);
1986 EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
1987 EnhancePixel(40.0); EnhancePixel(10.0);
1988 r=p+3*GetPixelChannels(image)*(image->columns+4);
1989 EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
1990 EnhancePixel(20.0); EnhancePixel(8.0);
1991 r=p+4*GetPixelChannels(image)*(image->columns+4);
1992 EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
1993 EnhancePixel(8.0); EnhancePixel(5.0);
1994 if (total_weight > MagickEpsilon)
1995 {
1996 pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
1997 pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
1998 pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
1999 pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
2000 pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
2001 }
2002 SetPixelViaPixelInfo(enhance_image,&pixel,q);
2003 p+=(ptrdiff_t) GetPixelChannels(image);
2004 q+=(ptrdiff_t) GetPixelChannels(enhance_image);
2005 }
2006 if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
2007 status=MagickFalse;
2008 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2009 {
2010 MagickBooleanType
2011 proceed;
2012
2013#if defined(MAGICKCORE_OPENMP_SUPPORT)
2014 #pragma omp atomic
2015#endif
2016 progress++;
2017 proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows);
2018 if (proceed == MagickFalse)
2019 status=MagickFalse;
2020 }
2021 }
2022 enhance_view=DestroyCacheView(enhance_view);
2023 image_view=DestroyCacheView(image_view);
2024 if (status == MagickFalse)
2025 enhance_image=DestroyImage(enhance_image);
2026 return(enhance_image);
2027}
2028␌
2029/*
2030%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2031% %
2032% %
2033% %
2034% E q u a l i z e I m a g e %
2035% %
2036% %
2037% %
2038%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2039%
2040% EqualizeImage() applies a histogram equalization to the image.
2041%
2042% The format of the EqualizeImage method is:
2043%
2044% MagickBooleanType EqualizeImage(Image *image,ExceptionInfo *exception)
2045%
2046% A description of each parameter follows:
2047%
2048% o image: the image.
2049%
2050% o exception: return any errors or warnings in this structure.
2051%
2052*/
2053MagickExport MagickBooleanType EqualizeImage(Image *image,
2054 ExceptionInfo *exception)
2055{
2056#define EqualizeImageTag "Equalize/Image"
2057
2058 CacheView
2059 *image_view;
2060
2061 double
2062 black[2*CompositePixelChannel+1],
2063 *equalize_map,
2064 *histogram,
2065 *map,
2066 white[2*CompositePixelChannel+1];
2067
2068 MagickBooleanType
2069 status;
2070
2071 MagickOffsetType
2072 progress;
2073
2074 ssize_t
2075 i;
2076
2077 ssize_t
2078 y;
2079
2080 /*
2081 Allocate and initialize histogram arrays.
2082 */
2083 assert(image != (Image *) NULL);
2084 assert(image->signature == MagickCoreSignature);
2085#if defined(MAGICKCORE_OPENCL_SUPPORT)
2086 if (AccelerateEqualizeImage(image,exception) != MagickFalse)
2087 return(MagickTrue);
2088#endif
2089 if (IsEventLogging() != MagickFalse)
2090 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2091 equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
2092 sizeof(*equalize_map));
2093 histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*
2094 sizeof(*histogram));
2095 map=(double *) AcquireQuantumMemory(MaxMap+1UL,MaxPixelChannels*sizeof(*map));
2096 if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) ||
2097 (map == (double *) NULL))
2098 {
2099 if (map != (double *) NULL)
2100 map=(double *) RelinquishMagickMemory(map);
2101 if (histogram != (double *) NULL)
2102 histogram=(double *) RelinquishMagickMemory(histogram);
2103 if (equalize_map != (double *) NULL)
2104 equalize_map=(double *) RelinquishMagickMemory(equalize_map);
2105 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2106 image->filename);
2107 }
2108 /*
2109 Form histogram.
2110 */
2111 status=MagickTrue;
2112 (void) memset(histogram,0,(MaxMap+1)*GetPixelChannels(image)*
2113 sizeof(*histogram));
2114 image_view=AcquireVirtualCacheView(image,exception);
2115 for (y=0; y < (ssize_t) image->rows; y++)
2116 {
2117 const Quantum
2118 *magick_restrict p;
2119
2120 ssize_t
2121 x;
2122
2123 if (status == MagickFalse)
2124 continue;
2125 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
2126 if (p == (const Quantum *) NULL)
2127 {
2128 status=MagickFalse;
2129 continue;
2130 }
2131 for (x=0; x < (ssize_t) image->columns; x++)
2132 {
2133 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2134 {
2135 double
2136 intensity;
2137
2138 intensity=(double) p[i];
2139 if ((image->channel_mask & SyncChannels) != 0)
2140 intensity=GetPixelIntensity(image,p);
2141 histogram[GetPixelChannels(image)*ScaleQuantumToMap(
2142 ClampToQuantum(intensity))+(size_t) i]++;
2143 }
2144 p+=(ptrdiff_t) GetPixelChannels(image);
2145 }
2146 }
2147 image_view=DestroyCacheView(image_view);
2148 /*
2149 Integrate the histogram to get the equalization map.
2150 */
2151 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2152 {
2153 double
2154 intensity;
2155
2156 ssize_t
2157 j;
2158
2159 intensity=0.0;
2160 for (j=0; j <= (ssize_t) MaxMap; j++)
2161 {
2162 intensity+=histogram[(ssize_t) GetPixelChannels(image)*j+i];
2163 map[(ssize_t) GetPixelChannels(image)*j+i]=intensity;
2164 }
2165 }
2166 (void) memset(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)*
2167 sizeof(*equalize_map));
2168 (void) memset(black,0,sizeof(*black));
2169 (void) memset(white,0,sizeof(*white));
2170 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
2171 {
2172 ssize_t
2173 j;
2174
2175 black[i]=map[i];
2176 white[i]=map[GetPixelChannels(image)*MaxMap+(size_t) i];
2177 if (black[i] != white[i])
2178 for (j=0; j <= (ssize_t) MaxMap; j++)
2179 equalize_map[GetPixelChannels(image)*(size_t) j+(size_t) i]=(double)
2180 ScaleMapToQuantum((double) ((MaxMap*(map[GetPixelChannels(image)*
2181 (size_t) j+(size_t) i]-black[i]))/(white[i]-black[i])));
2182 }
2183 histogram=(double *) RelinquishMagickMemory(histogram);
2184 map=(double *) RelinquishMagickMemory(map);
2185 if (image->storage_class == PseudoClass)
2186 {
2187 ssize_t
2188 j;
2189
2190 /*
2191 Equalize colormap.
2192 */
2193 for (j=0; j < (ssize_t) image->colors; j++)
2194 {
2195 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2196 {
2197 PixelChannel channel = GetPixelChannelChannel(image,
2198 RedPixelChannel);
2199 if (black[channel] != white[channel])
2200 image->colormap[j].red=equalize_map[(ssize_t)
2201 GetPixelChannels(image)*ScaleQuantumToMap(
2202 ClampToQuantum(image->colormap[j].red))+channel];
2203 }
2204 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2205 {
2206 PixelChannel channel = GetPixelChannelChannel(image,
2207 GreenPixelChannel);
2208 if (black[channel] != white[channel])
2209 image->colormap[j].green=equalize_map[(ssize_t)
2210 GetPixelChannels(image)*ScaleQuantumToMap(
2211 ClampToQuantum(image->colormap[j].green))+channel];
2212 }
2213 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2214 {
2215 PixelChannel channel = GetPixelChannelChannel(image,
2216 BluePixelChannel);
2217 if (black[channel] != white[channel])
2218 image->colormap[j].blue=equalize_map[(ssize_t)
2219 GetPixelChannels(image)*ScaleQuantumToMap(
2220 ClampToQuantum(image->colormap[j].blue))+channel];
2221 }
2222 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2223 {
2224 PixelChannel channel = GetPixelChannelChannel(image,
2225 AlphaPixelChannel);
2226 if (black[channel] != white[channel])
2227 image->colormap[j].alpha=equalize_map[(ssize_t)
2228 GetPixelChannels(image)*ScaleQuantumToMap(
2229 ClampToQuantum(image->colormap[j].alpha))+channel];
2230 }
2231 }
2232 }
2233 /*
2234 Equalize image.
2235 */
2236 progress=0;
2237 image_view=AcquireAuthenticCacheView(image,exception);
2238#if defined(MAGICKCORE_OPENMP_SUPPORT)
2239 #pragma omp parallel for schedule(static) shared(progress,status) \
2240 magick_number_threads(image,image,image->rows,1)
2241#endif
2242 for (y=0; y < (ssize_t) image->rows; y++)
2243 {
2244 Quantum
2245 *magick_restrict q;
2246
2247 ssize_t
2248 x;
2249
2250 if (status == MagickFalse)
2251 continue;
2252 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2253 if (q == (Quantum *) NULL)
2254 {
2255 status=MagickFalse;
2256 continue;
2257 }
2258 for (x=0; x < (ssize_t) image->columns; x++)
2259 {
2260 ssize_t
2261 j;
2262
2263 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
2264 {
2265 PixelChannel channel = GetPixelChannelChannel(image,j);
2266 PixelTrait traits = GetPixelChannelTraits(image,channel);
2267 if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j]))
2268 continue;
2269 q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)*
2270 ScaleQuantumToMap(q[j])+(size_t) j]);
2271 }
2272 q+=(ptrdiff_t) GetPixelChannels(image);
2273 }
2274 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2275 status=MagickFalse;
2276 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2277 {
2278 MagickBooleanType
2279 proceed;
2280
2281#if defined(MAGICKCORE_OPENMP_SUPPORT)
2282 #pragma omp atomic
2283#endif
2284 progress++;
2285 proceed=SetImageProgress(image,EqualizeImageTag,progress,image->rows);
2286 if (proceed == MagickFalse)
2287 status=MagickFalse;
2288 }
2289 }
2290 image_view=DestroyCacheView(image_view);
2291 equalize_map=(double *) RelinquishMagickMemory(equalize_map);
2292 return(status);
2293}
2294␌
2295/*
2296%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2297% %
2298% %
2299% %
2300% G a m m a I m a g e %
2301% %
2302% %
2303% %
2304%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2305%
2306% GammaImage() gamma-corrects a particular image channel. The same
2307% image viewed on different devices will have perceptual differences in the
2308% way the image's intensities are represented on the screen. Specify
2309% individual gamma levels for the red, green, and blue channels, or adjust
2310% all three with the gamma parameter. Values typically range from 0.8 to 2.3.
2311%
2312% You can also reduce the influence of a particular channel with a gamma
2313% value of 0.
2314%
2315% The format of the GammaImage method is:
2316%
2317% MagickBooleanType GammaImage(Image *image,const double gamma,
2318% ExceptionInfo *exception)
2319%
2320% A description of each parameter follows:
2321%
2322% o image: the image.
2323%
2324% o level: the image gamma as a string (e.g. 1.6,1.2,1.0).
2325%
2326% o gamma: the image gamma.
2327%
2328*/
2329
2330static inline double gamma_pow(const double value,const double gamma)
2331{
2332 return(value < 0.0 ? value : pow(value,gamma));
2333}
2334
2335MagickExport MagickBooleanType GammaImage(Image *image,const double gamma,
2336 ExceptionInfo *exception)
2337{
2338#define GammaImageTag "Gamma/Image"
2339
2340 CacheView
2341 *image_view;
2342
2343 MagickBooleanType
2344 status;
2345
2346 MagickOffsetType
2347 progress;
2348
2349 Quantum
2350 *gamma_map;
2351
2352 ssize_t
2353 i;
2354
2355 ssize_t
2356 y;
2357
2358 /*
2359 Allocate and initialize gamma maps.
2360 */
2361 assert(image != (Image *) NULL);
2362 assert(image->signature == MagickCoreSignature);
2363 if (IsEventLogging() != MagickFalse)
2364 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2365 if (gamma == 1.0)
2366 return(MagickTrue);
2367 gamma_map=(Quantum *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*gamma_map));
2368 if (gamma_map == (Quantum *) NULL)
2369 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
2370 image->filename);
2371 (void) memset(gamma_map,0,(MaxMap+1)*sizeof(*gamma_map));
2372 if (gamma != 0.0)
2373 for (i=0; i <= (ssize_t) MaxMap; i++)
2374 gamma_map[i]=ScaleMapToQuantum((double) (MaxMap*pow((double) i/
2375 MaxMap,MagickSafeReciprocal(gamma))));
2376 if (image->storage_class == PseudoClass)
2377 for (i=0; i < (ssize_t) image->colors; i++)
2378 {
2379 /*
2380 Gamma-correct colormap.
2381 */
2382 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2383 image->colormap[i].red=(double) gamma_map[ScaleQuantumToMap(
2384 ClampToQuantum(image->colormap[i].red))];
2385 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2386 image->colormap[i].green=(double) gamma_map[ScaleQuantumToMap(
2387 ClampToQuantum(image->colormap[i].green))];
2388 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2389 image->colormap[i].blue=(double) gamma_map[ScaleQuantumToMap(
2390 ClampToQuantum(image->colormap[i].blue))];
2391 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2392 image->colormap[i].alpha=(double) gamma_map[ScaleQuantumToMap(
2393 ClampToQuantum(image->colormap[i].alpha))];
2394 }
2395 /*
2396 Gamma-correct image.
2397 */
2398 status=MagickTrue;
2399 progress=0;
2400 image_view=AcquireAuthenticCacheView(image,exception);
2401#if defined(MAGICKCORE_OPENMP_SUPPORT)
2402 #pragma omp parallel for schedule(static) shared(progress,status) \
2403 magick_number_threads(image,image,image->rows,1)
2404#endif
2405 for (y=0; y < (ssize_t) image->rows; y++)
2406 {
2407 Quantum
2408 *magick_restrict q;
2409
2410 ssize_t
2411 x;
2412
2413 if (status == MagickFalse)
2414 continue;
2415 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2416 if (q == (Quantum *) NULL)
2417 {
2418 status=MagickFalse;
2419 continue;
2420 }
2421 for (x=0; x < (ssize_t) image->columns; x++)
2422 {
2423 ssize_t
2424 j;
2425
2426 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
2427 {
2428 PixelChannel channel = GetPixelChannelChannel(image,j);
2429 PixelTrait traits = GetPixelChannelTraits(image,channel);
2430 if ((traits & UpdatePixelTrait) == 0)
2431 continue;
2432 q[j]=gamma_map[ScaleQuantumToMap(ClampToQuantum((MagickRealType)
2433 q[j]))];
2434 }
2435 q+=(ptrdiff_t) GetPixelChannels(image);
2436 }
2437 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2438 status=MagickFalse;
2439 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2440 {
2441 MagickBooleanType
2442 proceed;
2443
2444#if defined(MAGICKCORE_OPENMP_SUPPORT)
2445 #pragma omp atomic
2446#endif
2447 progress++;
2448 proceed=SetImageProgress(image,GammaImageTag,progress,image->rows);
2449 if (proceed == MagickFalse)
2450 status=MagickFalse;
2451 }
2452 }
2453 image_view=DestroyCacheView(image_view);
2454 gamma_map=(Quantum *) RelinquishMagickMemory(gamma_map);
2455 if (image->gamma != 0.0)
2456 image->gamma*=gamma;
2457 return(status);
2458}
2459␌
2460/*
2461%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2462% %
2463% %
2464% %
2465% G r a y s c a l e I m a g e %
2466% %
2467% %
2468% %
2469%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2470%
2471% GrayscaleImage() converts the image to grayscale.
2472%
2473% The format of the GrayscaleImage method is:
2474%
2475% MagickBooleanType GrayscaleImage(Image *image,
2476% const PixelIntensityMethod method ,ExceptionInfo *exception)
2477%
2478% A description of each parameter follows:
2479%
2480% o image: the image.
2481%
2482% o method: the pixel intensity method.
2483%
2484% o exception: return any errors or warnings in this structure.
2485%
2486*/
2487MagickExport MagickBooleanType GrayscaleImage(Image *image,
2488 const PixelIntensityMethod method,ExceptionInfo *exception)
2489{
2490#define GrayscaleImageTag "Grayscale/Image"
2491
2492 CacheView
2493 *image_view;
2494
2495 MagickBooleanType
2496 status;
2497
2498 MagickOffsetType
2499 progress;
2500
2501 ssize_t
2502 y;
2503
2504 assert(image != (Image *) NULL);
2505 assert(image->signature == MagickCoreSignature);
2506 if (IsEventLogging() != MagickFalse)
2507 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2508 if (image->storage_class == PseudoClass)
2509 {
2510 if (SyncImage(image,exception) == MagickFalse)
2511 return(MagickFalse);
2512 if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2513 return(MagickFalse);
2514 }
2515#if defined(MAGICKCORE_OPENCL_SUPPORT)
2516 if (AccelerateGrayscaleImage(image,method,exception) != MagickFalse)
2517 {
2518 image->intensity=method;
2519 image->type=GrayscaleType;
2520 if ((method == Rec601LuminancePixelIntensityMethod) ||
2521 (method == Rec709LuminancePixelIntensityMethod))
2522 return(SetImageColorspace(image,LinearGRAYColorspace,exception));
2523 return(SetImageColorspace(image,GRAYColorspace,exception));
2524 }
2525#endif
2526 /*
2527 Grayscale image.
2528 */
2529 status=MagickTrue;
2530 progress=0;
2531 image_view=AcquireAuthenticCacheView(image,exception);
2532#if defined(MAGICKCORE_OPENMP_SUPPORT)
2533 #pragma omp parallel for schedule(static) shared(progress,status) \
2534 magick_number_threads(image,image,image->rows,1)
2535#endif
2536 for (y=0; y < (ssize_t) image->rows; y++)
2537 {
2538 Quantum
2539 *magick_restrict q;
2540
2541 ssize_t
2542 x;
2543
2544 if (status == MagickFalse)
2545 continue;
2546 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2547 if (q == (Quantum *) NULL)
2548 {
2549 status=MagickFalse;
2550 continue;
2551 }
2552 for (x=0; x < (ssize_t) image->columns; x++)
2553 {
2554 MagickRealType
2555 blue,
2556 green,
2557 red,
2558 intensity;
2559
2560 red=(MagickRealType) GetPixelRed(image,q);
2561 green=(MagickRealType) GetPixelGreen(image,q);
2562 blue=(MagickRealType) GetPixelBlue(image,q);
2563 intensity=0.0;
2564 switch (method)
2565 {
2566 case AveragePixelIntensityMethod:
2567 {
2568 intensity=(red+green+blue)/3.0;
2569 break;
2570 }
2571 case BrightnessPixelIntensityMethod:
2572 {
2573 intensity=MagickMax(MagickMax(red,green),blue);
2574 break;
2575 }
2576 case LightnessPixelIntensityMethod:
2577 {
2578 intensity=(MagickMin(MagickMin(red,green),blue)+
2579 MagickMax(MagickMax(red,green),blue))/2.0;
2580 break;
2581 }
2582 case MSPixelIntensityMethod:
2583 {
2584 intensity=(MagickRealType) (((double) red*red+green*green+
2585 blue*blue)/3.0);
2586 break;
2587 }
2588 case Rec601LumaPixelIntensityMethod:
2589 {
2590 if (image->colorspace == RGBColorspace)
2591 {
2592 red=EncodePixelGamma(red);
2593 green=EncodePixelGamma(green);
2594 blue=EncodePixelGamma(blue);
2595 }
2596 if ((red == green) && (green == blue))
2597 intensity=red;
2598 else
2599 intensity=0.298839*red+0.586811*green+0.114350*blue;
2600 break;
2601 }
2602 case Rec601LuminancePixelIntensityMethod:
2603 {
2604 if (image->colorspace == sRGBColorspace)
2605 {
2606 red=DecodePixelGamma(red);
2607 green=DecodePixelGamma(green);
2608 blue=DecodePixelGamma(blue);
2609 }
2610 if ((red == green) && (green == blue))
2611 intensity=red;
2612 else
2613 intensity=0.298839*red+0.586811*green+0.114350*blue;
2614 break;
2615 }
2616 case Rec709LumaPixelIntensityMethod:
2617 default:
2618 {
2619 if (image->colorspace == RGBColorspace)
2620 {
2621 red=EncodePixelGamma(red);
2622 green=EncodePixelGamma(green);
2623 blue=EncodePixelGamma(blue);
2624 }
2625 if ((red == green) && (green == blue))
2626 intensity=red;
2627 else
2628 intensity=0.212656*red+0.715158*green+0.072186*blue;
2629 break;
2630 }
2631 case Rec709LuminancePixelIntensityMethod:
2632 {
2633 if (image->colorspace == sRGBColorspace)
2634 {
2635 red=DecodePixelGamma(red);
2636 green=DecodePixelGamma(green);
2637 blue=DecodePixelGamma(blue);
2638 }
2639 if ((red == green) && (green == blue))
2640 intensity=red;
2641 else
2642 intensity=0.212656*red+0.715158*green+0.072186*blue;
2643 break;
2644 }
2645 case RMSPixelIntensityMethod:
2646 {
2647 intensity=(MagickRealType) (sqrt((double) red*red+green*green+
2648 blue*blue)/sqrt(3.0));
2649 break;
2650 }
2651 }
2652 SetPixelGray(image,ClampToQuantum(intensity),q);
2653 q+=(ptrdiff_t) GetPixelChannels(image);
2654 }
2655 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2656 status=MagickFalse;
2657 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2658 {
2659 MagickBooleanType
2660 proceed;
2661
2662#if defined(MAGICKCORE_OPENMP_SUPPORT)
2663 #pragma omp atomic
2664#endif
2665 progress++;
2666 proceed=SetImageProgress(image,GrayscaleImageTag,progress,image->rows);
2667 if (proceed == MagickFalse)
2668 status=MagickFalse;
2669 }
2670 }
2671 image_view=DestroyCacheView(image_view);
2672 image->intensity=method;
2673 image->type=GrayscaleType;
2674 if ((method == Rec601LuminancePixelIntensityMethod) ||
2675 (method == Rec709LuminancePixelIntensityMethod))
2676 return(SetImageColorspace(image,LinearGRAYColorspace,exception));
2677 return(SetImageColorspace(image,GRAYColorspace,exception));
2678}
2679␌
2680/*
2681%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2682% %
2683% %
2684% %
2685% H a l d C l u t I m a g e %
2686% %
2687% %
2688% %
2689%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2690%
2691% HaldClutImage() applies a Hald color lookup table to the image. A Hald
2692% color lookup table is a 3-dimensional color cube mapped to 2 dimensions.
2693% Create it with the HALD coder. You can apply any color transformation to
2694% the Hald image and then use this method to apply the transform to the
2695% image.
2696%
2697% The format of the HaldClutImage method is:
2698%
2699% MagickBooleanType HaldClutImage(Image *image,Image *hald_image,
2700% ExceptionInfo *exception)
2701%
2702% A description of each parameter follows:
2703%
2704% o image: the image, which is replaced by indexed CLUT values
2705%
2706% o hald_image: the color lookup table image for replacement color values.
2707%
2708% o exception: return any errors or warnings in this structure.
2709%
2710*/
2711MagickExport MagickBooleanType HaldClutImage(Image *image,
2712 const Image *hald_image,ExceptionInfo *exception)
2713{
2714#define HaldClutImageTag "Clut/Image"
2715
2716 typedef struct _HaldInfo
2717 {
2718 double
2719 x,
2720 y,
2721 z;
2722 } HaldInfo;
2723
2724 CacheView
2725 *hald_view,
2726 *image_view;
2727
2728 double
2729 width;
2730
2731 MagickBooleanType
2732 status;
2733
2734 MagickOffsetType
2735 progress;
2736
2737 PixelInfo
2738 zero;
2739
2740 size_t
2741 cube_size,
2742 length,
2743 level;
2744
2745 ssize_t
2746 y;
2747
2748 assert(image != (Image *) NULL);
2749 assert(image->signature == MagickCoreSignature);
2750 if (IsEventLogging() != MagickFalse)
2751 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2752 assert(hald_image != (Image *) NULL);
2753 assert(hald_image->signature == MagickCoreSignature);
2754 if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
2755 return(MagickFalse);
2756 if ((image->alpha_trait & BlendPixelTrait) == 0)
2757 (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
2758 if (image->colorspace != hald_image->colorspace)
2759 (void) SetImageColorspace(image,hald_image->colorspace,exception);
2760 /*
2761 Hald clut image.
2762 */
2763 status=MagickTrue;
2764 progress=0;
2765 length=(size_t) MagickMin((MagickRealType) hald_image->columns,
2766 (MagickRealType) hald_image->rows);
2767 for (level=2; (level*level*level) < length; level++) ;
2768 level*=level;
2769 cube_size=level*level;
2770 width=(double) hald_image->columns;
2771 GetPixelInfo(hald_image,&zero);
2772 hald_view=AcquireVirtualCacheView(hald_image,exception);
2773 image_view=AcquireAuthenticCacheView(image,exception);
2774#if defined(MAGICKCORE_OPENMP_SUPPORT)
2775 #pragma omp parallel for schedule(static) shared(progress,status) \
2776 magick_number_threads(image,image,image->rows,1)
2777#endif
2778 for (y=0; y < (ssize_t) image->rows; y++)
2779 {
2780 Quantum
2781 *magick_restrict q;
2782
2783 ssize_t
2784 x;
2785
2786 if (status == MagickFalse)
2787 continue;
2788 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
2789 if (q == (Quantum *) NULL)
2790 {
2791 status=MagickFalse;
2792 continue;
2793 }
2794 for (x=0; x < (ssize_t) image->columns; x++)
2795 {
2796 double
2797 area = 0.0,
2798 offset = 0.0;
2799
2800 HaldInfo
2801 point = { 0, 0, 0 };
2802
2803 PixelInfo
2804 pixel = zero,
2805 pixel1 = zero,
2806 pixel2 = zero,
2807 pixel3 = zero,
2808 pixel4 = zero;
2809
2810 point.x=QuantumScale*(level-1.0)*(double) GetPixelRed(image,q);
2811 point.y=QuantumScale*(level-1.0)*(double) GetPixelGreen(image,q);
2812 point.z=QuantumScale*(level-1.0)*(double) GetPixelBlue(image,q);
2813 offset=point.x+level*floor(point.y)+cube_size*floor(point.z);
2814 point.x-=floor(point.x);
2815 point.y-=floor(point.y);
2816 point.z-=floor(point.z);
2817 status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
2818 fmod(offset,width),floor(offset/width),&pixel1,exception);
2819 if (status == MagickFalse)
2820 break;
2821 status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
2822 fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
2823 if (status == MagickFalse)
2824 break;
2825 area=point.y;
2826 if (hald_image->interpolate == NearestInterpolatePixel)
2827 area=(point.y < 0.5) ? 0.0 : 1.0;
2828 CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
2829 area,&pixel3);
2830 offset+=cube_size;
2831 status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
2832 fmod(offset,width),floor(offset/width),&pixel1,exception);
2833 if (status == MagickFalse)
2834 break;
2835 status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate,
2836 fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception);
2837 if (status == MagickFalse)
2838 break;
2839 CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha,
2840 area,&pixel4);
2841 area=point.z;
2842 if (hald_image->interpolate == NearestInterpolatePixel)
2843 area=(point.z < 0.5)? 0.0 : 1.0;
2844 CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha,
2845 area,&pixel);
2846 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2847 SetPixelRed(image,ClampToQuantum(pixel.red),q);
2848 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2849 SetPixelGreen(image,ClampToQuantum(pixel.green),q);
2850 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2851 SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
2852 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2853 (image->colorspace == CMYKColorspace))
2854 SetPixelBlack(image,ClampToQuantum(pixel.black),q);
2855 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2856 (image->alpha_trait != UndefinedPixelTrait))
2857 SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
2858 q+=(ptrdiff_t) GetPixelChannels(image);
2859 }
2860 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
2861 status=MagickFalse;
2862 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2863 {
2864 MagickBooleanType
2865 proceed;
2866
2867#if defined(MAGICKCORE_OPENMP_SUPPORT)
2868 #pragma omp atomic
2869#endif
2870 progress++;
2871 proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows);
2872 if (proceed == MagickFalse)
2873 status=MagickFalse;
2874 }
2875 }
2876 hald_view=DestroyCacheView(hald_view);
2877 image_view=DestroyCacheView(image_view);
2878 return(status);
2879}
2880␌
2881/*
2882%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2883% %
2884% %
2885% %
2886% L e v e l I m a g e %
2887% %
2888% %
2889% %
2890%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2891%
2892% LevelImage() adjusts the levels of a particular image channel by
2893% scaling the colors falling between specified white and black points to
2894% the full available quantum range.
2895%
2896% The parameters provided represent the black, and white points. The black
2897% point specifies the darkest color in the image. Colors darker than the
2898% black point are set to zero. White point specifies the lightest color in
2899% the image. Colors brighter than the white point are set to the maximum
2900% quantum value.
2901%
2902% If a '!' flag is given, map black and white colors to the given levels
2903% rather than mapping those levels to black and white. See
2904% LevelizeImage() below.
2905%
2906% Gamma specifies a gamma correction to apply to the image.
2907%
2908% The format of the LevelImage method is:
2909%
2910% MagickBooleanType LevelImage(Image *image,const double black_point,
2911% const double white_point,const double gamma,ExceptionInfo *exception)
2912%
2913% A description of each parameter follows:
2914%
2915% o image: the image.
2916%
2917% o black_point: The level to map zero (black) to.
2918%
2919% o white_point: The level to map QuantumRange (white) to.
2920%
2921% o exception: return any errors or warnings in this structure.
2922%
2923*/
2924
2925static inline double LevelPixel(const double black_point,
2926 const double white_point,const double gamma,const double pixel)
2927{
2928 double
2929 level_pixel,
2930 scale;
2931
2932 scale=MagickSafeReciprocal(white_point-black_point);
2933 level_pixel=(double) QuantumRange*gamma_pow(scale*((double) pixel-(double)
2934 black_point),MagickSafeReciprocal(gamma));
2935 return(level_pixel);
2936}
2937
2938MagickExport MagickBooleanType LevelImage(Image *image,const double black_point,
2939 const double white_point,const double gamma,ExceptionInfo *exception)
2940{
2941#define LevelImageTag "Level/Image"
2942
2943 CacheView
2944 *image_view;
2945
2946 MagickBooleanType
2947 status;
2948
2949 MagickOffsetType
2950 progress;
2951
2952 ssize_t
2953 i,
2954 y;
2955
2956 /*
2957 Allocate and initialize levels map.
2958 */
2959 assert(image != (Image *) NULL);
2960 assert(image->signature == MagickCoreSignature);
2961 if (IsEventLogging() != MagickFalse)
2962 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
2963 if (image->storage_class == PseudoClass)
2964 for (i=0; i < (ssize_t) image->colors; i++)
2965 {
2966 /*
2967 Level colormap.
2968 */
2969 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2970 image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point,
2971 white_point,gamma,image->colormap[i].red));
2972 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2973 image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point,
2974 white_point,gamma,image->colormap[i].green));
2975 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2976 image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point,
2977 white_point,gamma,image->colormap[i].blue));
2978 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
2979 image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point,
2980 white_point,gamma,image->colormap[i].alpha));
2981 }
2982 /*
2983 Level image.
2984 */
2985 status=MagickTrue;
2986 progress=0;
2987 image_view=AcquireAuthenticCacheView(image,exception);
2988#if defined(MAGICKCORE_OPENMP_SUPPORT)
2989 #pragma omp parallel for schedule(static) shared(progress,status) \
2990 magick_number_threads(image,image,image->rows,1)
2991#endif
2992 for (y=0; y < (ssize_t) image->rows; y++)
2993 {
2994 Quantum
2995 *magick_restrict q;
2996
2997 ssize_t
2998 x;
2999
3000 if (status == MagickFalse)
3001 continue;
3002 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3003 if (q == (Quantum *) NULL)
3004 {
3005 status=MagickFalse;
3006 continue;
3007 }
3008 for (x=0; x < (ssize_t) image->columns; x++)
3009 {
3010 ssize_t
3011 j;
3012
3013 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
3014 {
3015 PixelChannel channel = GetPixelChannelChannel(image,j);
3016 PixelTrait traits = GetPixelChannelTraits(image,channel);
3017 if ((traits & UpdatePixelTrait) == 0)
3018 continue;
3019 q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma,
3020 (double) q[j]));
3021 }
3022 q+=(ptrdiff_t) GetPixelChannels(image);
3023 }
3024 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3025 status=MagickFalse;
3026 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3027 {
3028 MagickBooleanType
3029 proceed;
3030
3031#if defined(MAGICKCORE_OPENMP_SUPPORT)
3032 #pragma omp atomic
3033#endif
3034 progress++;
3035 proceed=SetImageProgress(image,LevelImageTag,progress,image->rows);
3036 if (proceed == MagickFalse)
3037 status=MagickFalse;
3038 }
3039 }
3040 image_view=DestroyCacheView(image_view);
3041 (void) ClampImage(image,exception);
3042 return(status);
3043}
3044␌
3045/*
3046%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3047% %
3048% %
3049% %
3050% L e v e l i z e I m a g e %
3051% %
3052% %
3053% %
3054%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3055%
3056% LevelizeImage() applies the reversed LevelImage() operation to just
3057% the specific channels specified. It compresses the full range of color
3058% values, so that they lie between the given black and white points. Gamma is
3059% applied before the values are mapped.
3060%
3061% LevelizeImage() can be called with by using a +level command line
3062% API option, or using a '!' on a -level or LevelImage() geometry string.
3063%
3064% It can be used to de-contrast a greyscale image to the exact levels
3065% specified. Or by using specific levels for each channel of an image you
3066% can convert a gray-scale image to any linear color gradient, according to
3067% those levels.
3068%
3069% The format of the LevelizeImage method is:
3070%
3071% MagickBooleanType LevelizeImage(Image *image,const double black_point,
3072% const double white_point,const double gamma,ExceptionInfo *exception)
3073%
3074% A description of each parameter follows:
3075%
3076% o image: the image.
3077%
3078% o black_point: The level to map zero (black) to.
3079%
3080% o white_point: The level to map QuantumRange (white) to.
3081%
3082% o gamma: adjust gamma by this factor before mapping values.
3083%
3084% o exception: return any errors or warnings in this structure.
3085%
3086*/
3087MagickExport MagickBooleanType LevelizeImage(Image *image,
3088 const double black_point,const double white_point,const double gamma,
3089 ExceptionInfo *exception)
3090{
3091#define LevelizeImageTag "Levelize/Image"
3092#define LevelizeValue(x) ClampToQuantum(((MagickRealType) gamma_pow((double) \
3093 (QuantumScale*((double) x)),gamma))*(white_point-black_point)+black_point)
3094
3095 CacheView
3096 *image_view;
3097
3098 MagickBooleanType
3099 status;
3100
3101 MagickOffsetType
3102 progress;
3103
3104 ssize_t
3105 i;
3106
3107 ssize_t
3108 y;
3109
3110 /*
3111 Allocate and initialize levels map.
3112 */
3113 assert(image != (Image *) NULL);
3114 assert(image->signature == MagickCoreSignature);
3115 if (IsEventLogging() != MagickFalse)
3116 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3117 if (image->storage_class == PseudoClass)
3118 for (i=0; i < (ssize_t) image->colors; i++)
3119 {
3120 /*
3121 Level colormap.
3122 */
3123 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3124 image->colormap[i].red=(double) LevelizeValue(image->colormap[i].red);
3125 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3126 image->colormap[i].green=(double) LevelizeValue(
3127 image->colormap[i].green);
3128 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3129 image->colormap[i].blue=(double) LevelizeValue(image->colormap[i].blue);
3130 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
3131 image->colormap[i].alpha=(double) LevelizeValue(
3132 image->colormap[i].alpha);
3133 }
3134 /*
3135 Level image.
3136 */
3137 status=MagickTrue;
3138 progress=0;
3139 image_view=AcquireAuthenticCacheView(image,exception);
3140#if defined(MAGICKCORE_OPENMP_SUPPORT)
3141 #pragma omp parallel for schedule(static) shared(progress,status) \
3142 magick_number_threads(image,image,image->rows,1)
3143#endif
3144 for (y=0; y < (ssize_t) image->rows; y++)
3145 {
3146 Quantum
3147 *magick_restrict q;
3148
3149 ssize_t
3150 x;
3151
3152 if (status == MagickFalse)
3153 continue;
3154 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3155 if (q == (Quantum *) NULL)
3156 {
3157 status=MagickFalse;
3158 continue;
3159 }
3160 for (x=0; x < (ssize_t) image->columns; x++)
3161 {
3162 ssize_t
3163 j;
3164
3165 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
3166 {
3167 PixelChannel channel = GetPixelChannelChannel(image,j);
3168 PixelTrait traits = GetPixelChannelTraits(image,channel);
3169 if ((traits & UpdatePixelTrait) == 0)
3170 continue;
3171 q[j]=LevelizeValue(q[j]);
3172 }
3173 q+=(ptrdiff_t) GetPixelChannels(image);
3174 }
3175 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3176 status=MagickFalse;
3177 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3178 {
3179 MagickBooleanType
3180 proceed;
3181
3182#if defined(MAGICKCORE_OPENMP_SUPPORT)
3183 #pragma omp atomic
3184#endif
3185 progress++;
3186 proceed=SetImageProgress(image,LevelizeImageTag,progress,image->rows);
3187 if (proceed == MagickFalse)
3188 status=MagickFalse;
3189 }
3190 }
3191 image_view=DestroyCacheView(image_view);
3192 return(status);
3193}
3194␌
3195/*
3196%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3197% %
3198% %
3199% %
3200% L e v e l I m a g e C o l o r s %
3201% %
3202% %
3203% %
3204%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3205%
3206% LevelImageColors() maps the given color to "black" and "white" values,
3207% linearly spreading out the colors, and level values on a channel by channel
3208% bases, as per LevelImage(). The given colors allows you to specify
3209% different level ranges for each of the color channels separately.
3210%
3211% If the boolean 'invert' is set true the image values will modified in the
3212% reverse direction. That is any existing "black" and "white" colors in the
3213% image will become the color values given, with all other values compressed
3214% appropriately. This effectively maps a greyscale gradient into the given
3215% color gradient.
3216%
3217% The format of the LevelImageColors method is:
3218%
3219% MagickBooleanType LevelImageColors(Image *image,
3220% const PixelInfo *black_color,const PixelInfo *white_color,
3221% const MagickBooleanType invert,ExceptionInfo *exception)
3222%
3223% A description of each parameter follows:
3224%
3225% o image: the image.
3226%
3227% o black_color: The color to map black to/from
3228%
3229% o white_point: The color to map white to/from
3230%
3231% o invert: if true map the colors (levelize), rather than from (level)
3232%
3233% o exception: return any errors or warnings in this structure.
3234%
3235*/
3236MagickExport MagickBooleanType LevelImageColors(Image *image,
3237 const PixelInfo *black_color,const PixelInfo *white_color,
3238 const MagickBooleanType invert,ExceptionInfo *exception)
3239{
3240 ChannelType
3241 channel_mask;
3242
3243 MagickStatusType
3244 status;
3245
3246 PixelInfo
3247 black,
3248 white;
3249
3250 /*
3251 Allocate and initialize levels map.
3252 */
3253 assert(image != (Image *) NULL);
3254 assert(image->signature == MagickCoreSignature);
3255 if (IsEventLogging() != MagickFalse)
3256 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3257 if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
3258 ((IsGrayColorspace(black_color->colorspace) == MagickFalse) ||
3259 (IsGrayColorspace(white_color->colorspace) == MagickFalse)))
3260 (void) SetImageColorspace(image,sRGBColorspace,exception);
3261 black=(*black_color);
3262 ConformPixelInfoColorspace(image,&black,exception);
3263 black_color=(&black);
3264 white=(*white_color);
3265 ConformPixelInfoColorspace(image,&white,exception);
3266 white_color=(&white);
3267 status=MagickTrue;
3268 if (invert == MagickFalse)
3269 {
3270 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3271 {
3272 channel_mask=SetImageChannelMask(image,RedChannel);
3273 status&=(MagickStatusType) LevelImage(image,black_color->red,
3274 white_color->red,1.0,exception);
3275 (void) SetImageChannelMask(image,channel_mask);
3276 }
3277 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3278 {
3279 channel_mask=SetImageChannelMask(image,GreenChannel);
3280 status&=(MagickStatusType) LevelImage(image,black_color->green,
3281 white_color->green,1.0,exception);
3282 (void) SetImageChannelMask(image,channel_mask);
3283 }
3284 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3285 {
3286 channel_mask=SetImageChannelMask(image,BlueChannel);
3287 status&=(MagickStatusType) LevelImage(image,black_color->blue,
3288 white_color->blue,1.0,exception);
3289 (void) SetImageChannelMask(image,channel_mask);
3290 }
3291 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3292 (image->colorspace == CMYKColorspace))
3293 {
3294 channel_mask=SetImageChannelMask(image,BlackChannel);
3295 status&=(MagickStatusType) LevelImage(image,black_color->black,
3296 white_color->black,1.0,exception);
3297 (void) SetImageChannelMask(image,channel_mask);
3298 }
3299 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
3300 (image->alpha_trait != UndefinedPixelTrait))
3301 {
3302 channel_mask=SetImageChannelMask(image,AlphaChannel);
3303 status&=(MagickStatusType) LevelImage(image,black_color->alpha,
3304 white_color->alpha,1.0,exception);
3305 (void) SetImageChannelMask(image,channel_mask);
3306 }
3307 }
3308 else
3309 {
3310 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3311 {
3312 channel_mask=SetImageChannelMask(image,RedChannel);
3313 status&=(MagickStatusType) LevelizeImage(image,black_color->red,
3314 white_color->red,1.0,exception);
3315 (void) SetImageChannelMask(image,channel_mask);
3316 }
3317 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3318 {
3319 channel_mask=SetImageChannelMask(image,GreenChannel);
3320 status&=(MagickStatusType) LevelizeImage(image,black_color->green,
3321 white_color->green,1.0,exception);
3322 (void) SetImageChannelMask(image,channel_mask);
3323 }
3324 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3325 {
3326 channel_mask=SetImageChannelMask(image,BlueChannel);
3327 status&=(MagickStatusType) LevelizeImage(image,black_color->blue,
3328 white_color->blue,1.0,exception);
3329 (void) SetImageChannelMask(image,channel_mask);
3330 }
3331 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3332 (image->colorspace == CMYKColorspace))
3333 {
3334 channel_mask=SetImageChannelMask(image,BlackChannel);
3335 status&=(MagickStatusType) LevelizeImage(image,black_color->black,
3336 white_color->black,1.0,exception);
3337 (void) SetImageChannelMask(image,channel_mask);
3338 }
3339 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
3340 (image->alpha_trait != UndefinedPixelTrait))
3341 {
3342 channel_mask=SetImageChannelMask(image,AlphaChannel);
3343 status&=(MagickStatusType) LevelizeImage(image,black_color->alpha,
3344 white_color->alpha,1.0,exception);
3345 (void) SetImageChannelMask(image,channel_mask);
3346 }
3347 }
3348 return(status != 0 ? MagickTrue : MagickFalse);
3349}
3350␌
3351/*
3352%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3353% %
3354% %
3355% %
3356% L i n e a r S t r e t c h I m a g e %
3357% %
3358% %
3359% %
3360%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3361%
3362% LinearStretchImage() discards any pixels below the black point and above
3363% the white point and levels the remaining pixels.
3364%
3365% The format of the LinearStretchImage method is:
3366%
3367% MagickBooleanType LinearStretchImage(Image *image,
3368% const double black_point,const double white_point,
3369% ExceptionInfo *exception)
3370%
3371% A description of each parameter follows:
3372%
3373% o image: the image.
3374%
3375% o black_point: the black point.
3376%
3377% o white_point: the white point.
3378%
3379% o exception: return any errors or warnings in this structure.
3380%
3381*/
3382MagickExport MagickBooleanType LinearStretchImage(Image *image,
3383 const double black_point,const double white_point,ExceptionInfo *exception)
3384{
3385#define LinearStretchImageTag "LinearStretch/Image"
3386
3387 CacheView
3388 *image_view;
3389
3390 char
3391 property[MagickPathExtent];
3392
3393 double
3394 *histogram,
3395 intensity;
3396
3397 MagickBooleanType
3398 status;
3399
3400 ssize_t
3401 black,
3402 white,
3403 y;
3404
3405 /*
3406 Allocate histogram and linear map.
3407 */
3408 assert(image != (Image *) NULL);
3409 assert(image->signature == MagickCoreSignature);
3410 histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*histogram));
3411 if (histogram == (double *) NULL)
3412 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
3413 image->filename);
3414 /*
3415 Form histogram.
3416 */
3417 (void) memset(histogram,0,(MaxMap+1)*sizeof(*histogram));
3418 image_view=AcquireVirtualCacheView(image,exception);
3419 for (y=0; y < (ssize_t) image->rows; y++)
3420 {
3421 const Quantum
3422 *magick_restrict p;
3423
3424 ssize_t
3425 x;
3426
3427 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
3428 if (p == (const Quantum *) NULL)
3429 break;
3430 for (x=0; x < (ssize_t) image->columns; x++)
3431 {
3432 intensity=GetPixelIntensity(image,p);
3433 histogram[ScaleQuantumToMap(ClampToQuantum(intensity))]++;
3434 p+=(ptrdiff_t) GetPixelChannels(image);
3435 }
3436 }
3437 image_view=DestroyCacheView(image_view);
3438 /*
3439 Find the histogram boundaries by locating the black and white point levels.
3440 */
3441 intensity=0.0;
3442 for (black=0; black < (ssize_t) MaxMap; black++)
3443 {
3444 intensity+=histogram[black];
3445 if (intensity >= black_point)
3446 break;
3447 }
3448 intensity=0.0;
3449 for (white=(ssize_t) MaxMap; white != 0; white--)
3450 {
3451 intensity+=histogram[white];
3452 if (intensity >= white_point)
3453 break;
3454 }
3455 histogram=(double *) RelinquishMagickMemory(histogram);
3456 status=LevelImage(image,(double) ScaleMapToQuantum((MagickRealType) black),
3457 (double) ScaleMapToQuantum((MagickRealType) white),1.0,exception);
3458 (void) FormatLocaleString(property,MagickPathExtent,"%gx%g%%",100.0*black/
3459 MaxMap,100.0*white/MaxMap);
3460 (void) SetImageProperty(image,"histogram:linear-stretch",property,exception);
3461 return(status);
3462}
3463␌
3464/*
3465%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3466% %
3467% %
3468% %
3469% M o d u l a t e I m a g e %
3470% %
3471% %
3472% %
3473%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3474%
3475% ModulateImage() lets you control the brightness, saturation, and hue
3476% of an image. Modulate represents the brightness, saturation, and hue
3477% as one parameter (e.g. 90,150,100). If the image colorspace is HSL, the
3478% modulation is lightness, saturation, and hue. For HWB, use blackness,
3479% whiteness, and hue. And for HCL, use chrome, luma, and hue.
3480%
3481% The format of the ModulateImage method is:
3482%
3483% MagickBooleanType ModulateImage(Image *image,const char *modulate,
3484% ExceptionInfo *exception)
3485%
3486% A description of each parameter follows:
3487%
3488% o image: the image.
3489%
3490% o modulate: Define the percent change in brightness, saturation, and hue.
3491%
3492% o exception: return any errors or warnings in this structure.
3493%
3494*/
3495
3496static inline void ModulateHCL(const double percent_hue,
3497 const double percent_chroma,const double percent_luma,double *red,
3498 double *green,double *blue)
3499{
3500 double
3501 hue,
3502 luma,
3503 chroma;
3504
3505 /*
3506 Increase or decrease color luma, chroma, or hue.
3507 */
3508 ConvertRGBToHCL(*red,*green,*blue,&hue,&chroma,&luma);
3509 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3510 chroma*=0.01*percent_chroma;
3511 luma*=0.01*percent_luma;
3512 ConvertHCLToRGB(hue,chroma,luma,red,green,blue);
3513}
3514
3515static inline void ModulateHCLp(const double percent_hue,
3516 const double percent_chroma,const double percent_luma,double *red,
3517 double *green,double *blue)
3518{
3519 double
3520 hue,
3521 luma,
3522 chroma;
3523
3524 /*
3525 Increase or decrease color luma, chroma, or hue.
3526 */
3527 ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma);
3528 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3529 chroma*=0.01*percent_chroma;
3530 luma*=0.01*percent_luma;
3531 ConvertHCLpToRGB(hue,chroma,luma,red,green,blue);
3532}
3533
3534static inline void ModulateHSB(const double percent_hue,
3535 const double percent_saturation,const double percent_brightness,double *red,
3536 double *green,double *blue)
3537{
3538 double
3539 brightness,
3540 hue,
3541 saturation;
3542
3543 /*
3544 Increase or decrease color brightness, saturation, or hue.
3545 */
3546 ConvertRGBToHSB(*red,*green,*blue,&hue,&saturation,&brightness);
3547 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3548 saturation*=0.01*percent_saturation;
3549 brightness*=0.01*percent_brightness;
3550 ConvertHSBToRGB(hue,saturation,brightness,red,green,blue);
3551}
3552
3553static inline void ModulateHSI(const double percent_hue,
3554 const double percent_saturation,const double percent_intensity,double *red,
3555 double *green,double *blue)
3556{
3557 double
3558 intensity,
3559 hue,
3560 saturation;
3561
3562 /*
3563 Increase or decrease color intensity, saturation, or hue.
3564 */
3565 ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity);
3566 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3567 saturation*=0.01*percent_saturation;
3568 intensity*=0.01*percent_intensity;
3569 ConvertHSIToRGB(hue,saturation,intensity,red,green,blue);
3570}
3571
3572static inline void ModulateHSL(const double percent_hue,
3573 const double percent_saturation,const double percent_lightness,double *red,
3574 double *green,double *blue)
3575{
3576 double
3577 hue,
3578 lightness,
3579 saturation;
3580
3581 /*
3582 Increase or decrease color lightness, saturation, or hue.
3583 */
3584 ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness);
3585 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3586 saturation*=0.01*percent_saturation;
3587 lightness*=0.01*percent_lightness;
3588 ConvertHSLToRGB(hue,saturation,lightness,red,green,blue);
3589}
3590
3591static inline void ModulateHSV(const double percent_hue,
3592 const double percent_saturation,const double percent_value,double *red,
3593 double *green,double *blue)
3594{
3595 double
3596 hue,
3597 saturation,
3598 value;
3599
3600 /*
3601 Increase or decrease color value, saturation, or hue.
3602 */
3603 ConvertRGBToHSV(*red,*green,*blue,&hue,&saturation,&value);
3604 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3605 saturation*=0.01*percent_saturation;
3606 value*=0.01*percent_value;
3607 ConvertHSVToRGB(hue,saturation,value,red,green,blue);
3608}
3609
3610static inline void ModulateHWB(const double percent_hue,
3611 const double percent_whiteness,const double percent_blackness,double *red,
3612 double *green,double *blue)
3613{
3614 double
3615 blackness,
3616 hue,
3617 whiteness;
3618
3619 /*
3620 Increase or decrease color blackness, whiteness, or hue.
3621 */
3622 ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness);
3623 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3624 blackness*=0.01*percent_blackness;
3625 whiteness*=0.01*percent_whiteness;
3626 ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue);
3627}
3628
3629static inline void ModulateLCHab(const double percent_luma,
3630 const double percent_chroma,const double percent_hue,
3631 const IlluminantType illuminant,double *red,double *green,double *blue)
3632{
3633 double
3634 hue,
3635 luma,
3636 chroma;
3637
3638 /*
3639 Increase or decrease color luma, chroma, or hue.
3640 */
3641 ConvertRGBToLCHab(*red,*green,*blue,illuminant,&luma,&chroma,&hue);
3642 luma*=0.01*percent_luma;
3643 chroma*=0.01*percent_chroma;
3644 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3645 ConvertLCHabToRGB(luma,chroma,hue,illuminant,red,green,blue);
3646}
3647
3648static inline void ModulateLCHuv(const double percent_luma,
3649 const double percent_chroma,const double percent_hue,
3650 const IlluminantType illuminant,double *red,double *green,double *blue)
3651{
3652 double
3653 hue,
3654 luma,
3655 chroma;
3656
3657 /*
3658 Increase or decrease color luma, chroma, or hue.
3659 */
3660 ConvertRGBToLCHuv(*red,*green,*blue,illuminant,&luma,&chroma,&hue);
3661 luma*=0.01*percent_luma;
3662 chroma*=0.01*percent_chroma;
3663 hue+=fmod((percent_hue-100.0),200.0)/200.0;
3664 ConvertLCHuvToRGB(luma,chroma,hue,illuminant,red,green,blue);
3665}
3666
3667MagickExport MagickBooleanType ModulateImage(Image *image,const char *modulate,
3668 ExceptionInfo *exception)
3669{
3670#define ModulateImageTag "Modulate/Image"
3671
3672 CacheView
3673 *image_view;
3674
3675 ColorspaceType
3676 colorspace = UndefinedColorspace;
3677
3678 const char
3679 *artifact;
3680
3681 double
3682 percent_brightness = 100.0,
3683 percent_hue = 100.0,
3684 percent_saturation = 100.0;
3685
3686 GeometryInfo
3687 geometry_info;
3688
3689 IlluminantType
3690 illuminant = D65Illuminant;
3691
3692 MagickBooleanType
3693 status;
3694
3695 MagickOffsetType
3696 progress;
3697
3698 MagickStatusType
3699 flags;
3700
3701 ssize_t
3702 i;
3703
3704 ssize_t
3705 y;
3706
3707 /*
3708 Initialize modulate table.
3709 */
3710 assert(image != (Image *) NULL);
3711 assert(image->signature == MagickCoreSignature);
3712 if (IsEventLogging() != MagickFalse)
3713 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3714 if (modulate == (char *) NULL)
3715 return(MagickFalse);
3716 if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
3717 (void) SetImageColorspace(image,sRGBColorspace,exception);
3718 flags=ParseGeometry(modulate,&geometry_info);
3719 if ((flags & RhoValue) != 0)
3720 percent_brightness=geometry_info.rho;
3721 if ((flags & SigmaValue) != 0)
3722 percent_saturation=geometry_info.sigma;
3723 if ((flags & XiValue) != 0)
3724 percent_hue=geometry_info.xi;
3725 artifact=GetImageArtifact(image,"modulate:colorspace");
3726 if (artifact != (const char *) NULL)
3727 colorspace=(ColorspaceType) ParseCommandOption(MagickColorspaceOptions,
3728 MagickFalse,artifact);
3729 artifact=GetImageArtifact(image,"color:illuminant");
3730 if (artifact != (const char *) NULL)
3731 {
3732 ssize_t
3733 illuminant_type;
3734
3735 illuminant_type=ParseCommandOption(MagickIlluminantOptions,MagickFalse,
3736 artifact);
3737 if (illuminant_type < 0)
3738 {
3739 illuminant=UndefinedIlluminant;
3740 colorspace=UndefinedColorspace;
3741 }
3742 else
3743 illuminant=(IlluminantType) illuminant_type;
3744 }
3745 if (image->storage_class == PseudoClass)
3746 for (i=0; i < (ssize_t) image->colors; i++)
3747 {
3748 double
3749 blue,
3750 green,
3751 red;
3752
3753 /*
3754 Modulate image colormap.
3755 */
3756 red=(double) image->colormap[i].red;
3757 green=(double) image->colormap[i].green;
3758 blue=(double) image->colormap[i].blue;
3759 switch (colorspace)
3760 {
3761 case HCLColorspace:
3762 {
3763 ModulateHCL(percent_hue,percent_saturation,percent_brightness,
3764 &red,&green,&blue);
3765 break;
3766 }
3767 case HCLpColorspace:
3768 {
3769 ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
3770 &red,&green,&blue);
3771 break;
3772 }
3773 case HSBColorspace:
3774 {
3775 ModulateHSB(percent_hue,percent_saturation,percent_brightness,
3776 &red,&green,&blue);
3777 break;
3778 }
3779 case HSIColorspace:
3780 {
3781 ModulateHSI(percent_hue,percent_saturation,percent_brightness,
3782 &red,&green,&blue);
3783 break;
3784 }
3785 case HSLColorspace:
3786 default:
3787 {
3788 ModulateHSL(percent_hue,percent_saturation,percent_brightness,
3789 &red,&green,&blue);
3790 break;
3791 }
3792 case HSVColorspace:
3793 {
3794 ModulateHSV(percent_hue,percent_saturation,percent_brightness,
3795 &red,&green,&blue);
3796 break;
3797 }
3798 case HWBColorspace:
3799 {
3800 ModulateHWB(percent_hue,percent_saturation,percent_brightness,
3801 &red,&green,&blue);
3802 break;
3803 }
3804 case LCHColorspace:
3805 case LCHabColorspace:
3806 {
3807 ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
3808 illuminant,&red,&green,&blue);
3809 break;
3810 }
3811 case LCHuvColorspace:
3812 {
3813 ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
3814 illuminant,&red,&green,&blue);
3815 break;
3816 }
3817 }
3818 image->colormap[i].red=red;
3819 image->colormap[i].green=green;
3820 image->colormap[i].blue=blue;
3821 }
3822 /*
3823 Modulate image.
3824 */
3825#if defined(MAGICKCORE_OPENCL_SUPPORT)
3826 if (AccelerateModulateImage(image,percent_brightness,percent_hue,
3827 percent_saturation,colorspace,exception) != MagickFalse)
3828 return(MagickTrue);
3829#endif
3830 status=MagickTrue;
3831 progress=0;
3832 image_view=AcquireAuthenticCacheView(image,exception);
3833#if defined(MAGICKCORE_OPENMP_SUPPORT)
3834 #pragma omp parallel for schedule(static) shared(progress,status) \
3835 magick_number_threads(image,image,image->rows,1)
3836#endif
3837 for (y=0; y < (ssize_t) image->rows; y++)
3838 {
3839 Quantum
3840 *magick_restrict q;
3841
3842 ssize_t
3843 x;
3844
3845 if (status == MagickFalse)
3846 continue;
3847 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3848 if (q == (Quantum *) NULL)
3849 {
3850 status=MagickFalse;
3851 continue;
3852 }
3853 for (x=0; x < (ssize_t) image->columns; x++)
3854 {
3855 double
3856 blue,
3857 green,
3858 red;
3859
3860 red=(double) GetPixelRed(image,q);
3861 green=(double) GetPixelGreen(image,q);
3862 blue=(double) GetPixelBlue(image,q);
3863 switch (colorspace)
3864 {
3865 case HCLColorspace:
3866 {
3867 ModulateHCL(percent_hue,percent_saturation,percent_brightness,
3868 &red,&green,&blue);
3869 break;
3870 }
3871 case HCLpColorspace:
3872 {
3873 ModulateHCLp(percent_hue,percent_saturation,percent_brightness,
3874 &red,&green,&blue);
3875 break;
3876 }
3877 case HSBColorspace:
3878 {
3879 ModulateHSB(percent_hue,percent_saturation,percent_brightness,
3880 &red,&green,&blue);
3881 break;
3882 }
3883 case HSIColorspace:
3884 {
3885 ModulateHSI(percent_hue,percent_saturation,percent_brightness,
3886 &red,&green,&blue);
3887 break;
3888 }
3889 case HSLColorspace:
3890 default:
3891 {
3892 ModulateHSL(percent_hue,percent_saturation,percent_brightness,
3893 &red,&green,&blue);
3894 break;
3895 }
3896 case HSVColorspace:
3897 {
3898 ModulateHSV(percent_hue,percent_saturation,percent_brightness,
3899 &red,&green,&blue);
3900 break;
3901 }
3902 case HWBColorspace:
3903 {
3904 ModulateHWB(percent_hue,percent_saturation,percent_brightness,
3905 &red,&green,&blue);
3906 break;
3907 }
3908 case LCHColorspace:
3909 case LCHabColorspace:
3910 {
3911 ModulateLCHab(percent_brightness,percent_saturation,percent_hue,
3912 illuminant,&red,&green,&blue);
3913 break;
3914 }
3915 case LCHuvColorspace:
3916 {
3917 ModulateLCHuv(percent_brightness,percent_saturation,percent_hue,
3918 illuminant,&red,&green,&blue);
3919 break;
3920 }
3921 }
3922 SetPixelRed(image,ClampToQuantum(red),q);
3923 SetPixelGreen(image,ClampToQuantum(green),q);
3924 SetPixelBlue(image,ClampToQuantum(blue),q);
3925 q+=(ptrdiff_t) GetPixelChannels(image);
3926 }
3927 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3928 status=MagickFalse;
3929 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3930 {
3931 MagickBooleanType
3932 proceed;
3933
3934#if defined(MAGICKCORE_OPENMP_SUPPORT)
3935 #pragma omp atomic
3936#endif
3937 progress++;
3938 proceed=SetImageProgress(image,ModulateImageTag,progress,image->rows);
3939 if (proceed == MagickFalse)
3940 status=MagickFalse;
3941 }
3942 }
3943 image_view=DestroyCacheView(image_view);
3944 return(status);
3945}
3946␌
3947/*
3948%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3949% %
3950% %
3951% %
3952% N e g a t e I m a g e %
3953% %
3954% %
3955% %
3956%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3957%
3958% NegateImage() negates the colors in the reference image. The grayscale
3959% option means that only grayscale values within the image are negated.
3960%
3961% The format of the NegateImage method is:
3962%
3963% MagickBooleanType NegateImage(Image *image,
3964% const MagickBooleanType grayscale,ExceptionInfo *exception)
3965%
3966% A description of each parameter follows:
3967%
3968% o image: the image.
3969%
3970% o grayscale: If MagickTrue, only negate grayscale pixels within the image.
3971%
3972% o exception: return any errors or warnings in this structure.
3973%
3974*/
3975MagickExport MagickBooleanType NegateImage(Image *image,
3976 const MagickBooleanType grayscale,ExceptionInfo *exception)
3977{
3978#define NegateImageTag "Negate/Image"
3979
3980 CacheView
3981 *image_view;
3982
3983 MagickBooleanType
3984 status;
3985
3986 MagickOffsetType
3987 progress;
3988
3989 ssize_t
3990 i;
3991
3992 ssize_t
3993 y;
3994
3995 assert(image != (Image *) NULL);
3996 assert(image->signature == MagickCoreSignature);
3997 if (IsEventLogging() != MagickFalse)
3998 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3999 if (image->storage_class == PseudoClass)
4000 for (i=0; i < (ssize_t) image->colors; i++)
4001 {
4002 /*
4003 Negate colormap.
4004 */
4005 if (grayscale != MagickFalse)
4006 if ((image->colormap[i].red != image->colormap[i].green) ||
4007 (image->colormap[i].green != image->colormap[i].blue))
4008 continue;
4009 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
4010 image->colormap[i].red=(double) QuantumRange-image->colormap[i].red;
4011 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
4012 image->colormap[i].green=(double) QuantumRange-image->colormap[i].green;
4013 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
4014 image->colormap[i].blue=(double) QuantumRange-image->colormap[i].blue;
4015 }
4016 /*
4017 Negate image.
4018 */
4019 status=MagickTrue;
4020 progress=0;
4021 image_view=AcquireAuthenticCacheView(image,exception);
4022 if( grayscale != MagickFalse )
4023 {
4024 for (y=0; y < (ssize_t) image->rows; y++)
4025 {
4026 MagickBooleanType
4027 sync;
4028
4029 Quantum
4030 *magick_restrict q;
4031
4032 ssize_t
4033 x;
4034
4035 if (status == MagickFalse)
4036 continue;
4037 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
4038 exception);
4039 if (q == (Quantum *) NULL)
4040 {
4041 status=MagickFalse;
4042 continue;
4043 }
4044 for (x=0; x < (ssize_t) image->columns; x++)
4045 {
4046 ssize_t
4047 j;
4048
4049 if (IsPixelGray(image,q) == MagickFalse)
4050 {
4051 q+=(ptrdiff_t) GetPixelChannels(image);
4052 continue;
4053 }
4054 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
4055 {
4056 PixelChannel channel = GetPixelChannelChannel(image,j);
4057 PixelTrait traits = GetPixelChannelTraits(image,channel);
4058 if ((traits & UpdatePixelTrait) == 0)
4059 continue;
4060 q[j]=QuantumRange-q[j];
4061 }
4062 q+=(ptrdiff_t) GetPixelChannels(image);
4063 }
4064 sync=SyncCacheViewAuthenticPixels(image_view,exception);
4065 if (sync == MagickFalse)
4066 status=MagickFalse;
4067 if (image->progress_monitor != (MagickProgressMonitor) NULL)
4068 {
4069 MagickBooleanType
4070 proceed;
4071
4072 progress++;
4073 proceed=SetImageProgress(image,NegateImageTag,progress,image->rows);
4074 if (proceed == MagickFalse)
4075 status=MagickFalse;
4076 }
4077 }
4078 image_view=DestroyCacheView(image_view);
4079 return(MagickTrue);
4080 }
4081 /*
4082 Negate image.
4083 */
4084#if defined(MAGICKCORE_OPENMP_SUPPORT)
4085 #pragma omp parallel for schedule(static) shared(progress,status) \
4086 magick_number_threads(image,image,image->rows,1)
4087#endif
4088 for (y=0; y < (ssize_t) image->rows; y++)
4089 {
4090 Quantum
4091 *magick_restrict q;
4092
4093 ssize_t
4094 x;
4095
4096 if (status == MagickFalse)
4097 continue;
4098 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
4099 if (q == (Quantum *) NULL)
4100 {
4101 status=MagickFalse;
4102 continue;
4103 }
4104 for (x=0; x < (ssize_t) image->columns; x++)
4105 {
4106 ssize_t
4107 j;
4108
4109 for (j=0; j < (ssize_t) GetPixelChannels(image); j++)
4110 {
4111 PixelChannel channel = GetPixelChannelChannel(image,j);
4112 PixelTrait traits = GetPixelChannelTraits(image,channel);
4113 if ((traits & UpdatePixelTrait) == 0)
4114 continue;
4115 q[j]=QuantumRange-q[j];
4116 }
4117 q+=(ptrdiff_t) GetPixelChannels(image);
4118 }
4119 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
4120 status=MagickFalse;
4121 if (image->progress_monitor != (MagickProgressMonitor) NULL)
4122 {
4123 MagickBooleanType
4124 proceed;
4125
4126#if defined(MAGICKCORE_OPENMP_SUPPORT)
4127 #pragma omp atomic
4128#endif
4129 progress++;
4130 proceed=SetImageProgress(image,NegateImageTag,progress,image->rows);
4131 if (proceed == MagickFalse)
4132 status=MagickFalse;
4133 }
4134 }
4135 image_view=DestroyCacheView(image_view);
4136 return(status);
4137}
4138␌
4139/*
4140%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4141% %
4142% %
4143% %
4144% N o r m a l i z e I m a g e %
4145% %
4146% %
4147% %
4148%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4149%
4150% The NormalizeImage() method enhances the contrast of a color image by
4151% mapping the darkest 2 percent of all pixel to black and the brightest
4152% 1 percent to white.
4153%
4154% The format of the NormalizeImage method is:
4155%
4156% MagickBooleanType NormalizeImage(Image *image,ExceptionInfo *exception)
4157%
4158% A description of each parameter follows:
4159%
4160% o image: the image.
4161%
4162% o exception: return any errors or warnings in this structure.
4163%
4164*/
4165MagickExport MagickBooleanType NormalizeImage(Image *image,
4166 ExceptionInfo *exception)
4167{
4168 double
4169 black_point,
4170 white_point;
4171
4172 black_point=0.02*image->columns*image->rows;
4173 white_point=0.99*image->columns*image->rows;
4174 return(ContrastStretchImage(image,black_point,white_point,exception));
4175}
4176␌
4177/*
4178%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4179% %
4180% %
4181% %
4182% S i g m o i d a l C o n t r a s t I m a g e %
4183% %
4184% %
4185% %
4186%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4187%
4188% SigmoidalContrastImage() adjusts the contrast of an image with a non-linear
4189% sigmoidal contrast algorithm. Increase the contrast of the image using a
4190% sigmoidal transfer function without saturating highlights or shadows.
4191% Contrast indicates how much to increase the contrast (0 is none; 3 is
4192% typical; 20 is pushing it); mid-point indicates where midtones fall in the
4193% resultant image (0 is white; 50% is middle-gray; 100% is black). Set
4194% sharpen to MagickTrue to increase the image contrast otherwise the contrast
4195% is reduced.
4196%
4197% The format of the SigmoidalContrastImage method is:
4198%
4199% MagickBooleanType SigmoidalContrastImage(Image *image,
4200% const MagickBooleanType sharpen,const char *levels,
4201% ExceptionInfo *exception)
4202%
4203% A description of each parameter follows:
4204%
4205% o image: the image.
4206%
4207% o sharpen: Increase or decrease image contrast.
4208%
4209% o contrast: strength of the contrast, the larger the number the more
4210% 'threshold-like' it becomes.
4211%
4212% o midpoint: midpoint of the function as a color value 0 to QuantumRange.
4213%
4214% o exception: return any errors or warnings in this structure.
4215%
4216*/
4217
4218/*
4219 ImageMagick 6 has a version of this function which uses LUTs.
4220*/
4221
4222/*
4223 Sigmoidal function Sigmoidal with inflexion point moved to b and "slope
4224 constant" set to a.
4225
4226 The first version, based on the hyperbolic tangent tanh, when combined with
4227 the scaling step, is an exact arithmetic clone of the sigmoid function
4228 based on the logistic curve. The equivalence is based on the identity
4229
4230 1/(1+exp(-t)) = (1+tanh(t/2))/2
4231
4232 (http://de.wikipedia.org/wiki/Sigmoidfunktion) and the fact that the
4233 scaled sigmoidal derivation is invariant under affine transformations of
4234 the ordinate.
4235
4236 The tanh version is almost certainly more accurate and cheaper. The 0.5
4237 factor in the argument is to clone the legacy ImageMagick behavior. The
4238 reason for making the define depend on atanh even though it only uses tanh
4239 has to do with the construction of the inverse of the scaled sigmoidal.
4240*/
4241#if defined(MAGICKCORE_HAVE_ATANH)
4242#define Sigmoidal(a,b,x) ( tanh((0.5*(a))*((x)-(b))) )
4243#else
4244#define Sigmoidal(a,b,x) ( 1.0/(1.0+exp((a)*((b)-(x)))) )
4245#endif
4246/*
4247 Scaled sigmoidal function:
4248
4249 ( Sigmoidal(a,b,x) - Sigmoidal(a,b,0) ) /
4250 ( Sigmoidal(a,b,1) - Sigmoidal(a,b,0) )
4251
4252 See http://osdir.com/ml/video.image-magick.devel/2005-04/msg00006.html and
4253 http://www.cs.dartmouth.edu/farid/downloads/tutorials/fip.pdf. The limit
4254 of ScaledSigmoidal as a->0 is the identity, but a=0 gives a division by
4255 zero. This is fixed below by exiting immediately when contrast is small,
4256 leaving the image (or colormap) unmodified. This appears to be safe because
4257 the series expansion of the logistic sigmoidal function around x=b is
4258
4259 1/2-a*(b-x)/4+...
4260
4261 so that the key denominator s(1)-s(0) is about a/4 (a/2 with tanh).
4262*/
4263#define ScaledSigmoidal(a,b,x) ( \
4264 (Sigmoidal((a),(b),(x))-Sigmoidal((a),(b),0.0)) / \
4265 (Sigmoidal((a),(b),1.0)-Sigmoidal((a),(b),0.0)) )
4266/*
4267 Inverse of ScaledSigmoidal, used for +sigmoidal-contrast. Because b
4268 may be 0 or 1, the argument of the hyperbolic tangent (resp. logistic
4269 sigmoidal) may be outside of the interval (-1,1) (resp. (0,1)), even
4270 when creating a LUT from in gamut values, hence the branching. In
4271 addition, HDRI may have out of gamut values.
4272 InverseScaledSigmoidal is not a two-sided inverse of ScaledSigmoidal:
4273 It is only a right inverse. This is unavoidable.
4274*/
4275static inline double InverseScaledSigmoidal(const double a,const double b,
4276 const double x)
4277{
4278 const double sig0=Sigmoidal(a,b,0.0);
4279 const double sig1=Sigmoidal(a,b,1.0);
4280 const double argument=(sig1-sig0)*x+sig0;
4281 const double clamped=
4282 (
4283#if defined(MAGICKCORE_HAVE_ATANH)
4284 argument < -1+MagickEpsilon
4285 ?
4286 -1+MagickEpsilon
4287 :
4288 ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
4289 );
4290 return(b+(2.0/a)*atanh(clamped));
4291#else
4292 argument < MagickEpsilon
4293 ?
4294 MagickEpsilon
4295 :
4296 ( argument > 1-MagickEpsilon ? 1-MagickEpsilon : argument )
4297 );
4298 return(b-log(1.0/clamped-1.0)/a);
4299#endif
4300}
4301
4302MagickExport MagickBooleanType SigmoidalContrastImage(Image *image,
4303 const MagickBooleanType sharpen,const double contrast,const double midpoint,
4304 ExceptionInfo *exception)
4305{
4306#define SigmoidalContrastImageTag "SigmoidalContrast/Image"
4307#define ScaledSig(x) (ClampToQuantum((double) QuantumRange* \
4308 ScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale*((double) x))) )
4309#define InverseScaledSig(x) (ClampToQuantum((double) QuantumRange* \
4310 InverseScaledSigmoidal(contrast,QuantumScale*midpoint,QuantumScale* \
4311 ((double) x))) )
4312
4313 CacheView
4314 *image_view;
4315
4316 MagickBooleanType
4317 status;
4318
4319 MagickOffsetType
4320 progress;
4321
4322 ssize_t
4323 y;
4324
4325 /*
4326 Convenience macros.
4327 */
4328 assert(image != (Image *) NULL);
4329 assert(image->signature == MagickCoreSignature);
4330 if (IsEventLogging() != MagickFalse)
4331 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
4332 /*
4333 Side effect: may clamp values unless contrast<MagickEpsilon, in which
4334 case nothing is done.
4335 */
4336 if (contrast < MagickEpsilon)
4337 return(MagickTrue);
4338 /*
4339 Sigmoidal-contrast enhance colormap.
4340 */
4341 if (image->storage_class == PseudoClass)
4342 {
4343 ssize_t
4344 i;
4345
4346 if( sharpen != MagickFalse )
4347 for (i=0; i < (ssize_t) image->colors; i++)
4348 {
4349 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
4350 image->colormap[i].red=(MagickRealType) ScaledSig(
4351 image->colormap[i].red);
4352 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
4353 image->colormap[i].green=(MagickRealType) ScaledSig(
4354 image->colormap[i].green);
4355 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
4356 image->colormap[i].blue=(MagickRealType) ScaledSig(
4357 image->colormap[i].blue);
4358 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
4359 image->colormap[i].alpha=(MagickRealType) ScaledSig(
4360 image->colormap[i].alpha);
4361 }
4362 else
4363 for (i=0; i < (ssize_t) image->colors; i++)
4364 {
4365 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
4366 image->colormap[i].red=(MagickRealType) InverseScaledSig(
4367 image->colormap[i].red);
4368 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
4369 image->colormap[i].green=(MagickRealType) InverseScaledSig(
4370 image->colormap[i].green);
4371 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
4372 image->colormap[i].blue=(MagickRealType) InverseScaledSig(
4373 image->colormap[i].blue);
4374 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
4375 image->colormap[i].alpha=(MagickRealType) InverseScaledSig(
4376 image->colormap[i].alpha);
4377 }
4378 }
4379 /*
4380 Sigmoidal-contrast enhance image.
4381 */
4382 status=MagickTrue;
4383 progress=0;
4384 image_view=AcquireAuthenticCacheView(image,exception);
4385#if defined(MAGICKCORE_OPENMP_SUPPORT)
4386 #pragma omp parallel for schedule(static) shared(progress,status) \
4387 magick_number_threads(image,image,image->rows,1)
4388#endif
4389 for (y=0; y < (ssize_t) image->rows; y++)
4390 {
4391 Quantum
4392 *magick_restrict q;
4393
4394 ssize_t
4395 x;
4396
4397 if (status == MagickFalse)
4398 continue;
4399 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
4400 if (q == (Quantum *) NULL)
4401 {
4402 status=MagickFalse;
4403 continue;
4404 }
4405 for (x=0; x < (ssize_t) image->columns; x++)
4406 {
4407 ssize_t
4408 i;
4409
4410 for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
4411 {
4412 PixelChannel channel = GetPixelChannelChannel(image,i);
4413 PixelTrait traits = GetPixelChannelTraits(image,channel);
4414 if ((traits & UpdatePixelTrait) == 0)
4415 continue;
4416 if( sharpen != MagickFalse )
4417 q[i]=ScaledSig(q[i]);
4418 else
4419 q[i]=InverseScaledSig(q[i]);
4420 }
4421 q+=(ptrdiff_t) GetPixelChannels(image);
4422 }
4423 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
4424 status=MagickFalse;
4425 if (image->progress_monitor != (MagickProgressMonitor) NULL)
4426 {
4427 MagickBooleanType
4428 proceed;
4429
4430#if defined(MAGICKCORE_OPENMP_SUPPORT)
4431 #pragma omp atomic
4432#endif
4433 progress++;
4434 proceed=SetImageProgress(image,SigmoidalContrastImageTag,progress,
4435 image->rows);
4436 if (proceed == MagickFalse)
4437 status=MagickFalse;
4438 }
4439 }
4440 image_view=DestroyCacheView(image_view);
4441 return(status);
4442}
4443␌
4444/*
4445%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4446% %
4447% %
4448% %
4449% W h i t e B a l a n c e I m a g e %
4450% %
4451% %
4452% %
4453%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4454%
4455% WhiteBalanceImage() applies white balancing to an image according to a
4456% grayworld assumption in the LAB colorspace.
4457%
4458% The format of the WhiteBalanceImage method is:
4459%
4460% MagickBooleanType WhiteBalanceImage(Image *image,
4461% ExceptionInfo *exception)
4462%
4463% A description of each parameter follows:
4464%
4465% o image: The image to auto-level
4466%
4467% o exception: return any errors or warnings in this structure.
4468%
4469*/
4470MagickExport MagickBooleanType WhiteBalanceImage(Image *image,
4471 ExceptionInfo *exception)
4472{
4473#define WhiteBalanceImageTag "WhiteBalance/Image"
4474
4475 CacheView
4476 *image_view;
4477
4478 const char
4479 *artifact;
4480
4481 double
4482 a_mean,
4483 b_mean;
4484
4485 MagickOffsetType
4486 progress;
4487
4488 MagickStatusType
4489 status;
4490
4491 ssize_t
4492 y;
4493
4494 /*
4495 White balance image.
4496 */
4497 assert(image != (Image *) NULL);
4498 assert(image->signature == MagickCoreSignature);
4499 if (IsEventLogging() != MagickFalse)
4500 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
4501 if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
4502 return(MagickFalse);
4503 status=TransformImageColorspace(image,LabColorspace,exception);
4504 a_mean=0.0;
4505 b_mean=0.0;
4506 image_view=AcquireAuthenticCacheView(image,exception);
4507 for (y=0; y < (ssize_t) image->rows; y++)
4508 {
4509 const Quantum
4510 *magick_restrict p;
4511
4512 ssize_t
4513 x;
4514
4515 if (status == MagickFalse)
4516 continue;
4517 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
4518 if (p == (Quantum *) NULL)
4519 {
4520 status=MagickFalse;
4521 continue;
4522 }
4523 for (x=0; x < (ssize_t) image->columns; x++)
4524 {
4525 a_mean+=QuantumScale*(double) GetPixela(image,p)-0.5;
4526 b_mean+=QuantumScale*(double) GetPixelb(image,p)-0.5;
4527 p+=(ptrdiff_t) GetPixelChannels(image);
4528 }
4529 }
4530 a_mean/=((double) image->columns*image->rows);
4531 b_mean/=((double) image->columns*image->rows);
4532 progress=0;
4533#if defined(MAGICKCORE_OPENMP_SUPPORT)
4534 #pragma omp parallel for schedule(static) shared(progress,status) \
4535 magick_number_threads(image,image,image->rows,1)
4536#endif
4537 for (y=0; y < (ssize_t) image->rows; y++)
4538 {
4539 Quantum
4540 *magick_restrict q;
4541
4542 ssize_t
4543 x;
4544
4545 if (status == MagickFalse)
4546 continue;
4547 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
4548 if (q == (Quantum *) NULL)
4549 {
4550 status=MagickFalse;
4551 continue;
4552 }
4553 for (x=0; x < (ssize_t) image->columns; x++)
4554 {
4555 double
4556 a,
4557 b;
4558
4559 /*
4560 Scale the chroma distance shifted according to amount of luminance.
4561 */
4562 a=(double) GetPixela(image,q)-1.1*(double) GetPixelL(image,q)*a_mean;
4563 b=(double) GetPixelb(image,q)-1.1*(double) GetPixelL(image,q)*b_mean;
4564 SetPixela(image,ClampToQuantum(a),q);
4565 SetPixelb(image,ClampToQuantum(b),q);
4566 q+=(ptrdiff_t) GetPixelChannels(image);
4567 }
4568 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
4569 status=MagickFalse;
4570 if (image->progress_monitor != (MagickProgressMonitor) NULL)
4571 {
4572 MagickBooleanType
4573 proceed;
4574
4575#if defined(MAGICKCORE_OPENMP_SUPPORT)
4576 #pragma omp atomic
4577#endif
4578 progress++;
4579 proceed=SetImageProgress(image,WhiteBalanceImageTag,progress,
4580 image->rows);
4581 if (proceed == MagickFalse)
4582 status=MagickFalse;
4583 }
4584 }
4585 image_view=DestroyCacheView(image_view);
4586 artifact=GetImageArtifact(image,"white-balance:vibrance");
4587 if (artifact != (const char *) NULL)
4588 {
4589 ChannelType
4590 channel_mask;
4591
4592 double
4593 black_point = 0.0;
4594
4595 GeometryInfo
4596 geometry_info;
4597
4598 MagickStatusType
4599 flags;
4600
4601 /*
4602 Level the a & b channels.
4603 */
4604 flags=ParseGeometry(artifact,&geometry_info);
4605 if ((flags & RhoValue) != 0)
4606 black_point=geometry_info.rho;
4607 if ((flags & PercentValue) != 0)
4608 black_point*=((double) QuantumRange/100.0);
4609 channel_mask=SetImageChannelMask(image,(ChannelType) (aChannel |
4610 bChannel));
4611 status&=(MagickStatusType) LevelImage(image,black_point,(double)
4612 QuantumRange-black_point,1.0,exception);
4613 (void) SetImageChannelMask(image,channel_mask);
4614 }
4615 status&=(MagickStatusType) TransformImageColorspace(image,sRGBColorspace,
4616 exception);
4617 return(status != 0 ? MagickTrue : MagickFalse);
4618}