]> granicus.if.org Git - imagemagick/blob - MagickCore/histogram.c
Update web pages
[imagemagick] / MagickCore / histogram.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %      H   H   IIIII   SSSSS  TTTTT   OOO    GGGG  RRRR    AAA   M   M        %
7 %      H   H     I     SS       T    O   O  G      R   R  A   A  MM MM        %
8 %      HHHHH     I      SSS     T    O   O  G  GG  RRRR   AAAAA  M M M        %
9 %      H   H     I        SS    T    O   O  G   G  R R    A   A  M   M        %
10 %      H   H   IIIII   SSSSS    T     OOO    GGG   R  R   A   A  M   M        %
11 %                                                                             %
12 %                                                                             %
13 %                        MagickCore Histogram Methods                         %
14 %                                                                             %
15 %                              Software Design                                %
16 %                              Anthony Thyssen                                %
17 %                               Fred Weinhaus                                 %
18 %                                August 2009                                  %
19 %                                                                             %
20 %                                                                             %
21 %  Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization      %
22 %  dedicated to making software imaging solutions freely available.           %
23 %                                                                             %
24 %  You may not use this file except in compliance with the License.  You may  %
25 %  obtain a copy of the License at                                            %
26 %                                                                             %
27 %    http://www.imagemagick.org/script/license.php                            %
28 %                                                                             %
29 %  Unless required by applicable law or agreed to in writing, software        %
30 %  distributed under the License is distributed on an "AS IS" BASIS,          %
31 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
32 %  See the License for the specific language governing permissions and        %
33 %  limitations under the License.                                             %
34 %                                                                             %
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 %
37 %
38 */
39 \f
40 /*
41   Include declarations.
42 */
43 #include "MagickCore/studio.h"
44 #include "MagickCore/cache-view.h"
45 #include "MagickCore/color-private.h"
46 #include "MagickCore/enhance.h"
47 #include "MagickCore/exception.h"
48 #include "MagickCore/exception-private.h"
49 #include "MagickCore/hashmap.h"
50 #include "MagickCore/histogram.h"
51 #include "MagickCore/image.h"
52 #include "MagickCore/list.h"
53 #include "MagickCore/memory_.h"
54 #include "MagickCore/monitor-private.h"
55 #include "MagickCore/pixel-accessor.h"
56 #include "MagickCore/prepress.h"
57 #include "MagickCore/quantize.h"
58 #include "MagickCore/registry.h"
59 #include "MagickCore/semaphore.h"
60 #include "MagickCore/splay-tree.h"
61 #include "MagickCore/statistic.h"
62 #include "MagickCore/string_.h"
63 \f
64 /*
65   Define declarations.
66 */
67 #define MaxTreeDepth  8
68 #define NodesInAList  1536
69 \f
70 /*
71   Typedef declarations.
72 */
73 typedef struct _NodeInfo
74 {
75   struct _NodeInfo
76     *child[16];
77
78   PixelInfo
79     *list;
80
81   MagickSizeType
82     number_unique;
83
84   size_t
85     level;
86 } NodeInfo;
87
88 typedef struct _Nodes
89 {
90   NodeInfo
91     nodes[NodesInAList];
92
93   struct _Nodes
94     *next;
95 } Nodes;
96
97 typedef struct _CubeInfo
98 {
99   NodeInfo
100     *root;
101
102   ssize_t
103     x;
104
105   MagickOffsetType
106     progress;
107
108   size_t
109     colors,
110     free_nodes;
111
112   NodeInfo
113     *node_info;
114
115   Nodes
116     *node_queue;
117 } CubeInfo;
118 \f
119 /*
120   Forward declarations.
121 */
122 static CubeInfo
123   *GetCubeInfo(void);
124
125 static NodeInfo
126   *GetNodeInfo(CubeInfo *,const size_t);
127
128 static void
129   DestroyColorCube(const Image *,NodeInfo *);
130 \f
131 /*
132 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
133 %                                                                             %
134 %                                                                             %
135 %                                                                             %
136 +   C l a s s i f y I m a g e C o l o r s                                     %
137 %                                                                             %
138 %                                                                             %
139 %                                                                             %
140 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
141 %
142 %  ClassifyImageColors() builds a populated CubeInfo tree for the specified
143 %  image.  The returned tree should be deallocated using DestroyCubeInfo()
144 %  once it is no longer needed.
145 %
146 %  The format of the ClassifyImageColors() method is:
147 %
148 %      CubeInfo *ClassifyImageColors(const Image *image,
149 %        ExceptionInfo *exception)
150 %
151 %  A description of each parameter follows.
152 %
153 %    o image: the image.
154 %
155 %    o exception: return any errors or warnings in this structure.
156 %
157 */
158
159 static inline size_t ColorToNodeId(const Image *image,
160   const PixelInfo *pixel,size_t index)
161 {
162   size_t
163     id;
164
165   id=(size_t) (
166     ((ScaleQuantumToChar(ClampToQuantum(pixel->red)) >> index) & 0x01) |
167     ((ScaleQuantumToChar(ClampToQuantum(pixel->green)) >> index) & 0x01) << 1 |
168     ((ScaleQuantumToChar(ClampToQuantum(pixel->blue)) >> index) & 0x01) << 2);
169   if (image->alpha_trait != UndefinedPixelTrait)
170     id|=((ScaleQuantumToChar(ClampToQuantum(pixel->alpha)) >> index) &
171       0x01) << 3;
172   return(id);
173 }
174
175 static CubeInfo *ClassifyImageColors(const Image *image,
176   ExceptionInfo *exception)
177 {
178 #define EvaluateImageTag  "  Compute image colors...  "
179
180   CacheView
181     *image_view;
182
183   CubeInfo
184     *cube_info;
185
186   MagickBooleanType
187     proceed;
188
189   PixelInfo
190     pixel,
191     target;
192
193   NodeInfo
194     *node_info;
195
196   register const Quantum
197     *p;
198
199   register size_t
200     id,
201     index,
202     level;
203
204   register ssize_t
205     i,
206     x;
207
208   ssize_t
209     y;
210
211   /*
212     Initialize color description tree.
213   */
214   assert(image != (const Image *) NULL);
215   assert(image->signature == MagickCoreSignature);
216   if (image->debug != MagickFalse)
217     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
218   cube_info=GetCubeInfo();
219   if (cube_info == (CubeInfo *) NULL)
220     {
221       (void) ThrowMagickException(exception,GetMagickModule(),
222         ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
223       return(cube_info);
224     }
225   GetPixelInfo(image,&pixel);
226   GetPixelInfo(image,&target);
227   image_view=AcquireVirtualCacheView(image,exception);
228   for (y=0; y < (ssize_t) image->rows; y++)
229   {
230     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
231     if (p == (const Quantum *) NULL)
232       break;
233     for (x=0; x < (ssize_t) image->columns; x++)
234     {
235       /*
236         Start at the root and proceed level by level.
237       */
238       node_info=cube_info->root;
239       index=MaxTreeDepth-1;
240       for (level=1; level < MaxTreeDepth; level++)
241       {
242         GetPixelInfoPixel(image,p,&pixel);
243         id=ColorToNodeId(image,&pixel,index);
244         if (node_info->child[id] == (NodeInfo *) NULL)
245           {
246             node_info->child[id]=GetNodeInfo(cube_info,level);
247             if (node_info->child[id] == (NodeInfo *) NULL)
248               {
249                 (void) ThrowMagickException(exception,GetMagickModule(),
250                   ResourceLimitError,"MemoryAllocationFailed","`%s'",
251                   image->filename);
252                 return(0);
253               }
254           }
255         node_info=node_info->child[id];
256         index--;
257       }
258       for (i=0; i < (ssize_t) node_info->number_unique; i++)
259       {
260         target=node_info->list[i];
261         if (IsPixelInfoEquivalent(&pixel,&target) != MagickFalse)
262           break;
263       }
264       if (i < (ssize_t) node_info->number_unique)
265         node_info->list[i].count++;
266       else
267         {
268           if (node_info->number_unique == 0)
269             node_info->list=(PixelInfo *) AcquireMagickMemory(
270               sizeof(*node_info->list));
271           else
272             node_info->list=(PixelInfo *) ResizeQuantumMemory(node_info->list,
273               (size_t) (i+1),sizeof(*node_info->list));
274           if (node_info->list == (PixelInfo *) NULL)
275             {
276               (void) ThrowMagickException(exception,GetMagickModule(),
277                 ResourceLimitError,"MemoryAllocationFailed","`%s'",
278                 image->filename);
279               return(0);
280             }
281           node_info->list[i]=pixel;
282           node_info->list[i].red=(double) GetPixelRed(image,p);
283           node_info->list[i].green=(double) GetPixelGreen(image,p);
284           node_info->list[i].blue=(double) GetPixelBlue(image,p);
285           if (image->colorspace == CMYKColorspace)
286             node_info->list[i].black=(double) GetPixelBlack(image,p);
287           node_info->list[i].alpha=(double) GetPixelAlpha(image,p);
288           node_info->list[i].count=1;
289           node_info->number_unique++;
290           cube_info->colors++;
291         }
292       p+=GetPixelChannels(image);
293     }
294     proceed=SetImageProgress(image,EvaluateImageTag,(MagickOffsetType) y,
295       image->rows);
296     if (proceed == MagickFalse)
297       break;
298   }
299   image_view=DestroyCacheView(image_view);
300   return(cube_info);
301 }
302 \f
303 /*
304 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
305 %                                                                             %
306 %                                                                             %
307 %                                                                             %
308 +   D e f i n e I m a g e H i s t o g r a m                                   %
309 %                                                                             %
310 %                                                                             %
311 %                                                                             %
312 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
313 %
314 %  DefineImageHistogram() traverses the color cube tree and notes each colormap
315 %  entry.  A colormap entry is any node in the color cube tree where the
316 %  of unique colors is not zero.
317 %
318 %  The format of the DefineImageHistogram method is:
319 %
320 %      DefineImageHistogram(const Image *image,NodeInfo *node_info,
321 %        PixelInfo **unique_colors)
322 %
323 %  A description of each parameter follows.
324 %
325 %    o image: the image.
326 %
327 %    o node_info: the address of a structure of type NodeInfo which points to a
328 %      node in the color cube tree that is to be pruned.
329 %
330 %    o histogram: the image histogram.
331 %
332 */
333 static void DefineImageHistogram(const Image *image,NodeInfo *node_info,
334   PixelInfo **histogram)
335 {
336   register ssize_t
337     i;
338
339   size_t
340     number_children;
341
342   /*
343     Traverse any children.
344   */
345   number_children=image->alpha_trait == UndefinedPixelTrait ? 8UL : 16UL;
346   for (i=0; i < (ssize_t) number_children; i++)
347     if (node_info->child[i] != (NodeInfo *) NULL)
348       DefineImageHistogram(image,node_info->child[i],histogram);
349   if (node_info->level == (MaxTreeDepth-1))
350     {
351       register PixelInfo
352         *p;
353
354       p=node_info->list;
355       for (i=0; i < (ssize_t) node_info->number_unique; i++)
356       {
357         **histogram=(*p);
358         (*histogram)++;
359         p++;
360       }
361     }
362 }
363 \f
364 /*
365 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
366 %                                                                             %
367 %                                                                             %
368 %                                                                             %
369 +   D e s t r o y C u b e I n f o                                             %
370 %                                                                             %
371 %                                                                             %
372 %                                                                             %
373 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
374 %
375 %  DestroyCubeInfo() deallocates memory associated with a CubeInfo structure.
376 %
377 %  The format of the DestroyCubeInfo method is:
378 %
379 %      DestroyCubeInfo(const Image *image,CubeInfo *cube_info)
380 %
381 %  A description of each parameter follows:
382 %
383 %    o image: the image.
384 %
385 %    o cube_info: the address of a structure of type CubeInfo.
386 %
387 */
388 static CubeInfo *DestroyCubeInfo(const Image *image,CubeInfo *cube_info)
389 {
390   register Nodes
391     *nodes;
392
393   /*
394     Release color cube tree storage.
395   */
396   DestroyColorCube(image,cube_info->root);
397   do
398   {
399     nodes=cube_info->node_queue->next;
400     cube_info->node_queue=(Nodes *)
401       RelinquishMagickMemory(cube_info->node_queue);
402     cube_info->node_queue=nodes;
403   } while (cube_info->node_queue != (Nodes *) NULL);
404   return((CubeInfo *) RelinquishMagickMemory(cube_info));
405 }
406 \f
407 /*
408 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
409 %                                                                             %
410 %                                                                             %
411 %                                                                             %
412 +  D e s t r o y C o l o r C u b e                                            %
413 %                                                                             %
414 %                                                                             %
415 %                                                                             %
416 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
417 %
418 %  DestroyColorCube() traverses the color cube tree and frees the list of
419 %  unique colors.
420 %
421 %  The format of the DestroyColorCube method is:
422 %
423 %      void DestroyColorCube(const Image *image,const NodeInfo *node_info)
424 %
425 %  A description of each parameter follows.
426 %
427 %    o image: the image.
428 %
429 %    o node_info: the address of a structure of type NodeInfo which points to a
430 %      node in the color cube tree that is to be pruned.
431 %
432 */
433 static void DestroyColorCube(const Image *image,NodeInfo *node_info)
434 {
435   register ssize_t
436     i;
437
438   size_t
439     number_children;
440
441   /*
442     Traverse any children.
443   */
444   number_children=image->alpha_trait == UndefinedPixelTrait ? 8UL : 16UL;
445   for (i=0; i < (ssize_t) number_children; i++)
446     if (node_info->child[i] != (NodeInfo *) NULL)
447       DestroyColorCube(image,node_info->child[i]);
448   if (node_info->list != (PixelInfo *) NULL)
449     node_info->list=(PixelInfo *) RelinquishMagickMemory(node_info->list);
450 }
451 \f
452 /*
453 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
454 %                                                                             %
455 %                                                                             %
456 %                                                                             %
457 +   G e t C u b e I n f o                                                     %
458 %                                                                             %
459 %                                                                             %
460 %                                                                             %
461 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
462 %
463 %  GetCubeInfo() initializes the CubeInfo data structure.
464 %
465 %  The format of the GetCubeInfo method is:
466 %
467 %      cube_info=GetCubeInfo()
468 %
469 %  A description of each parameter follows.
470 %
471 %    o cube_info: A pointer to the Cube structure.
472 %
473 */
474 static CubeInfo *GetCubeInfo(void)
475 {
476   CubeInfo
477     *cube_info;
478
479   /*
480     Initialize tree to describe color cube.
481   */
482   cube_info=(CubeInfo *) AcquireMagickMemory(sizeof(*cube_info));
483   if (cube_info == (CubeInfo *) NULL)
484     return((CubeInfo *) NULL);
485   (void) ResetMagickMemory(cube_info,0,sizeof(*cube_info));
486   /*
487     Initialize root node.
488   */
489   cube_info->root=GetNodeInfo(cube_info,0);
490   if (cube_info->root == (NodeInfo *) NULL)
491     return((CubeInfo *) NULL);
492   return(cube_info);
493 }
494 \f
495 /*
496 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
497 %                                                                             %
498 %                                                                             %
499 %                                                                             %
500 %  G e t I m a g e H i s t o g r a m                                          %
501 %                                                                             %
502 %                                                                             %
503 %                                                                             %
504 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
505 %
506 %  GetImageHistogram() returns the unique colors in an image.
507 %
508 %  The format of the GetImageHistogram method is:
509 %
510 %      size_t GetImageHistogram(const Image *image,
511 %        size_t *number_colors,ExceptionInfo *exception)
512 %
513 %  A description of each parameter follows.
514 %
515 %    o image: the image.
516 %
517 %    o file:  Write a histogram of the color distribution to this file handle.
518 %
519 %    o exception: return any errors or warnings in this structure.
520 %
521 */
522 MagickExport PixelInfo *GetImageHistogram(const Image *image,
523   size_t *number_colors,ExceptionInfo *exception)
524 {
525   PixelInfo
526     *histogram;
527
528   CubeInfo
529     *cube_info;
530
531   *number_colors=0;
532   histogram=(PixelInfo *) NULL;
533   cube_info=ClassifyImageColors(image,exception);
534   if (cube_info != (CubeInfo *) NULL)
535     {
536       histogram=(PixelInfo *) AcquireQuantumMemory((size_t) cube_info->colors,
537         sizeof(*histogram));
538       if (histogram == (PixelInfo *) NULL)
539         (void) ThrowMagickException(exception,GetMagickModule(),
540           ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
541       else
542         {
543           PixelInfo
544             *root;
545
546           *number_colors=cube_info->colors;
547           root=histogram;
548           DefineImageHistogram(image,cube_info->root,&root);
549         }
550     }
551   cube_info=DestroyCubeInfo(image,cube_info);
552   return(histogram);
553 }
554 \f
555 /*
556 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
557 %                                                                             %
558 %                                                                             %
559 %                                                                             %
560 +  G e t N o d e I n f o                                                      %
561 %                                                                             %
562 %                                                                             %
563 %                                                                             %
564 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
565 %
566 %  GetNodeInfo() allocates memory for a new node in the color cube tree and
567 %  presets all fields to zero.
568 %
569 %  The format of the GetNodeInfo method is:
570 %
571 %      NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t level)
572 %
573 %  A description of each parameter follows.
574 %
575 %    o cube_info: A pointer to the CubeInfo structure.
576 %
577 %    o level: Specifies the level in the storage_class the node resides.
578 %
579 */
580 static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t level)
581 {
582   NodeInfo
583     *node_info;
584
585   if (cube_info->free_nodes == 0)
586     {
587       Nodes
588         *nodes;
589
590       /*
591         Allocate a new nodes of nodes.
592       */
593       nodes=(Nodes *) AcquireMagickMemory(sizeof(*nodes));
594       if (nodes == (Nodes *) NULL)
595         return((NodeInfo *) NULL);
596       nodes->next=cube_info->node_queue;
597       cube_info->node_queue=nodes;
598       cube_info->node_info=nodes->nodes;
599       cube_info->free_nodes=NodesInAList;
600     }
601   cube_info->free_nodes--;
602   node_info=cube_info->node_info++;
603   (void) ResetMagickMemory(node_info,0,sizeof(*node_info));
604   node_info->level=level;
605   return(node_info);
606 }
607 \f
608 /*
609 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
610 %                                                                             %
611 %                                                                             %
612 %                                                                             %
613 %  I d e n t i f y P a l e t t e I m a g e                                    %
614 %                                                                             %
615 %                                                                             %
616 %                                                                             %
617 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
618 %
619 %  IdentifyPaletteImage() returns MagickTrue if the image has 256 unique colors
620 %  or less.
621 %
622 %  The format of the IdentifyPaletteImage method is:
623 %
624 %      MagickBooleanType IdentifyPaletteImage(const Image *image,
625 %        ExceptionInfo *exception)
626 %
627 %  A description of each parameter follows.
628 %
629 %    o image: the image.
630 %
631 %    o exception: return any errors or warnings in this structure.
632 %
633 */
634
635 static MagickBooleanType CheckImageColors(const Image *image,
636   ExceptionInfo *exception,size_t max_colors)
637 {
638   CacheView
639     *image_view;
640
641   CubeInfo
642     *cube_info;
643
644   PixelInfo
645     pixel,
646     target;
647
648   register const Quantum
649     *p;
650
651   register ssize_t
652     x;
653
654   register NodeInfo
655     *node_info;
656
657   register ssize_t
658     i;
659
660   size_t
661     id,
662     index,
663     level;
664
665   ssize_t
666     y;
667
668   if (image->storage_class == PseudoClass)
669     return((image->colors <= max_colors) ? MagickTrue : MagickFalse);
670   /*
671     Initialize color description tree.
672   */
673   cube_info=GetCubeInfo();
674   if (cube_info == (CubeInfo *) NULL)
675     {
676       (void) ThrowMagickException(exception,GetMagickModule(),
677         ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
678       return(MagickFalse);
679     }
680   GetPixelInfo(image,&pixel);
681   GetPixelInfo(image,&target);
682   image_view=AcquireVirtualCacheView(image,exception);
683   for (y=0; y < (ssize_t) image->rows; y++)
684   {
685     p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
686     if (p == (const Quantum *) NULL)
687       break;
688     for (x=0; x < (ssize_t) image->columns; x++)
689     {
690       /*
691         Start at the root and proceed level by level.
692       */
693       node_info=cube_info->root;
694       index=MaxTreeDepth-1;
695       for (level=1; level < MaxTreeDepth; level++)
696       {
697         GetPixelInfoPixel(image,p,&pixel);
698         id=ColorToNodeId(image,&pixel,index);
699         if (node_info->child[id] == (NodeInfo *) NULL)
700           {
701             node_info->child[id]=GetNodeInfo(cube_info,level);
702             if (node_info->child[id] == (NodeInfo *) NULL)
703               {
704                 (void) ThrowMagickException(exception,GetMagickModule(),
705                   ResourceLimitError,"MemoryAllocationFailed","`%s'",
706                   image->filename);
707                 break;
708               }
709           }
710         node_info=node_info->child[id];
711         index--;
712       }
713       if (level < MaxTreeDepth)
714         break;
715       for (i=0; i < (ssize_t) node_info->number_unique; i++)
716       {
717         target=node_info->list[i];
718         if (IsPixelInfoEquivalent(&pixel,&target) != MagickFalse)
719           break;
720       }
721       if (i < (ssize_t) node_info->number_unique)
722         node_info->list[i].count++;
723       else
724         {
725           /*
726             Add this unique color to the color list.
727           */
728           if (node_info->number_unique == 0)
729             node_info->list=(PixelInfo *) AcquireMagickMemory(
730               sizeof(*node_info->list));
731           else
732             node_info->list=(PixelInfo *) ResizeQuantumMemory(node_info->list,
733               (size_t) (i+1),sizeof(*node_info->list));
734           if (node_info->list == (PixelInfo *) NULL)
735             {
736               (void) ThrowMagickException(exception,GetMagickModule(),
737                 ResourceLimitError,"MemoryAllocationFailed","`%s'",
738                 image->filename);
739               break;
740             }
741           node_info->list[i].red=(double) GetPixelRed(image,p);
742           node_info->list[i].green=(double) GetPixelGreen(image,p);
743           node_info->list[i].blue=(double) GetPixelBlue(image,p);
744           if (image->colorspace == CMYKColorspace)
745             node_info->list[i].black=(double) GetPixelBlack(image,p);
746           node_info->list[i].alpha=(double) GetPixelAlpha(image,p);
747           node_info->list[i].count=1;
748           node_info->number_unique++;
749           cube_info->colors++;
750           if (cube_info->colors > max_colors)
751             break;
752         }
753       p+=GetPixelChannels(image);
754     }
755     if (x < (ssize_t) image->columns)
756       break;
757   }
758   image_view=DestroyCacheView(image_view);
759   cube_info=DestroyCubeInfo(image,cube_info);
760   return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
761 }
762
763 MagickExport MagickBooleanType IdentifyPaletteImage(const Image *image,
764   ExceptionInfo *exception)
765 {
766   assert(image != (Image *) NULL);
767   assert(image->signature == MagickCoreSignature);
768   if (image->debug != MagickFalse)
769     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
770   return(CheckImageColors(image,exception,256));
771 }
772
773 /*
774 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
775 %                                                                             %
776 %                                                                             %
777 %                                                                             %
778 %  I s H i s t o g r a m I m a g e                                            %
779 %                                                                             %
780 %                                                                             %
781 %                                                                             %
782 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
783 %
784 %  IsHistogramImage() returns MagickTrue if the image has 1024 unique colors or
785 %  less.
786 %
787 %  The format of the IsHistogramImage method is:
788 %
789 %      MagickBooleanType IsHistogramImage(const Image *image,
790 %        ExceptionInfo *exception)
791 %
792 %  A description of each parameter follows.
793 %
794 %    o image: the image.
795 %
796 %    o exception: return any errors or warnings in this structure.
797 %
798 */
799 MagickExport MagickBooleanType IsHistogramImage(const Image *image,
800   ExceptionInfo *exception)
801 {
802 #define MaximumUniqueColors  1024
803
804   assert(image != (Image *) NULL);
805   assert(image->signature == MagickCoreSignature);
806   if (image->debug != MagickFalse)
807     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
808   return(CheckImageColors(image,exception,MaximumUniqueColors));
809 }
810 \f
811 /*
812 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
813 %                                                                             %
814 %                                                                             %
815 %                                                                             %
816 %  I s P a l e t t e I m a g e                                                %
817 %                                                                             %
818 %                                                                             %
819 %                                                                             %
820 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
821 %
822 %  IsPaletteImage() returns MagickTrue if the image is PseudoClass and has 256
823 %  unique colors or less.
824 %
825 %  The format of the IsPaletteImage method is:
826 %
827 %      MagickBooleanType IsPaletteImage(const Image *image)
828 %
829 %  A description of each parameter follows.
830 %
831 %    o image: the image.
832 %
833 */
834 MagickExport MagickBooleanType IsPaletteImage(const Image *image)
835 {
836   assert(image != (Image *) NULL);
837   assert(image->signature == MagickCoreSignature);
838   if (image->debug != MagickFalse)
839     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
840   if (image->storage_class != PseudoClass)
841     return(MagickFalse);
842   return((image->colors <= 256) ? MagickTrue : MagickFalse);
843 }
844 \f
845 /*
846 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
847 %                                                                             %
848 %                                                                             %
849 %                                                                             %
850 %     M i n M a x S t r e t c h I m a g e                                     %
851 %                                                                             %
852 %                                                                             %
853 %                                                                             %
854 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
855 %
856 %  MinMaxStretchImage() uses the exact minimum and maximum values found in
857 %  each of the channels given, as the BlackPoint and WhitePoint to linearly
858 %  stretch the colors (and histogram) of the image.  The stretch points are
859 %  also moved further inward by the adjustment values given.
860 %
861 %  If the adjustment values are both zero this function is equivalent to a
862 %  perfect normalization (or autolevel) of the image.
863 %
864 %  Each channel is stretched independantally of each other (producing color
865 %  distortion) unless the special 'SyncChannels' flag is also provided in the
866 %  channels setting. If this flag is present the minimum and maximum point
867 %  will be extracted from all the given channels, and those channels will be
868 %  stretched by exactly the same amount (preventing color distortion).
869 %
870 %  In the special case that only ONE value is found in a channel of the image
871 %  that value is not stretched, that value is left as is.
872 %
873 %  The 'SyncChannels' is turned on in the 'DefaultChannels' setting by
874 %  default.
875 %
876 %  The format of the MinMaxStretchImage method is:
877 %
878 %      MagickBooleanType MinMaxStretchImage(Image *image,const double black,
879 %        const double white,const double gamma,ExceptionInfo *exception)
880 %
881 %  A description of each parameter follows:
882 %
883 %    o image: The image to auto-level
884 %
885 %    o black, white:  move the black / white point inward from the minimum and
886 %      maximum points by this color value.
887 %
888 %    o gamma: the gamma.
889 %
890 %    o exception: return any errors or warnings in this structure.
891 %
892 */
893 MagickExport MagickBooleanType MinMaxStretchImage(Image *image,
894   const double black,const double white,const double gamma,
895   ExceptionInfo *exception)
896 {
897   double
898     min,
899     max;
900
901   register ssize_t
902     i;
903
904   MagickStatusType
905     status;
906
907   /*
908     Auto-level each channel.
909   */
910   status=MagickTrue;
911   for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
912   {
913     ChannelType
914       channel_mask;
915
916     PixelChannel channel=GetPixelChannelChannel(image,i);
917     PixelTrait traits=GetPixelChannelTraits(image,channel);
918     if ((traits & UpdatePixelTrait) == 0)
919       continue;
920     channel_mask=SetImageChannelMask(image,(ChannelType) (1 << i));
921     status&=GetImageRange(image,&min,&max,exception);
922     min+=black;
923     max-=white;
924     if (fabs(min-max) >= MagickEpsilon)
925       status&=LevelImage(image,min,max,gamma,exception);
926     (void) SetImageChannelMask(image,channel_mask);
927   }
928   return(status != 0 ? MagickTrue : MagickFalse);
929 }
930 \f
931 /*
932 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
933 %                                                                             %
934 %                                                                             %
935 %                                                                             %
936 %  G e t N u m b e r C o l o r s                                              %
937 %                                                                             %
938 %                                                                             %
939 %                                                                             %
940 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
941 %
942 %  GetNumberColors() returns the number of unique colors in an image.
943 %
944 %  The format of the GetNumberColors method is:
945 %
946 %      size_t GetNumberColors(const Image *image,FILE *file,
947 %        ExceptionInfo *exception)
948 %
949 %  A description of each parameter follows.
950 %
951 %    o image: the image.
952 %
953 %    o file:  Write a histogram of the color distribution to this file handle.
954 %
955 %    o exception: return any errors or warnings in this structure.
956 %
957 */
958
959 #if defined(__cplusplus) || defined(c_plusplus)
960 extern "C" {
961 #endif
962
963 static int HistogramCompare(const void *x,const void *y)
964 {
965   const PixelInfo
966     *color_1,
967     *color_2;
968
969   color_1=(const PixelInfo *) x;
970   color_2=(const PixelInfo *) y;
971   if (color_2->red != color_1->red)
972     return((int) color_1->red-(int) color_2->red);
973   if (color_2->green != color_1->green)
974     return((int) color_1->green-(int) color_2->green);
975   if (color_2->blue != color_1->blue)
976     return((int) color_1->blue-(int) color_2->blue);
977   return((int) color_2->count-(int) color_1->count);
978 }
979
980 #if defined(__cplusplus) || defined(c_plusplus)
981 }
982 #endif
983
984 MagickExport size_t GetNumberColors(const Image *image,FILE *file,
985   ExceptionInfo *exception)
986 {
987 #define HistogramImageTag  "Histogram/Image"
988
989   char
990     color[MagickPathExtent],
991     hex[MagickPathExtent],
992     tuple[MagickPathExtent];
993
994   PixelInfo
995     *histogram;
996
997   MagickBooleanType
998     status;
999
1000   PixelInfo
1001     pixel;
1002
1003   register PixelInfo
1004     *p;
1005
1006   register ssize_t
1007     i;
1008
1009   size_t
1010     number_colors;
1011
1012   number_colors=0;
1013   if (file == (FILE *) NULL)
1014     {
1015       CubeInfo
1016         *cube_info;
1017
1018       cube_info=ClassifyImageColors(image,exception);
1019       if (cube_info != (CubeInfo *) NULL)
1020         number_colors=cube_info->colors;
1021       cube_info=DestroyCubeInfo(image,cube_info);
1022       return(number_colors);
1023     }
1024   histogram=GetImageHistogram(image,&number_colors,exception);
1025   if (histogram == (PixelInfo *) NULL)
1026     return(number_colors);
1027   qsort((void *) histogram,(size_t) number_colors,sizeof(*histogram),
1028     HistogramCompare);
1029   GetPixelInfo(image,&pixel);
1030   p=histogram;
1031   status=MagickTrue;
1032   for (i=0; i < (ssize_t) number_colors; i++)
1033   {
1034     pixel=(*p);
1035     (void) CopyMagickString(tuple,"(",MagickPathExtent);
1036     ConcatenateColorComponent(&pixel,RedPixelChannel,X11Compliance,tuple);
1037     (void) ConcatenateMagickString(tuple,",",MagickPathExtent);
1038     ConcatenateColorComponent(&pixel,GreenPixelChannel,X11Compliance,tuple);
1039     (void) ConcatenateMagickString(tuple,",",MagickPathExtent);
1040     ConcatenateColorComponent(&pixel,BluePixelChannel,X11Compliance,tuple);
1041     if (pixel.colorspace == CMYKColorspace)
1042       {
1043         (void) ConcatenateMagickString(tuple,",",MagickPathExtent);
1044         ConcatenateColorComponent(&pixel,BlackPixelChannel,X11Compliance,
1045           tuple);
1046       }
1047     if (pixel.alpha_trait != UndefinedPixelTrait)
1048       {
1049         (void) ConcatenateMagickString(tuple,",",MagickPathExtent);
1050         ConcatenateColorComponent(&pixel,AlphaPixelChannel,X11Compliance,
1051           tuple);
1052       }
1053     (void) ConcatenateMagickString(tuple,")",MagickPathExtent);
1054     (void) QueryColorname(image,&pixel,SVGCompliance,color,exception);
1055     GetColorTuple(&pixel,MagickTrue,hex);
1056     (void) FormatLocaleFile(file,"%10.20g",(double) ((MagickOffsetType)
1057       p->count));
1058     (void) FormatLocaleFile(file,": %s %s %s\n",tuple,hex,color);
1059     if (image->progress_monitor != (MagickProgressMonitor) NULL)
1060       {
1061         MagickBooleanType
1062           proceed;
1063
1064         proceed=SetImageProgress(image,HistogramImageTag,(MagickOffsetType) i,
1065           number_colors);
1066         if (proceed == MagickFalse)
1067           status=MagickFalse;
1068       }
1069     p++;
1070   }
1071   (void) fflush(file);
1072   histogram=(PixelInfo *) RelinquishMagickMemory(histogram);
1073   if (status == MagickFalse)
1074     return(0);
1075   return(number_colors);
1076 }
1077 \f
1078 /*
1079 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1080 %                                                                             %
1081 %                                                                             %
1082 %                                                                             %
1083 %  U n i q u e I m a g e C o l o r s                                          %
1084 %                                                                             %
1085 %                                                                             %
1086 %                                                                             %
1087 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1088 %
1089 %  UniqueImageColors() returns the unique colors of an image.
1090 %
1091 %  The format of the UniqueImageColors method is:
1092 %
1093 %      Image *UniqueImageColors(const Image *image,ExceptionInfo *exception)
1094 %
1095 %  A description of each parameter follows.
1096 %
1097 %    o image: the image.
1098 %
1099 %    o exception: return any errors or warnings in this structure.
1100 %
1101 */
1102
1103 static void UniqueColorsToImage(Image *unique_image,CacheView *unique_view,
1104   CubeInfo *cube_info,const NodeInfo *node_info,ExceptionInfo *exception)
1105 {
1106 #define UniqueColorsImageTag  "UniqueColors/Image"
1107
1108   MagickBooleanType
1109     status;
1110
1111   register ssize_t
1112     i;
1113
1114   size_t
1115     number_children;
1116
1117   /*
1118     Traverse any children.
1119   */
1120   number_children=unique_image->alpha_trait == UndefinedPixelTrait ? 8UL : 16UL;
1121   for (i=0; i < (ssize_t) number_children; i++)
1122     if (node_info->child[i] != (NodeInfo *) NULL)
1123       UniqueColorsToImage(unique_image,unique_view,cube_info,
1124         node_info->child[i],exception);
1125   if (node_info->level == (MaxTreeDepth-1))
1126     {
1127       register PixelInfo
1128         *p;
1129
1130       register Quantum
1131         *restrict q;
1132
1133       status=MagickTrue;
1134       p=node_info->list;
1135       for (i=0; i < (ssize_t) node_info->number_unique; i++)
1136       {
1137         q=QueueCacheViewAuthenticPixels(unique_view,cube_info->x,0,1,1,
1138           exception);
1139         if (q == (Quantum *) NULL)
1140           continue;
1141         SetPixelRed(unique_image,ClampToQuantum(p->red),q);
1142         SetPixelGreen(unique_image,ClampToQuantum(p->green),q);
1143         SetPixelBlue(unique_image,ClampToQuantum(p->blue),q);
1144         SetPixelAlpha(unique_image,ClampToQuantum(p->alpha),q);
1145         if (unique_image->colorspace == CMYKColorspace)
1146           SetPixelBlack(unique_image,ClampToQuantum(p->black),q);
1147         if (SyncCacheViewAuthenticPixels(unique_view,exception) == MagickFalse)
1148           break;
1149         cube_info->x++;
1150         p++;
1151       }
1152       if (unique_image->progress_monitor != (MagickProgressMonitor) NULL)
1153         {
1154           MagickBooleanType
1155             proceed;
1156
1157           proceed=SetImageProgress(unique_image,UniqueColorsImageTag,
1158             cube_info->progress,cube_info->colors);
1159           if (proceed == MagickFalse)
1160             status=MagickFalse;
1161         }
1162       cube_info->progress++;
1163       if (status == MagickFalse)
1164         return;
1165     }
1166 }
1167
1168 MagickExport Image *UniqueImageColors(const Image *image,
1169   ExceptionInfo *exception)
1170 {
1171   CacheView
1172     *unique_view;
1173
1174   CubeInfo
1175     *cube_info;
1176
1177   Image
1178     *unique_image;
1179
1180   cube_info=ClassifyImageColors(image,exception);
1181   if (cube_info == (CubeInfo *) NULL)
1182     return((Image *) NULL);
1183   unique_image=CloneImage(image,cube_info->colors,1,MagickTrue,exception);
1184   if (unique_image == (Image *) NULL)
1185     return(unique_image);
1186   if (SetImageStorageClass(unique_image,DirectClass,exception) == MagickFalse)
1187     {
1188       unique_image=DestroyImage(unique_image);
1189       return((Image *) NULL);
1190     }
1191   unique_view=AcquireAuthenticCacheView(unique_image,exception);
1192   UniqueColorsToImage(unique_image,unique_view,cube_info,cube_info->root,
1193     exception);
1194   unique_view=DestroyCacheView(unique_view);
1195   cube_info=DestroyCubeInfo(image,cube_info);
1196   return(unique_image);
1197 }