2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
6 % SSSSS EEEEE GGGG M M EEEEE N N TTTTT %
7 % SS E G MM MM E NN N T %
8 % SSS EEE G GGG M M M EEE N N N T %
9 % SS E G G M M E N NN T %
10 % SSSSS EEEEE GGGG M M EEEEE N N T %
13 % MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means %
20 % Copyright 1999-2011 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
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. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Segment segments an image by analyzing the histograms of the color
37 % components and identifying units that are homogeneous with the fuzzy
38 % c-means technique. The scale-space filter analyzes the histograms of
39 % the three color components of the image and identifies a set of
40 % classes. The extents of each class is used to coarsely segment the
41 % image with thresholding. The color associated with each class is
42 % determined by the mean color of all pixels within the extents of a
43 % particular class. Finally, any unclassified pixels are assigned to
44 % the closest class with the fuzzy c-means technique.
46 % The fuzzy c-Means algorithm can be summarized as follows:
48 % o Build a histogram, one for each color component of the image.
50 % o For each histogram, successively apply the scale-space filter and
51 % build an interval tree of zero crossings in the second derivative
52 % at each scale. Analyze this scale-space ``fingerprint'' to
53 % determine which peaks and valleys in the histogram are most
56 % o The fingerprint defines intervals on the axis of the histogram.
57 % Each interval contains either a minima or a maxima in the original
58 % signal. If each color component lies within the maxima interval,
59 % that pixel is considered ``classified'' and is assigned an unique
62 % o Any pixel that fails to be classified in the above thresholding
63 % pass is classified using the fuzzy c-Means technique. It is
64 % assigned to one of the classes discovered in the histogram analysis
67 % The fuzzy c-Means technique attempts to cluster a pixel by finding
68 % the local minima of the generalized within group sum of squared error
69 % objective function. A pixel is assigned to the closest class of
70 % which the fuzzy membership has a maximum value.
72 % Segment is strongly based on software written by Andy Gallo,
73 % University of Delaware.
75 % The following reference was used in creating this program:
77 % Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation
78 % Algorithm Based on the Thresholding and the Fuzzy c-Means
79 % Techniques", Pattern Recognition, Volume 23, Number 9, pages
85 #include "magick/studio.h"
86 #include "magick/cache.h"
87 #include "magick/color.h"
88 #include "magick/colormap.h"
89 #include "magick/colorspace.h"
90 #include "magick/exception.h"
91 #include "magick/exception-private.h"
92 #include "magick/image.h"
93 #include "magick/image-private.h"
94 #include "magick/memory_.h"
95 #include "magick/monitor.h"
96 #include "magick/monitor-private.h"
97 #include "magick/quantize.h"
98 #include "magick/quantum.h"
99 #include "magick/quantum-private.h"
100 #include "magick/segment.h"
101 #include "magick/string_.h"
106 #define MaxDimension 3
107 #define DeltaTau 0.5f
108 #if defined(FastClassify)
109 #define WeightingExponent 2.0
110 #define SegmentPower(ratio) (ratio)
112 #define WeightingExponent 2.5
113 #define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0)));
118 Typedef declarations.
120 typedef struct _ExtentPacket
131 typedef struct _Cluster
146 typedef struct _IntervalTree
164 typedef struct _ZeroCrossing
175 Constant declarations.
187 static MagickRealType
188 OptimalTau(const ssize_t *,const double,const double,const double,
189 const double,short *);
192 DefineRegion(const short *,ExtentPacket *);
195 InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *),
196 ScaleSpace(const ssize_t *,const MagickRealType,MagickRealType *),
197 ZeroCrossHistogram(MagickRealType *,const MagickRealType,short *);
200 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
208 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
210 % Classify() defines one or more classes. Each pixel is thresholded to
211 % determine which class it belongs to. If the class is not identified it is
212 % assigned to the closest class based on the fuzzy c-Means technique.
214 % The format of the Classify method is:
216 % MagickBooleanType Classify(Image *image,short **extrema,
217 % const MagickRealType cluster_threshold,
218 % const MagickRealType weighting_exponent,
219 % const MagickBooleanType verbose)
221 % A description of each parameter follows.
223 % o image: the image.
225 % o extrema: Specifies a pointer to an array of integers. They
226 % represent the peaks and valleys of the histogram for each color
229 % o cluster_threshold: This MagickRealType represents the minimum number of
230 % pixels contained in a hexahedra before it can be considered valid
231 % (expressed as a percentage).
233 % o weighting_exponent: Specifies the membership weighting exponent.
235 % o verbose: A value greater than zero prints detailed information about
236 % the identified classes.
239 static MagickBooleanType Classify(Image *image,short **extrema,
240 const MagickRealType cluster_threshold,
241 const MagickRealType weighting_exponent,const MagickBooleanType verbose)
243 #define SegmentImageTag "Segment/Image"
274 register MagickRealType
287 cluster=(Cluster *) NULL;
288 head=(Cluster *) NULL;
289 (void) ResetMagickMemory(&red,0,sizeof(red));
290 (void) ResetMagickMemory(&green,0,sizeof(green));
291 (void) ResetMagickMemory(&blue,0,sizeof(blue));
292 while (DefineRegion(extrema[Red],&red) != 0)
295 while (DefineRegion(extrema[Green],&green) != 0)
298 while (DefineRegion(extrema[Blue],&blue) != 0)
301 Allocate a new class.
303 if (head != (Cluster *) NULL)
305 cluster->next=(Cluster *) AcquireMagickMemory(
306 sizeof(*cluster->next));
307 cluster=cluster->next;
311 cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
314 if (cluster == (Cluster *) NULL)
315 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
318 Initialize a new class.
322 cluster->green=green;
324 cluster->next=(Cluster *) NULL;
328 if (head == (Cluster *) NULL)
331 No classes were identified-- create one.
333 cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
334 if (cluster == (Cluster *) NULL)
335 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
338 Initialize a new class.
342 cluster->green=green;
344 cluster->next=(Cluster *) NULL;
348 Count the pixels for each cluster.
353 exception=(&image->exception);
354 image_view=AcquireCacheView(image);
355 for (y=0; y < (ssize_t) image->rows; y++)
357 register const PixelPacket
363 p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
364 if (p == (const PixelPacket *) NULL)
366 for (x=0; x < (ssize_t) image->columns; x++)
368 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
369 if (((ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p)) >=
370 (cluster->red.left-SafeMargin)) &&
371 ((ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p)) <=
372 (cluster->red.right+SafeMargin)) &&
373 ((ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p)) >=
374 (cluster->green.left-SafeMargin)) &&
375 ((ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p)) <=
376 (cluster->green.right+SafeMargin)) &&
377 ((ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p)) >=
378 (cluster->blue.left-SafeMargin)) &&
379 ((ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p)) <=
380 (cluster->blue.right+SafeMargin)))
386 cluster->red.center+=(MagickRealType) ScaleQuantumToChar(GetRedPixelComponent(p));
387 cluster->green.center+=(MagickRealType)
388 ScaleQuantumToChar(GetGreenPixelComponent(p));
389 cluster->blue.center+=(MagickRealType) ScaleQuantumToChar(GetBluePixelComponent(p));
395 if (image->progress_monitor != (MagickProgressMonitor) NULL)
400 #if defined(MAGICKCORE_OPENMP_SUPPORT)
401 #pragma omp critical (MagickCore_Classify)
403 proceed=SetImageProgress(image,SegmentImageTag,progress++,
405 if (proceed == MagickFalse)
409 image_view=DestroyCacheView(image_view);
411 Remove clusters that do not meet minimum cluster threshold.
416 for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
418 next_cluster=cluster->next;
419 if ((cluster->count > 0) &&
420 (cluster->count >= (count*cluster_threshold/100.0)))
426 cluster->red.center/=cluster->count;
427 cluster->green.center/=cluster->count;
428 cluster->blue.center/=cluster->count;
430 last_cluster=cluster;
439 last_cluster->next=next_cluster;
440 cluster=(Cluster *) RelinquishMagickMemory(cluster);
442 number_clusters=(size_t) count;
443 if (verbose != MagickFalse)
446 Print cluster statistics.
448 (void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n");
449 (void) FormatLocaleFile(stdout,"===================\n\n");
450 (void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double)
452 (void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double)
454 (void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n",
455 (double) number_clusters);
457 Print the total number of points per cluster.
459 (void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n");
460 (void) FormatLocaleFile(stdout,"=============================\n\n");
461 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
462 (void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double)
463 cluster->id,(double) cluster->count);
465 Print the cluster extents.
467 (void) FormatLocaleFile(stdout,
468 "\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension);
469 (void) FormatLocaleFile(stdout,"================");
470 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
472 (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
474 (void) FormatLocaleFile(stdout,
475 "%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double)
476 cluster->red.left,(double) cluster->red.right,(double)
477 cluster->green.left,(double) cluster->green.right,(double)
478 cluster->blue.left,(double) cluster->blue.right);
481 Print the cluster center values.
483 (void) FormatLocaleFile(stdout,
484 "\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension);
485 (void) FormatLocaleFile(stdout,"=====================");
486 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
488 (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
490 (void) FormatLocaleFile(stdout,"%g %g %g\n",(double)
491 cluster->red.center,(double) cluster->green.center,(double)
492 cluster->blue.center);
494 (void) FormatLocaleFile(stdout,"\n");
496 if (number_clusters > 256)
497 ThrowBinaryException(ImageError,"TooManyClusters",image->filename);
499 Speed up distance calculations.
501 squares=(MagickRealType *) AcquireQuantumMemory(513UL,sizeof(*squares));
502 if (squares == (MagickRealType *) NULL)
503 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
506 for (i=(-255); i <= 255; i++)
507 squares[i]=(MagickRealType) i*(MagickRealType) i;
509 Allocate image colormap.
511 if (AcquireImageColormap(image,number_clusters) == MagickFalse)
512 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
515 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
517 image->colormap[i].red=ScaleCharToQuantum((unsigned char)
518 (cluster->red.center+0.5));
519 image->colormap[i].green=ScaleCharToQuantum((unsigned char)
520 (cluster->green.center+0.5));
521 image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
522 (cluster->blue.center+0.5));
526 Do course grain classes.
528 exception=(&image->exception);
529 image_view=AcquireCacheView(image);
530 #if defined(MAGICKCORE_OPENMP_SUPPORT)
531 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
533 for (y=0; y < (ssize_t) image->rows; y++)
538 register const PixelPacket
550 if (status == MagickFalse)
552 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
553 if (q == (PixelPacket *) NULL)
558 indexes=GetCacheViewAuthenticIndexQueue(image_view);
559 for (x=0; x < (ssize_t) image->columns; x++)
561 SetIndexPixelComponent(indexes+x,0);
562 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
564 if (((ssize_t) ScaleQuantumToChar(q->red) >=
565 (cluster->red.left-SafeMargin)) &&
566 ((ssize_t) ScaleQuantumToChar(q->red) <=
567 (cluster->red.right+SafeMargin)) &&
568 ((ssize_t) ScaleQuantumToChar(q->green) >=
569 (cluster->green.left-SafeMargin)) &&
570 ((ssize_t) ScaleQuantumToChar(q->green) <=
571 (cluster->green.right+SafeMargin)) &&
572 ((ssize_t) ScaleQuantumToChar(q->blue) >=
573 (cluster->blue.left-SafeMargin)) &&
574 ((ssize_t) ScaleQuantumToChar(q->blue) <=
575 (cluster->blue.right+SafeMargin)))
580 SetIndexPixelComponent(indexes+x,cluster->id);
584 if (cluster == (Cluster *) NULL)
598 Compute fuzzy membership.
601 for (j=0; j < (ssize_t) image->colors; j++)
605 distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)-
606 (ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p))]+
607 squares[(ssize_t) ScaleQuantumToChar(q->green)-
608 (ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p))]+
609 squares[(ssize_t) ScaleQuantumToChar(q->blue)-
610 (ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p))];
611 numerator=distance_squared;
612 for (k=0; k < (ssize_t) image->colors; k++)
615 distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)-
616 (ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p))]+
617 squares[(ssize_t) ScaleQuantumToChar(q->green)-
618 (ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p))]+
619 squares[(ssize_t) ScaleQuantumToChar(q->blue)-
620 (ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p))];
621 ratio=numerator/distance_squared;
622 sum+=SegmentPower(ratio);
624 if ((sum != 0.0) && ((1.0/sum) > local_minima))
629 local_minima=1.0/sum;
630 SetIndexPixelComponent(indexes+x,j);
636 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
638 if (image->progress_monitor != (MagickProgressMonitor) NULL)
643 #if defined(MAGICKCORE_OPENMP_SUPPORT)
644 #pragma omp critical (MagickCore_Classify)
646 proceed=SetImageProgress(image,SegmentImageTag,progress++,
648 if (proceed == MagickFalse)
652 image_view=DestroyCacheView(image_view);
653 status&=SyncImage(image);
655 Relinquish resources.
657 for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
659 next_cluster=cluster->next;
660 cluster=(Cluster *) RelinquishMagickMemory(cluster);
663 free_squares=squares;
664 free_squares=(MagickRealType *) RelinquishMagickMemory(free_squares);
669 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
673 + C o n s o l i d a t e C r o s s i n g s %
677 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
679 % ConsolidateCrossings() guarantees that an even number of zero crossings
680 % always lie between two crossings.
682 % The format of the ConsolidateCrossings method is:
684 % ConsolidateCrossings(ZeroCrossing *zero_crossing,
685 % const size_t number_crossings)
687 % A description of each parameter follows.
689 % o zero_crossing: Specifies an array of structures of type ZeroCrossing.
691 % o number_crossings: This size_t specifies the number of elements
692 % in the zero_crossing array.
696 static inline ssize_t MagickAbsoluteValue(const ssize_t x)
703 static inline ssize_t MagickMax(const ssize_t x,const ssize_t y)
710 static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
717 static void ConsolidateCrossings(ZeroCrossing *zero_crossing,
718 const size_t number_crossings)
734 Consolidate zero crossings.
736 for (i=(ssize_t) number_crossings-1; i >= 0; i--)
737 for (j=0; j <= 255; j++)
739 if (zero_crossing[i].crossings[j] == 0)
742 Find the entry that is closest to j and still preserves the
743 property that there are an even number of crossings between
746 for (k=j-1; k > 0; k--)
747 if (zero_crossing[i+1].crossings[k] != 0)
751 for (k=j+1; k < 255; k++)
752 if (zero_crossing[i+1].crossings[k] != 0)
754 right=MagickMin(k,255);
756 K is the zero crossing just left of j.
758 for (k=j-1; k > 0; k--)
759 if (zero_crossing[i].crossings[k] != 0)
764 Check center for an even number of crossings between k and j.
767 if (zero_crossing[i+1].crossings[j] != 0)
770 for (l=k+1; l < center; l++)
771 if (zero_crossing[i+1].crossings[l] != 0)
773 if (((count % 2) == 0) && (center != k))
777 Check left for an even number of crossings between k and j.
782 for (l=k+1; l < left; l++)
783 if (zero_crossing[i+1].crossings[l] != 0)
785 if (((count % 2) == 0) && (left != k))
789 Check right for an even number of crossings between k and j.
794 for (l=k+1; l < right; l++)
795 if (zero_crossing[i+1].crossings[l] != 0)
797 if (((count % 2) == 0) && (right != k))
800 l=(ssize_t) zero_crossing[i].crossings[j];
801 zero_crossing[i].crossings[j]=0;
803 zero_crossing[i].crossings[correct]=(short) l;
808 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
812 + D e f i n e R e g i o n %
816 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
818 % DefineRegion() defines the left and right boundaries of a peak region.
820 % The format of the DefineRegion method is:
822 % ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
824 % A description of each parameter follows.
826 % o extrema: Specifies a pointer to an array of integers. They
827 % represent the peaks and valleys of the histogram for each color
830 % o extents: This pointer to an ExtentPacket represent the extends
831 % of a particular peak or valley of a color component.
834 static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
837 Initialize to default values.
843 Find the left side (maxima).
845 for ( ; extents->index <= 255; extents->index++)
846 if (extrema[extents->index] > 0)
848 if (extents->index > 255)
849 return(MagickFalse); /* no left side - no region exists */
850 extents->left=extents->index;
852 Find the right side (minima).
854 for ( ; extents->index <= 255; extents->index++)
855 if (extrema[extents->index] < 0)
857 extents->right=extents->index-1;
862 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
866 + D e r i v a t i v e H i s t o g r a m %
870 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
872 % DerivativeHistogram() determines the derivative of the histogram using
873 % central differencing.
875 % The format of the DerivativeHistogram method is:
877 % DerivativeHistogram(const MagickRealType *histogram,
878 % MagickRealType *derivative)
880 % A description of each parameter follows.
882 % o histogram: Specifies an array of MagickRealTypes representing the number
883 % of pixels for each intensity of a particular color component.
885 % o derivative: This array of MagickRealTypes is initialized by
886 % DerivativeHistogram to the derivative of the histogram using central
890 static void DerivativeHistogram(const MagickRealType *histogram,
891 MagickRealType *derivative)
898 Compute endpoints using second order polynomial interpolation.
901 derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]);
902 derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]);
904 Compute derivative using central differencing.
906 for (i=1; i < n; i++)
907 derivative[i]=(histogram[i+1]-histogram[i-1])/2.0;
912 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
916 + G e t I m a g e D y n a m i c T h r e s h o l d %
920 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
922 % GetImageDynamicThreshold() returns the dynamic threshold for an image.
924 % The format of the GetImageDynamicThreshold method is:
926 % MagickBooleanType GetImageDynamicThreshold(const Image *image,
927 % const double cluster_threshold,const double smooth_threshold,
928 % MagickPixelPacket *pixel,ExceptionInfo *exception)
930 % A description of each parameter follows.
932 % o image: the image.
934 % o cluster_threshold: This MagickRealType represents the minimum number of
935 % pixels contained in a hexahedra before it can be considered valid
936 % (expressed as a percentage).
938 % o smooth_threshold: the smoothing threshold eliminates noise in the second
939 % derivative of the histogram. As the value is increased, you can expect a
940 % smoother second derivative.
942 % o pixel: return the dynamic threshold here.
944 % o exception: return any errors or warnings in this structure.
947 MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image,
948 const double cluster_threshold,const double smooth_threshold,
949 MagickPixelPacket *pixel,ExceptionInfo *exception)
970 register const PixelPacket
978 *extrema[MaxDimension];
982 *histogram[MaxDimension],
986 Allocate histogram and extrema.
988 assert(image != (Image *) NULL);
989 assert(image->signature == MagickSignature);
990 if (image->debug != MagickFalse)
991 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
992 GetMagickPixelPacket(image,pixel);
993 for (i=0; i < MaxDimension; i++)
995 histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram));
996 extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram));
997 if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
999 for (i-- ; i >= 0; i--)
1001 extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
1002 histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
1004 (void) ThrowMagickException(exception,GetMagickModule(),
1005 ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
1006 return(MagickFalse);
1010 Initialize histogram.
1012 InitializeHistogram(image,histogram,exception);
1013 (void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau,
1014 (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]);
1015 (void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau,
1016 (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]);
1017 (void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau,
1018 (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]);
1022 cluster=(Cluster *) NULL;
1023 head=(Cluster *) NULL;
1024 (void) ResetMagickMemory(&red,0,sizeof(red));
1025 (void) ResetMagickMemory(&green,0,sizeof(green));
1026 (void) ResetMagickMemory(&blue,0,sizeof(blue));
1027 while (DefineRegion(extrema[Red],&red) != 0)
1030 while (DefineRegion(extrema[Green],&green) != 0)
1033 while (DefineRegion(extrema[Blue],&blue) != 0)
1036 Allocate a new class.
1038 if (head != (Cluster *) NULL)
1040 cluster->next=(Cluster *) AcquireMagickMemory(
1041 sizeof(*cluster->next));
1042 cluster=cluster->next;
1046 cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
1049 if (cluster == (Cluster *) NULL)
1051 (void) ThrowMagickException(exception,GetMagickModule(),
1052 ResourceLimitError,"MemoryAllocationFailed","`%s'",
1054 return(MagickFalse);
1057 Initialize a new class.
1061 cluster->green=green;
1063 cluster->next=(Cluster *) NULL;
1067 if (head == (Cluster *) NULL)
1070 No classes were identified-- create one.
1072 cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
1073 if (cluster == (Cluster *) NULL)
1075 (void) ThrowMagickException(exception,GetMagickModule(),
1076 ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
1077 return(MagickFalse);
1080 Initialize a new class.
1084 cluster->green=green;
1086 cluster->next=(Cluster *) NULL;
1090 Count the pixels for each cluster.
1093 for (y=0; y < (ssize_t) image->rows; y++)
1095 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1096 if (p == (const PixelPacket *) NULL)
1098 for (x=0; x < (ssize_t) image->columns; x++)
1100 for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
1101 if (((ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p)) >=
1102 (cluster->red.left-SafeMargin)) &&
1103 ((ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p)) <=
1104 (cluster->red.right+SafeMargin)) &&
1105 ((ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p)) >=
1106 (cluster->green.left-SafeMargin)) &&
1107 ((ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p)) <=
1108 (cluster->green.right+SafeMargin)) &&
1109 ((ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p)) >=
1110 (cluster->blue.left-SafeMargin)) &&
1111 ((ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p)) <=
1112 (cluster->blue.right+SafeMargin)))
1118 cluster->red.center+=(MagickRealType)
1119 ScaleQuantumToChar(GetRedPixelComponent(p));
1120 cluster->green.center+=(MagickRealType)
1121 ScaleQuantumToChar(GetGreenPixelComponent(p));
1122 cluster->blue.center+=(MagickRealType)
1123 ScaleQuantumToChar(GetBluePixelComponent(p));
1129 proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y,
1131 if (proceed == MagickFalse)
1135 Remove clusters that do not meet minimum cluster threshold.
1140 for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
1142 next_cluster=cluster->next;
1143 if ((cluster->count > 0) &&
1144 (cluster->count >= (count*cluster_threshold/100.0)))
1150 cluster->red.center/=cluster->count;
1151 cluster->green.center/=cluster->count;
1152 cluster->blue.center/=cluster->count;
1154 last_cluster=cluster;
1160 if (cluster == head)
1163 last_cluster->next=next_cluster;
1164 cluster=(Cluster *) RelinquishMagickMemory(cluster);
1171 for (cluster=object; cluster->next != (Cluster *) NULL; )
1173 if (cluster->count < object->count)
1175 cluster=cluster->next;
1177 background=head->next;
1178 for (cluster=background; cluster->next != (Cluster *) NULL; )
1180 if (cluster->count > background->count)
1182 cluster=cluster->next;
1185 threshold=(background->red.center+object->red.center)/2.0;
1186 pixel->red=(MagickRealType) ScaleCharToQuantum((unsigned char)
1188 threshold=(background->green.center+object->green.center)/2.0;
1189 pixel->green=(MagickRealType) ScaleCharToQuantum((unsigned char)
1191 threshold=(background->blue.center+object->blue.center)/2.0;
1192 pixel->blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
1195 Relinquish resources.
1197 for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
1199 next_cluster=cluster->next;
1200 cluster=(Cluster *) RelinquishMagickMemory(cluster);
1202 for (i=0; i < MaxDimension; i++)
1204 extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
1205 histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
1211 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1215 + I n i t i a l i z e H i s t o g r a m %
1219 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1221 % InitializeHistogram() computes the histogram for an image.
1223 % The format of the InitializeHistogram method is:
1225 % InitializeHistogram(const Image *image,ssize_t **histogram)
1227 % A description of each parameter follows.
1229 % o image: Specifies a pointer to an Image structure; returned from
1232 % o histogram: Specifies an array of integers representing the number
1233 % of pixels for each intensity of a particular color component.
1236 static void InitializeHistogram(const Image *image,ssize_t **histogram,
1237 ExceptionInfo *exception)
1239 register const PixelPacket
1250 Initialize histogram.
1252 for (i=0; i <= 255; i++)
1254 histogram[Red][i]=0;
1255 histogram[Green][i]=0;
1256 histogram[Blue][i]=0;
1258 for (y=0; y < (ssize_t) image->rows; y++)
1260 p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1261 if (p == (const PixelPacket *) NULL)
1263 for (x=0; x < (ssize_t) image->columns; x++)
1265 histogram[Red][(ssize_t) ScaleQuantumToChar(GetRedPixelComponent(p))]++;
1266 histogram[Green][(ssize_t) ScaleQuantumToChar(GetGreenPixelComponent(p))]++;
1267 histogram[Blue][(ssize_t) ScaleQuantumToChar(GetBluePixelComponent(p))]++;
1274 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1278 + I n i t i a l i z e I n t e r v a l T r e e %
1282 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1284 % InitializeIntervalTree() initializes an interval tree from the lists of
1287 % The format of the InitializeIntervalTree method is:
1289 % InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes,
1290 % IntervalTree *node)
1292 % A description of each parameter follows.
1294 % o zero_crossing: Specifies an array of structures of type ZeroCrossing.
1296 % o number_crossings: This size_t specifies the number of elements
1297 % in the zero_crossing array.
1301 static void InitializeList(IntervalTree **list,ssize_t *number_nodes,
1304 if (node == (IntervalTree *) NULL)
1306 if (node->child == (IntervalTree *) NULL)
1307 list[(*number_nodes)++]=node;
1308 InitializeList(list,number_nodes,node->sibling);
1309 InitializeList(list,number_nodes,node->child);
1312 static void MeanStability(IntervalTree *node)
1314 register IntervalTree
1317 if (node == (IntervalTree *) NULL)
1319 node->mean_stability=0.0;
1321 if (child != (IntervalTree *) NULL)
1326 register MagickRealType
1331 for ( ; child != (IntervalTree *) NULL; child=child->sibling)
1333 sum+=child->stability;
1336 node->mean_stability=sum/(MagickRealType) count;
1338 MeanStability(node->sibling);
1339 MeanStability(node->child);
1342 static void Stability(IntervalTree *node)
1344 if (node == (IntervalTree *) NULL)
1346 if (node->child == (IntervalTree *) NULL)
1347 node->stability=0.0;
1349 node->stability=node->tau-(node->child)->tau;
1350 Stability(node->sibling);
1351 Stability(node->child);
1354 static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing,
1355 const size_t number_crossings)
1373 Allocate interval tree.
1375 list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
1377 if (list == (IntervalTree **) NULL)
1378 return((IntervalTree *) NULL);
1380 The root is the entire histogram.
1382 root=(IntervalTree *) AcquireMagickMemory(sizeof(*root));
1383 root->child=(IntervalTree *) NULL;
1384 root->sibling=(IntervalTree *) NULL;
1388 for (i=(-1); i < (ssize_t) number_crossings; i++)
1391 Initialize list with all nodes with no children.
1394 InitializeList(list,&number_nodes,root);
1398 for (j=0; j < number_nodes; j++)
1403 for (k=head->left+1; k < head->right; k++)
1405 if (zero_crossing[i+1].crossings[k] != 0)
1409 node->child=(IntervalTree *) AcquireMagickMemory(
1410 sizeof(*node->child));
1415 node->sibling=(IntervalTree *) AcquireMagickMemory(
1416 sizeof(*node->sibling));
1419 node->tau=zero_crossing[i+1].tau;
1420 node->child=(IntervalTree *) NULL;
1421 node->sibling=(IntervalTree *) NULL;
1427 if (left != head->left)
1429 node->sibling=(IntervalTree *) AcquireMagickMemory(
1430 sizeof(*node->sibling));
1432 node->tau=zero_crossing[i+1].tau;
1433 node->child=(IntervalTree *) NULL;
1434 node->sibling=(IntervalTree *) NULL;
1436 node->right=head->right;
1441 Determine the stability: difference between a nodes tau and its child.
1443 Stability(root->child);
1444 MeanStability(root->child);
1445 list=(IntervalTree **) RelinquishMagickMemory(list);
1450 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1454 + O p t i m a l T a u %
1458 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1460 % OptimalTau() finds the optimal tau for each band of the histogram.
1462 % The format of the OptimalTau method is:
1464 % MagickRealType OptimalTau(const ssize_t *histogram,const double max_tau,
1465 % const double min_tau,const double delta_tau,
1466 % const double smooth_threshold,short *extrema)
1468 % A description of each parameter follows.
1470 % o histogram: Specifies an array of integers representing the number
1471 % of pixels for each intensity of a particular color component.
1473 % o extrema: Specifies a pointer to an array of integers. They
1474 % represent the peaks and valleys of the histogram for each color
1479 static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes,
1482 if (node == (IntervalTree *) NULL)
1484 if (node->stability >= node->mean_stability)
1486 list[(*number_nodes)++]=node;
1487 ActiveNodes(list,number_nodes,node->sibling);
1491 ActiveNodes(list,number_nodes,node->sibling);
1492 ActiveNodes(list,number_nodes,node->child);
1496 static void FreeNodes(IntervalTree *node)
1498 if (node == (IntervalTree *) NULL)
1500 FreeNodes(node->sibling);
1501 FreeNodes(node->child);
1502 node=(IntervalTree *) RelinquishMagickMemory(node);
1505 static MagickRealType OptimalTau(const ssize_t *histogram,const double max_tau,
1506 const double min_tau,const double delta_tau,const double smooth_threshold,
1542 Allocate interval tree.
1544 list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
1546 if (list == (IntervalTree **) NULL)
1549 Allocate zero crossing list.
1551 count=(size_t) ((max_tau-min_tau)/delta_tau)+2;
1552 zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count,
1553 sizeof(*zero_crossing));
1554 if (zero_crossing == (ZeroCrossing *) NULL)
1556 for (i=0; i < (ssize_t) count; i++)
1557 zero_crossing[i].tau=(-1.0);
1559 Initialize zero crossing list.
1561 derivative=(MagickRealType *) AcquireQuantumMemory(256,sizeof(*derivative));
1562 second_derivative=(MagickRealType *) AcquireQuantumMemory(256,
1563 sizeof(*second_derivative));
1564 if ((derivative == (MagickRealType *) NULL) ||
1565 (second_derivative == (MagickRealType *) NULL))
1566 ThrowFatalException(ResourceLimitFatalError,
1567 "UnableToAllocateDerivatives");
1569 for (tau=max_tau; tau >= min_tau; tau-=delta_tau)
1571 zero_crossing[i].tau=tau;
1572 ScaleSpace(histogram,tau,zero_crossing[i].histogram);
1573 DerivativeHistogram(zero_crossing[i].histogram,derivative);
1574 DerivativeHistogram(derivative,second_derivative);
1575 ZeroCrossHistogram(second_derivative,smooth_threshold,
1576 zero_crossing[i].crossings);
1580 Add an entry for the original histogram.
1582 zero_crossing[i].tau=0.0;
1583 for (j=0; j <= 255; j++)
1584 zero_crossing[i].histogram[j]=(MagickRealType) histogram[j];
1585 DerivativeHistogram(zero_crossing[i].histogram,derivative);
1586 DerivativeHistogram(derivative,second_derivative);
1587 ZeroCrossHistogram(second_derivative,smooth_threshold,
1588 zero_crossing[i].crossings);
1589 number_crossings=(size_t) i;
1590 derivative=(MagickRealType *) RelinquishMagickMemory(derivative);
1591 second_derivative=(MagickRealType *)
1592 RelinquishMagickMemory(second_derivative);
1594 Ensure the scale-space fingerprints form lines in scale-space, not loops.
1596 ConsolidateCrossings(zero_crossing,number_crossings);
1598 Force endpoints to be included in the interval.
1600 for (i=0; i <= (ssize_t) number_crossings; i++)
1602 for (j=0; j < 255; j++)
1603 if (zero_crossing[i].crossings[j] != 0)
1605 zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]);
1606 for (j=255; j > 0; j--)
1607 if (zero_crossing[i].crossings[j] != 0)
1609 zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]);
1612 Initialize interval tree.
1614 root=InitializeIntervalTree(zero_crossing,number_crossings);
1615 if (root == (IntervalTree *) NULL)
1618 Find active nodes: stability is greater (or equal) to the mean stability of
1622 ActiveNodes(list,&number_nodes,root->child);
1626 for (i=0; i <= 255; i++)
1628 for (i=0; i < number_nodes; i++)
1631 Find this tau in zero crossings list.
1635 for (j=0; j <= (ssize_t) number_crossings; j++)
1636 if (zero_crossing[j].tau == node->tau)
1639 Find the value of the peak.
1641 peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue :
1644 value=zero_crossing[k].histogram[index];
1645 for (x=node->left; x <= node->right; x++)
1647 if (peak != MagickFalse)
1649 if (zero_crossing[k].histogram[x] > value)
1651 value=zero_crossing[k].histogram[x];
1656 if (zero_crossing[k].histogram[x] < value)
1658 value=zero_crossing[k].histogram[x];
1662 for (x=node->left; x <= node->right; x++)
1666 if (peak != MagickFalse)
1667 extrema[x]=(short) index;
1669 extrema[x]=(short) (-index);
1673 Determine the average tau.
1676 for (i=0; i < number_nodes; i++)
1677 average_tau+=list[i]->tau;
1678 average_tau/=(MagickRealType) number_nodes;
1680 Relinquish resources.
1683 zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing);
1684 list=(IntervalTree **) RelinquishMagickMemory(list);
1685 return(average_tau);
1689 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1693 + S c a l e S p a c e %
1697 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1699 % ScaleSpace() performs a scale-space filter on the 1D histogram.
1701 % The format of the ScaleSpace method is:
1703 % ScaleSpace(const ssize_t *histogram,const MagickRealType tau,
1704 % MagickRealType *scale_histogram)
1706 % A description of each parameter follows.
1708 % o histogram: Specifies an array of MagickRealTypes representing the number
1709 % of pixels for each intensity of a particular color component.
1713 static void ScaleSpace(const ssize_t *histogram,const MagickRealType tau,
1714 MagickRealType *scale_histogram)
1726 gamma=(MagickRealType *) AcquireQuantumMemory(256,sizeof(*gamma));
1727 if (gamma == (MagickRealType *) NULL)
1728 ThrowFatalException(ResourceLimitFatalError,
1729 "UnableToAllocateGammaMap");
1730 alpha=1.0/(tau*sqrt(2.0*MagickPI));
1731 beta=(-1.0/(2.0*tau*tau));
1732 for (x=0; x <= 255; x++)
1734 for (x=0; x <= 255; x++)
1736 gamma[x]=exp((double) beta*x*x);
1737 if (gamma[x] < MagickEpsilon)
1740 for (x=0; x <= 255; x++)
1743 for (u=0; u <= 255; u++)
1744 sum+=(MagickRealType) histogram[u]*gamma[MagickAbsoluteValue(x-u)];
1745 scale_histogram[x]=alpha*sum;
1747 gamma=(MagickRealType *) RelinquishMagickMemory(gamma);
1751 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1755 % S e g m e n t I m a g e %
1759 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1761 % SegmentImage() segment an image by analyzing the histograms of the color
1762 % components and identifying units that are homogeneous with the fuzzy
1763 % C-means technique.
1765 % The format of the SegmentImage method is:
1767 % MagickBooleanType SegmentImage(Image *image,
1768 % const ColorspaceType colorspace,const MagickBooleanType verbose,
1769 % const double cluster_threshold,const double smooth_threshold)
1771 % A description of each parameter follows.
1773 % o image: the image.
1775 % o colorspace: Indicate the colorspace.
1777 % o verbose: Set to MagickTrue to print detailed information about the
1778 % identified classes.
1780 % o cluster_threshold: This represents the minimum number of pixels
1781 % contained in a hexahedra before it can be considered valid (expressed
1784 % o smooth_threshold: the smoothing threshold eliminates noise in the second
1785 % derivative of the histogram. As the value is increased, you can expect a
1786 % smoother second derivative.
1789 MagickExport MagickBooleanType SegmentImage(Image *image,
1790 const ColorspaceType colorspace,const MagickBooleanType verbose,
1791 const double cluster_threshold,const double smooth_threshold)
1800 *extrema[MaxDimension];
1803 *histogram[MaxDimension];
1806 Allocate histogram and extrema.
1808 assert(image != (Image *) NULL);
1809 assert(image->signature == MagickSignature);
1810 if (image->debug != MagickFalse)
1811 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1812 for (i=0; i < MaxDimension; i++)
1814 histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram));
1815 extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema));
1816 if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
1818 for (i-- ; i >= 0; i--)
1820 extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
1821 histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
1823 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
1827 if (colorspace != RGBColorspace)
1828 (void) TransformImageColorspace(image,colorspace);
1830 Initialize histogram.
1832 InitializeHistogram(image,histogram,&image->exception);
1833 (void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau,
1834 smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]);
1835 (void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau,
1836 smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]);
1837 (void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau,
1838 smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]);
1840 Classify using the fuzzy c-Means technique.
1842 status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose);
1843 if (colorspace != RGBColorspace)
1844 (void) TransformImageColorspace(image,colorspace);
1846 Relinquish resources.
1848 for (i=0; i < MaxDimension; i++)
1850 extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
1851 histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
1857 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1861 + Z e r o C r o s s H i s t o g r a m %
1865 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1867 % ZeroCrossHistogram() find the zero crossings in a histogram and marks
1868 % directions as: 1 is negative to positive; 0 is zero crossing; and -1
1869 % is positive to negative.
1871 % The format of the ZeroCrossHistogram method is:
1873 % ZeroCrossHistogram(MagickRealType *second_derivative,
1874 % const MagickRealType smooth_threshold,short *crossings)
1876 % A description of each parameter follows.
1878 % o second_derivative: Specifies an array of MagickRealTypes representing the
1879 % second derivative of the histogram of a particular color component.
1881 % o crossings: This array of integers is initialized with
1882 % -1, 0, or 1 representing the slope of the first derivative of the
1883 % of a particular color component.
1886 static void ZeroCrossHistogram(MagickRealType *second_derivative,
1887 const MagickRealType smooth_threshold,short *crossings)
1896 Merge low numbers to zero to help prevent noise.
1898 for (i=0; i <= 255; i++)
1899 if ((second_derivative[i] < smooth_threshold) &&
1900 (second_derivative[i] >= -smooth_threshold))
1901 second_derivative[i]=0.0;
1903 Mark zero crossings.
1906 for (i=0; i <= 255; i++)
1909 if (second_derivative[i] < 0.0)
1916 if (second_derivative[i] > 0.0)