]> granicus.if.org Git - imagemagick/blob - MagickCore/morphology.c
(no commit message)
[imagemagick] / MagickCore / morphology.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %    M   M    OOO    RRRR   PPPP   H   H   OOO   L       OOO    GGGG  Y   Y   %
7 %    MM MM   O   O   R   R  P   P  H   H  O   O  L      O   O  G       Y Y    %
8 %    M M M   O   O   RRRR   PPPP   HHHHH  O   O  L      O   O  G GGG    Y     %
9 %    M   M   O   O   R R    P      H   H  O   O  L      O   O  G   G    Y     %
10 %    M   M    OOO    R  R   P      H   H   OOO   LLLLL   OOO    GGG     Y     %
11 %                                                                             %
12 %                                                                             %
13 %                        MagickCore Morphology Methods                        %
14 %                                                                             %
15 %                              Software Design                                %
16 %                              Anthony Thyssen                                %
17 %                               January 2010                                  %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2012 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 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 % Morpology is the the application of various kernels, of any size and even
37 % shape, to a image in various ways (typically binary, but not always).
38 %
39 % Convolution (weighted sum or average) is just one specific type of
40 % morphology. Just one that is very common for image bluring and sharpening
41 % effects.  Not only 2D Gaussian blurring, but also 2-pass 1D Blurring.
42 %
43 % This module provides not only a general morphology function, and the ability
44 % to apply more advanced or iterative morphologies, but also functions for the
45 % generation of many different types of kernel arrays from user supplied
46 % arguments. Prehaps even the generation of a kernel from a small image.
47 */
48 \f
49 /*
50   Include declarations.
51 */
52 #include "MagickCore/studio.h"
53 #include "MagickCore/artifact.h"
54 #include "MagickCore/cache-view.h"
55 #include "MagickCore/color-private.h"
56 #include "MagickCore/enhance.h"
57 #include "MagickCore/exception.h"
58 #include "MagickCore/exception-private.h"
59 #include "MagickCore/gem.h"
60 #include "MagickCore/gem-private.h"
61 #include "MagickCore/hashmap.h"
62 #include "MagickCore/image.h"
63 #include "MagickCore/image-private.h"
64 #include "MagickCore/list.h"
65 #include "MagickCore/magick.h"
66 #include "MagickCore/memory_.h"
67 #include "MagickCore/monitor-private.h"
68 #include "MagickCore/morphology.h"
69 #include "MagickCore/morphology-private.h"
70 #include "MagickCore/option.h"
71 #include "MagickCore/pixel-accessor.h"
72 #include "MagickCore/prepress.h"
73 #include "MagickCore/quantize.h"
74 #include "MagickCore/resource_.h"
75 #include "MagickCore/registry.h"
76 #include "MagickCore/semaphore.h"
77 #include "MagickCore/splay-tree.h"
78 #include "MagickCore/statistic.h"
79 #include "MagickCore/string_.h"
80 #include "MagickCore/string-private.h"
81 #include "MagickCore/token.h"
82 #include "MagickCore/utility.h"
83 #include "MagickCore/utility-private.h"
84 \f
85
86 /*
87 ** The following test is for special floating point numbers of value NaN (not
88 ** a number), that may be used within a Kernel Definition.  NaN's are defined
89 ** as part of the IEEE standard for floating point number representation.
90 **
91 ** These are used as a Kernel value to mean that this kernel position is not
92 ** part of the kernel neighbourhood for convolution or morphology processing,
93 ** and thus should be ignored.  This allows the use of 'shaped' kernels.
94 **
95 ** The special properity that two NaN's are never equal, even if they are from
96 ** the same variable allow you to test if a value is special NaN value.
97 **
98 ** This macro  IsNaN() is thus is only true if the value given is NaN.
99 */
100 #define IsNan(a)   ((a)!=(a))
101
102 /*
103   Other global definitions used by module.
104 */
105 static inline double MagickMin(const double x,const double y)
106 {
107   return( x < y ? x : y);
108 }
109 static inline double MagickMax(const double x,const double y)
110 {
111   return( x > y ? x : y);
112 }
113 #define Minimize(assign,value) assign=MagickMin(assign,value)
114 #define Maximize(assign,value) assign=MagickMax(assign,value)
115
116 /* Currently these are only internal to this module */
117 static void
118   CalcKernelMetaData(KernelInfo *),
119   ExpandMirrorKernelInfo(KernelInfo *),
120   ExpandRotateKernelInfo(KernelInfo *, const double),
121   RotateKernelInfo(KernelInfo *, double);
122 \f
123
124 /* Quick function to find last kernel in a kernel list */
125 static inline KernelInfo *LastKernelInfo(KernelInfo *kernel)
126 {
127   while (kernel->next != (KernelInfo *) NULL)
128     kernel = kernel->next;
129   return(kernel);
130 }
131
132 /*
133 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
134 %                                                                             %
135 %                                                                             %
136 %                                                                             %
137 %     A c q u i r e K e r n e l I n f o                                       %
138 %                                                                             %
139 %                                                                             %
140 %                                                                             %
141 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
142 %
143 %  AcquireKernelInfo() takes the given string (generally supplied by the
144 %  user) and converts it into a Morphology/Convolution Kernel.  This allows
145 %  users to specify a kernel from a number of pre-defined kernels, or to fully
146 %  specify their own kernel for a specific Convolution or Morphology
147 %  Operation.
148 %
149 %  The kernel so generated can be any rectangular array of floating point
150 %  values (doubles) with the 'control point' or 'pixel being affected'
151 %  anywhere within that array of values.
152 %
153 %  Previously IM was restricted to a square of odd size using the exact
154 %  center as origin, this is no longer the case, and any rectangular kernel
155 %  with any value being declared the origin. This in turn allows the use of
156 %  highly asymmetrical kernels.
157 %
158 %  The floating point values in the kernel can also include a special value
159 %  known as 'nan' or 'not a number' to indicate that this value is not part
160 %  of the kernel array. This allows you to shaped the kernel within its
161 %  rectangular area. That is 'nan' values provide a 'mask' for the kernel
162 %  shape.  However at least one non-nan value must be provided for correct
163 %  working of a kernel.
164 %
165 %  The returned kernel should be freed using the DestroyKernelInfo() when you
166 %  are finished with it.  Do not free this memory yourself.
167 %
168 %  Input kernel defintion strings can consist of any of three types.
169 %
170 %    "name:args[[@><]"
171 %         Select from one of the built in kernels, using the name and
172 %         geometry arguments supplied.  See AcquireKernelBuiltIn()
173 %
174 %    "WxH[+X+Y][@><]:num, num, num ..."
175 %         a kernel of size W by H, with W*H floating point numbers following.
176 %         the 'center' can be optionally be defined at +X+Y (such that +0+0
177 %         is top left corner). If not defined the pixel in the center, for
178 %         odd sizes, or to the immediate top or left of center for even sizes
179 %         is automatically selected.
180 %
181 %    "num, num, num, num, ..."
182 %         list of floating point numbers defining an 'old style' odd sized
183 %         square kernel.  At least 9 values should be provided for a 3x3
184 %         square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc.
185 %         Values can be space or comma separated.  This is not recommended.
186 %
187 %  You can define a 'list of kernels' which can be used by some morphology
188 %  operators A list is defined as a semi-colon separated list kernels.
189 %
190 %     " kernel ; kernel ; kernel ; "
191 %
192 %  Any extra ';' characters, at start, end or between kernel defintions are
193 %  simply ignored.
194 %
195 %  The special flags will expand a single kernel, into a list of rotated
196 %  kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree
197 %  cyclic rotations, while a '>' will generate a list of 90-degree rotations.
198 %  The '<' also exands using 90-degree rotates, but giving a 180-degree
199 %  reflected kernel before the +/- 90-degree rotations, which can be important
200 %  for Thinning operations.
201 %
202 %  Note that 'name' kernels will start with an alphabetic character while the
203 %  new kernel specification has a ':' character in its specification string.
204 %  If neither is the case, it is assumed an old style of a simple list of
205 %  numbers generating a odd-sized square kernel has been given.
206 %
207 %  The format of the AcquireKernal method is:
208 %
209 %      KernelInfo *AcquireKernelInfo(const char *kernel_string)
210 %
211 %  A description of each parameter follows:
212 %
213 %    o kernel_string: the Morphology/Convolution kernel wanted.
214 %
215 */
216
217 /* This was separated so that it could be used as a separate
218 ** array input handling function, such as for -color-matrix
219 */
220 static KernelInfo *ParseKernelArray(const char *kernel_string)
221 {
222   KernelInfo
223     *kernel;
224
225   char
226     token[MaxTextExtent];
227
228   const char
229     *p,
230     *end;
231
232   register ssize_t
233     i;
234
235   double
236     nan = sqrt((double)-1.0);  /* Special Value : Not A Number */
237
238   MagickStatusType
239     flags;
240
241   GeometryInfo
242     args;
243
244   kernel=(KernelInfo *) AcquireQuantumMemory(1,sizeof(*kernel));
245   if (kernel == (KernelInfo *)NULL)
246     return(kernel);
247   (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
248   kernel->minimum = kernel->maximum = kernel->angle = 0.0;
249   kernel->negative_range = kernel->positive_range = 0.0;
250   kernel->type = UserDefinedKernel;
251   kernel->next = (KernelInfo *) NULL;
252   kernel->signature = MagickSignature;
253   if (kernel_string == (const char *) NULL)
254     return(kernel);
255
256   /* find end of this specific kernel definition string */
257   end = strchr(kernel_string, ';');
258   if ( end == (char *) NULL )
259     end = strchr(kernel_string, '\0');
260
261   /* clear flags - for Expanding kernel lists thorugh rotations */
262    flags = NoValue;
263
264   /* Has a ':' in argument - New user kernel specification
265      FUTURE: this split on ':' could be done by StringToken()
266    */
267   p = strchr(kernel_string, ':');
268   if ( p != (char *) NULL && p < end)
269     {
270       /* ParseGeometry() needs the geometry separated! -- Arrgghh */
271       memcpy(token, kernel_string, (size_t) (p-kernel_string));
272       token[p-kernel_string] = '\0';
273       SetGeometryInfo(&args);
274       flags = ParseGeometry(token, &args);
275
276       /* Size handling and checks of geometry settings */
277       if ( (flags & WidthValue) == 0 ) /* if no width then */
278         args.rho = args.sigma;         /* then  width = height */
279       if ( args.rho < 1.0 )            /* if width too small */
280          args.rho = 1.0;               /* then  width = 1 */
281       if ( args.sigma < 1.0 )          /* if height too small */
282         args.sigma = args.rho;         /* then  height = width */
283       kernel->width = (size_t)args.rho;
284       kernel->height = (size_t)args.sigma;
285
286       /* Offset Handling and Checks */
287       if ( args.xi  < 0.0 || args.psi < 0.0 )
288         return(DestroyKernelInfo(kernel));
289       kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi
290                                         : (ssize_t) (kernel->width-1)/2;
291       kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi
292                                         : (ssize_t) (kernel->height-1)/2;
293       if ( kernel->x >= (ssize_t) kernel->width ||
294            kernel->y >= (ssize_t) kernel->height )
295         return(DestroyKernelInfo(kernel));
296
297       p++; /* advance beyond the ':' */
298     }
299   else
300     { /* ELSE - Old old specification, forming odd-square kernel */
301       /* count up number of values given */
302       p=(const char *) kernel_string;
303       while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
304         p++;  /* ignore "'" chars for convolve filter usage - Cristy */
305       for (i=0; p < end; i++)
306       {
307         GetMagickToken(p,&p,token);
308         if (*token == ',')
309           GetMagickToken(p,&p,token);
310       }
311       /* set the size of the kernel - old sized square */
312       kernel->width = kernel->height= (size_t) sqrt((double) i+1.0);
313       kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
314       p=(const char *) kernel_string;
315       while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
316         p++;  /* ignore "'" chars for convolve filter usage - Cristy */
317     }
318
319   /* Read in the kernel values from rest of input string argument */
320   kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
321     kernel->height*sizeof(*kernel->values));
322   if (kernel->values == (MagickRealType *) NULL)
323     return(DestroyKernelInfo(kernel));
324   kernel->minimum = +MagickHuge;
325   kernel->maximum = -MagickHuge;
326   kernel->negative_range = kernel->positive_range = 0.0;
327   for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++)
328   {
329     GetMagickToken(p,&p,token);
330     if (*token == ',')
331       GetMagickToken(p,&p,token);
332     if (    LocaleCompare("nan",token) == 0
333         || LocaleCompare("-",token) == 0 ) {
334       kernel->values[i] = nan; /* this value is not part of neighbourhood */
335     }
336     else {
337       kernel->values[i] = StringToDouble(token,(char **) NULL);
338       ( kernel->values[i] < 0)
339           ?  ( kernel->negative_range += kernel->values[i] )
340           :  ( kernel->positive_range += kernel->values[i] );
341       Minimize(kernel->minimum, kernel->values[i]);
342       Maximize(kernel->maximum, kernel->values[i]);
343     }
344   }
345
346   /* sanity check -- no more values in kernel definition */
347   GetMagickToken(p,&p,token);
348   if ( *token != '\0' && *token != ';' && *token != '\'' )
349     return(DestroyKernelInfo(kernel));
350
351 #if 0
352   /* this was the old method of handling a incomplete kernel */
353   if ( i < (ssize_t) (kernel->width*kernel->height) ) {
354     Minimize(kernel->minimum, kernel->values[i]);
355     Maximize(kernel->maximum, kernel->values[i]);
356     for ( ; i < (ssize_t) (kernel->width*kernel->height); i++)
357       kernel->values[i]=0.0;
358   }
359 #else
360   /* Number of values for kernel was not enough - Report Error */
361   if ( i < (ssize_t) (kernel->width*kernel->height) )
362     return(DestroyKernelInfo(kernel));
363 #endif
364
365   /* check that we recieved at least one real (non-nan) value! */
366   if ( kernel->minimum == MagickHuge )
367     return(DestroyKernelInfo(kernel));
368
369   if ( (flags & AreaValue) != 0 )         /* '@' symbol in kernel size */
370     ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */
371   else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
372     ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */
373   else if ( (flags & LessValue) != 0 )    /* '<' symbol in kernel args */
374     ExpandMirrorKernelInfo(kernel);       /* 90 degree mirror rotate */
375
376   return(kernel);
377 }
378
379 static KernelInfo *ParseKernelName(const char *kernel_string)
380 {
381   char
382     token[MaxTextExtent];
383
384   const char
385     *p,
386     *end;
387
388   GeometryInfo
389     args;
390
391   KernelInfo
392     *kernel;
393
394   MagickStatusType
395     flags;
396
397   ssize_t
398     type;
399
400   /* Parse special 'named' kernel */
401   GetMagickToken(kernel_string,&p,token);
402   type=ParseCommandOption(MagickKernelOptions,MagickFalse,token);
403   if ( type < 0 || type == UserDefinedKernel )
404     return((KernelInfo *)NULL);  /* not a valid named kernel */
405
406   while (((isspace((int) ((unsigned char) *p)) != 0) ||
407           (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
408     p++;
409
410   end = strchr(p, ';'); /* end of this kernel defintion */
411   if ( end == (char *) NULL )
412     end = strchr(p, '\0');
413
414   /* ParseGeometry() needs the geometry separated! -- Arrgghh */
415   memcpy(token, p, (size_t) (end-p));
416   token[end-p] = '\0';
417   SetGeometryInfo(&args);
418   flags = ParseGeometry(token, &args);
419
420 #if 0
421   /* For Debugging Geometry Input */
422   (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
423     flags, args.rho, args.sigma, args.xi, args.psi );
424 #endif
425
426   /* special handling of missing values in input string */
427   switch( type ) {
428     /* Shape Kernel Defaults */
429     case UnityKernel:
430       if ( (flags & WidthValue) == 0 )
431         args.rho = 1.0;    /* Default scale = 1.0, zero is valid */
432       break;
433     case SquareKernel:
434     case DiamondKernel:
435     case OctagonKernel:
436     case DiskKernel:
437     case PlusKernel:
438     case CrossKernel:
439       if ( (flags & HeightValue) == 0 )
440         args.sigma = 1.0;    /* Default scale = 1.0, zero is valid */
441       break;
442     case RingKernel:
443       if ( (flags & XValue) == 0 )
444         args.xi = 1.0;       /* Default scale = 1.0, zero is valid */
445       break;
446     case RectangleKernel:    /* Rectangle - set size defaults */
447       if ( (flags & WidthValue) == 0 ) /* if no width then */
448         args.rho = args.sigma;         /* then  width = height */
449       if ( args.rho < 1.0 )            /* if width too small */
450           args.rho = 3;                /* then  width = 3 */
451       if ( args.sigma < 1.0 )          /* if height too small */
452         args.sigma = args.rho;         /* then  height = width */
453       if ( (flags & XValue) == 0 )     /* center offset if not defined */
454         args.xi = (double)(((ssize_t)args.rho-1)/2);
455       if ( (flags & YValue) == 0 )
456         args.psi = (double)(((ssize_t)args.sigma-1)/2);
457       break;
458     /* Distance Kernel Defaults */
459     case ChebyshevKernel:
460     case ManhattanKernel:
461     case OctagonalKernel:
462     case EuclideanKernel:
463       if ( (flags & HeightValue) == 0 )           /* no distance scale */
464         args.sigma = 100.0;                       /* default distance scaling */
465       else if ( (flags & AspectValue ) != 0 )     /* '!' flag */
466         args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */
467       else if ( (flags & PercentValue ) != 0 )    /* '%' flag */
468         args.sigma *= QuantumRange/100.0;         /* percentage of color range */
469       break;
470     default:
471       break;
472   }
473
474   kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args);
475   if ( kernel == (KernelInfo *) NULL )
476     return(kernel);
477
478   /* global expand to rotated kernel list - only for single kernels */
479   if ( kernel->next == (KernelInfo *) NULL ) {
480     if ( (flags & AreaValue) != 0 )         /* '@' symbol in kernel args */
481       ExpandRotateKernelInfo(kernel, 45.0);
482     else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
483       ExpandRotateKernelInfo(kernel, 90.0);
484     else if ( (flags & LessValue) != 0 )    /* '<' symbol in kernel args */
485       ExpandMirrorKernelInfo(kernel);
486   }
487
488   return(kernel);
489 }
490
491 MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string)
492 {
493
494   KernelInfo
495     *kernel,
496     *new_kernel;
497
498   char
499     token[MaxTextExtent];
500
501   const char
502     *p;
503
504   size_t
505     kernel_number;
506
507   if (kernel_string == (const char *) NULL)
508     return(ParseKernelArray(kernel_string));
509   p = kernel_string;
510   kernel = NULL;
511   kernel_number = 0;
512
513   while ( GetMagickToken(p,NULL,token),  *token != '\0' ) {
514
515     /* ignore extra or multiple ';' kernel separators */
516     if ( *token != ';' ) {
517
518       /* tokens starting with alpha is a Named kernel */
519       if (isalpha((int) *token) != 0)
520         new_kernel = ParseKernelName(p);
521       else /* otherwise a user defined kernel array */
522         new_kernel = ParseKernelArray(p);
523
524       /* Error handling -- this is not proper error handling! */
525       if ( new_kernel == (KernelInfo *) NULL ) {
526         (void) FormatLocaleFile(stderr, "Failed to parse kernel number #%.20g\n",
527           (double) kernel_number);
528         if ( kernel != (KernelInfo *) NULL )
529           kernel=DestroyKernelInfo(kernel);
530         return((KernelInfo *) NULL);
531       }
532
533       /* initialise or append the kernel list */
534       if ( kernel == (KernelInfo *) NULL )
535         kernel = new_kernel;
536       else
537         LastKernelInfo(kernel)->next = new_kernel;
538     }
539
540     /* look for the next kernel in list */
541     p = strchr(p, ';');
542     if ( p == (char *) NULL )
543       break;
544     p++;
545
546   }
547   return(kernel);
548 }
549
550 \f
551 /*
552 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
553 %                                                                             %
554 %                                                                             %
555 %                                                                             %
556 %     A c q u i r e K e r n e l B u i l t I n                                 %
557 %                                                                             %
558 %                                                                             %
559 %                                                                             %
560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
561 %
562 %  AcquireKernelBuiltIn() returned one of the 'named' built-in types of
563 %  kernels used for special purposes such as gaussian blurring, skeleton
564 %  pruning, and edge distance determination.
565 %
566 %  They take a KernelType, and a set of geometry style arguments, which were
567 %  typically decoded from a user supplied string, or from a more complex
568 %  Morphology Method that was requested.
569 %
570 %  The format of the AcquireKernalBuiltIn method is:
571 %
572 %      KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
573 %           const GeometryInfo args)
574 %
575 %  A description of each parameter follows:
576 %
577 %    o type: the pre-defined type of kernel wanted
578 %
579 %    o args: arguments defining or modifying the kernel
580 %
581 %  Convolution Kernels
582 %
583 %    Unity
584 %       The a No-Op or Scaling single element kernel.
585 %
586 %    Gaussian:{radius},{sigma}
587 %       Generate a two-dimensional gaussian kernel, as used by -gaussian.
588 %       The sigma for the curve is required.  The resulting kernel is
589 %       normalized,
590 %
591 %       If 'sigma' is zero, you get a single pixel on a field of zeros.
592 %
593 %       NOTE: that the 'radius' is optional, but if provided can limit (clip)
594 %       the final size of the resulting kernel to a square 2*radius+1 in size.
595 %       The radius should be at least 2 times that of the sigma value, or
596 %       sever clipping and aliasing may result.  If not given or set to 0 the
597 %       radius will be determined so as to produce the best minimal error
598 %       result, which is usally much larger than is normally needed.
599 %
600 %    LoG:{radius},{sigma}
601 %        "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
602 %        The supposed ideal edge detection, zero-summing kernel.
603 %
604 %        An alturnative to this kernel is to use a "DoG" with a sigma ratio of
605 %        approx 1.6 (according to wikipedia).
606 %
607 %    DoG:{radius},{sigma1},{sigma2}
608 %        "Difference of Gaussians" Kernel.
609 %        As "Gaussian" but with a gaussian produced by 'sigma2' subtracted
610 %        from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1.
611 %        The result is a zero-summing kernel.
612 %
613 %    Blur:{radius},{sigma}[,{angle}]
614 %       Generates a 1 dimensional or linear gaussian blur, at the angle given
615 %       (current restricted to orthogonal angles).  If a 'radius' is given the
616 %       kernel is clipped to a width of 2*radius+1.  Kernel can be rotated
617 %       by a 90 degree angle.
618 %
619 %       If 'sigma' is zero, you get a single pixel on a field of zeros.
620 %
621 %       Note that two convolutions with two "Blur" kernels perpendicular to
622 %       each other, is equivalent to a far larger "Gaussian" kernel with the
623 %       same sigma value, However it is much faster to apply. This is how the
624 %       "-blur" operator actually works.
625 %
626 %    Comet:{width},{sigma},{angle}
627 %       Blur in one direction only, much like how a bright object leaves
628 %       a comet like trail.  The Kernel is actually half a gaussian curve,
629 %       Adding two such blurs in opposite directions produces a Blur Kernel.
630 %       Angle can be rotated in multiples of 90 degrees.
631 %
632 %       Note that the first argument is the width of the kernel and not the
633 %       radius of the kernel.
634 %
635 %    # Still to be implemented...
636 %    #
637 %    # Filter2D
638 %    # Filter1D
639 %    #    Set kernel values using a resize filter, and given scale (sigma)
640 %    #    Cylindrical or Linear.   Is this possible with an image?
641 %    #
642 %
643 %  Named Constant Convolution Kernels
644 %
645 %  All these are unscaled, zero-summing kernels by default. As such for
646 %  non-HDRI version of ImageMagick some form of normalization, user scaling,
647 %  and biasing the results is recommended, to prevent the resulting image
648 %  being 'clipped'.
649 %
650 %  The 3x3 kernels (most of these) can be circularly rotated in multiples of
651 %  45 degrees to generate the 8 angled varients of each of the kernels.
652 %
653 %    Laplacian:{type}
654 %      Discrete Lapacian Kernels, (without normalization)
655 %        Type 0 :  3x3 with center:8 surounded by -1  (8 neighbourhood)
656 %        Type 1 :  3x3 with center:4 edge:-1 corner:0 (4 neighbourhood)
657 %        Type 2 :  3x3 with center:4 edge:1 corner:-2
658 %        Type 3 :  3x3 with center:4 edge:-2 corner:1
659 %        Type 5 :  5x5 laplacian
660 %        Type 7 :  7x7 laplacian
661 %        Type 15 : 5x5 LoG (sigma approx 1.4)
662 %        Type 19 : 9x9 LoG (sigma approx 1.4)
663 %
664 %    Sobel:{angle}
665 %      Sobel 'Edge' convolution kernel (3x3)
666 %          | -1, 0, 1 |
667 %          | -2, 0,-2 |
668 %          | -1, 0, 1 |
669 %
670 %    Roberts:{angle}
671 %      Roberts convolution kernel (3x3)
672 %          |  0, 0, 0 |
673 %          | -1, 1, 0 |
674 %          |  0, 0, 0 |
675 %
676 %    Prewitt:{angle}
677 %      Prewitt Edge convolution kernel (3x3)
678 %          | -1, 0, 1 |
679 %          | -1, 0, 1 |
680 %          | -1, 0, 1 |
681 %
682 %    Compass:{angle}
683 %      Prewitt's "Compass" convolution kernel (3x3)
684 %          | -1, 1, 1 |
685 %          | -1,-2, 1 |
686 %          | -1, 1, 1 |
687 %
688 %    Kirsch:{angle}
689 %      Kirsch's "Compass" convolution kernel (3x3)
690 %          | -3,-3, 5 |
691 %          | -3, 0, 5 |
692 %          | -3,-3, 5 |
693 %
694 %    FreiChen:{angle}
695 %      Frei-Chen Edge Detector is based on a kernel that is similar to
696 %      the Sobel Kernel, but is designed to be isotropic. That is it takes
697 %      into account the distance of the diagonal in the kernel.
698 %
699 %          |   1,     0,   -1     |
700 %          | sqrt(2), 0, -sqrt(2) |
701 %          |   1,     0,   -1     |
702 %
703 %    FreiChen:{type},{angle}
704 %
705 %      Frei-Chen Pre-weighted kernels...
706 %
707 %        Type 0:  default un-nomalized version shown above.
708 %
709 %        Type 1: Orthogonal Kernel (same as type 11 below)
710 %          |   1,     0,   -1     |
711 %          | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
712 %          |   1,     0,   -1     |
713 %
714 %        Type 2: Diagonal form of Kernel...
715 %          |   1,     sqrt(2),    0     |
716 %          | sqrt(2),   0,     -sqrt(2) | / 2*sqrt(2)
717 %          |   0,    -sqrt(2)    -1     |
718 %
719 %      However this kernel is als at the heart of the FreiChen Edge Detection
720 %      Process which uses a set of 9 specially weighted kernel.  These 9
721 %      kernels not be normalized, but directly applied to the image. The
722 %      results is then added together, to produce the intensity of an edge in
723 %      a specific direction.  The square root of the pixel value can then be
724 %      taken as the cosine of the edge, and at least 2 such runs at 90 degrees
725 %      from each other, both the direction and the strength of the edge can be
726 %      determined.
727 %
728 %        Type 10: All 9 of the following pre-weighted kernels...
729 %
730 %        Type 11: |   1,     0,   -1     |
731 %                 | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
732 %                 |   1,     0,   -1     |
733 %
734 %        Type 12: | 1, sqrt(2), 1 |
735 %                 | 0,   0,     0 | / 2*sqrt(2)
736 %                 | 1, sqrt(2), 1 |
737 %
738 %        Type 13: | sqrt(2), -1,    0     |
739 %                 |  -1,      0,    1     | / 2*sqrt(2)
740 %                 |   0,      1, -sqrt(2) |
741 %
742 %        Type 14: |    0,     1, -sqrt(2) |
743 %                 |   -1,     0,     1    | / 2*sqrt(2)
744 %                 | sqrt(2), -1,     0    |
745 %
746 %        Type 15: | 0, -1, 0 |
747 %                 | 1,  0, 1 | / 2
748 %                 | 0, -1, 0 |
749 %
750 %        Type 16: |  1, 0, -1 |
751 %                 |  0, 0,  0 | / 2
752 %                 | -1, 0,  1 |
753 %
754 %        Type 17: |  1, -2,  1 |
755 %                 | -2,  4, -2 | / 6
756 %                 | -1, -2,  1 |
757 %
758 %        Type 18: | -2, 1, -2 |
759 %                 |  1, 4,  1 | / 6
760 %                 | -2, 1, -2 |
761 %
762 %        Type 19: | 1, 1, 1 |
763 %                 | 1, 1, 1 | / 3
764 %                 | 1, 1, 1 |
765 %
766 %      The first 4 are for edge detection, the next 4 are for line detection
767 %      and the last is to add a average component to the results.
768 %
769 %      Using a special type of '-1' will return all 9 pre-weighted kernels
770 %      as a multi-kernel list, so that you can use them directly (without
771 %      normalization) with the special "-set option:morphology:compose Plus"
772 %      setting to apply the full FreiChen Edge Detection Technique.
773 %
774 %      If 'type' is large it will be taken to be an actual rotation angle for
775 %      the default FreiChen (type 0) kernel.  As such  FreiChen:45  will look
776 %      like a  Sobel:45  but with 'sqrt(2)' instead of '2' values.
777 %
778 %      WARNING: The above was layed out as per
779 %          http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf
780 %      But rotated 90 degrees so direction is from left rather than the top.
781 %      I have yet to find any secondary confirmation of the above. The only
782 %      other source found was actual source code at
783 %          http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf
784 %      Neigher paper defineds the kernels in a way that looks locical or
785 %      correct when taken as a whole.
786 %
787 %  Boolean Kernels
788 %
789 %    Diamond:[{radius}[,{scale}]]
790 %       Generate a diamond shaped kernel with given radius to the points.
791 %       Kernel size will again be radius*2+1 square and defaults to radius 1,
792 %       generating a 3x3 kernel that is slightly larger than a square.
793 %
794 %    Square:[{radius}[,{scale}]]
795 %       Generate a square shaped kernel of size radius*2+1, and defaulting
796 %       to a 3x3 (radius 1).
797 %
798 %    Octagon:[{radius}[,{scale}]]
799 %       Generate octagonal shaped kernel of given radius and constant scale.
800 %       Default radius is 3 producing a 7x7 kernel. A radius of 1 will result
801 %       in "Diamond" kernel.
802 %
803 %    Disk:[{radius}[,{scale}]]
804 %       Generate a binary disk, thresholded at the radius given, the radius
805 %       may be a float-point value. Final Kernel size is floor(radius)*2+1
806 %       square. A radius of 5.3 is the default.
807 %
808 %       NOTE: That a low radii Disk kernels produce the same results as
809 %       many of the previously defined kernels, but differ greatly at larger
810 %       radii.  Here is a table of equivalences...
811 %          "Disk:1"    => "Diamond", "Octagon:1", or "Cross:1"
812 %          "Disk:1.5"  => "Square"
813 %          "Disk:2"    => "Diamond:2"
814 %          "Disk:2.5"  => "Octagon"
815 %          "Disk:2.9"  => "Square:2"
816 %          "Disk:3.5"  => "Octagon:3"
817 %          "Disk:4.5"  => "Octagon:4"
818 %          "Disk:5.4"  => "Octagon:5"
819 %          "Disk:6.4"  => "Octagon:6"
820 %       All other Disk shapes are unique to this kernel, but because a "Disk"
821 %       is more circular when using a larger radius, using a larger radius is
822 %       preferred over iterating the morphological operation.
823 %
824 %    Rectangle:{geometry}
825 %       Simply generate a rectangle of 1's with the size given. You can also
826 %       specify the location of the 'control point', otherwise the closest
827 %       pixel to the center of the rectangle is selected.
828 %
829 %       Properly centered and odd sized rectangles work the best.
830 %
831 %  Symbol Dilation Kernels
832 %
833 %    These kernel is not a good general morphological kernel, but is used
834 %    more for highlighting and marking any single pixels in an image using,
835 %    a "Dilate" method as appropriate.
836 %
837 %    For the same reasons iterating these kernels does not produce the
838 %    same result as using a larger radius for the symbol.
839 %
840 %    Plus:[{radius}[,{scale}]]
841 %    Cross:[{radius}[,{scale}]]
842 %       Generate a kernel in the shape of a 'plus' or a 'cross' with
843 %       a each arm the length of the given radius (default 2).
844 %
845 %       NOTE: "plus:1" is equivalent to a "Diamond" kernel.
846 %
847 %    Ring:{radius1},{radius2}[,{scale}]
848 %       A ring of the values given that falls between the two radii.
849 %       Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
850 %       This is the 'edge' pixels of the default "Disk" kernel,
851 %       More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
852 %
853 %  Hit and Miss Kernels
854 %
855 %    Peak:radius1,radius2
856 %       Find any peak larger than the pixels the fall between the two radii.
857 %       The default ring of pixels is as per "Ring".
858 %    Edges
859 %       Find flat orthogonal edges of a binary shape
860 %    Corners
861 %       Find 90 degree corners of a binary shape
862 %    Diagonals:type
863 %       A special kernel to thin the 'outside' of diagonals
864 %    LineEnds:type
865 %       Find end points of lines (for pruning a skeletion)
866 %       Two types of lines ends (default to both) can be searched for
867 %         Type 0: All line ends
868 %         Type 1: single kernel for 4-conneected line ends
869 %         Type 2: single kernel for simple line ends
870 %    LineJunctions
871 %       Find three line junctions (within a skeletion)
872 %         Type 0: all line junctions
873 %         Type 1: Y Junction kernel
874 %         Type 2: Diagonal T Junction kernel
875 %         Type 3: Orthogonal T Junction kernel
876 %         Type 4: Diagonal X Junction kernel
877 %         Type 5: Orthogonal + Junction kernel
878 %    Ridges:type
879 %       Find single pixel ridges or thin lines
880 %         Type 1: Fine single pixel thick lines and ridges
881 %         Type 2: Find two pixel thick lines and ridges
882 %    ConvexHull
883 %       Octagonal Thickening Kernel, to generate convex hulls of 45 degrees
884 %    Skeleton:type
885 %       Traditional skeleton generating kernels.
886 %         Type 1: Tradional Skeleton kernel (4 connected skeleton)
887 %         Type 2: HIPR2 Skeleton kernel (8 connected skeleton)
888 %         Type 3: Thinning skeleton based on a ressearch paper by
889 %                 Dan S. Bloomberg (Default Type)
890 %    ThinSE:type
891 %       A huge variety of Thinning Kernels designed to preserve conectivity.
892 %       many other kernel sets use these kernels as source definitions.
893 %       Type numbers are 41-49, 81-89, 481, and 482 which are based on
894 %       the super and sub notations used in the source research paper.
895 %
896 %  Distance Measuring Kernels
897 %
898 %    Different types of distance measuring methods, which are used with the
899 %    a 'Distance' morphology method for generating a gradient based on
900 %    distance from an edge of a binary shape, though there is a technique
901 %    for handling a anti-aliased shape.
902 %
903 %    See the 'Distance' Morphological Method, for information of how it is
904 %    applied.
905 %
906 %    Chebyshev:[{radius}][x{scale}[%!]]
907 %       Chebyshev Distance (also known as Tchebychev or Chessboard distance)
908 %       is a value of one to any neighbour, orthogonal or diagonal. One why
909 %       of thinking of it is the number of squares a 'King' or 'Queen' in
910 %       chess needs to traverse reach any other position on a chess board.
911 %       It results in a 'square' like distance function, but one where
912 %       diagonals are given a value that is closer than expected.
913 %
914 %    Manhattan:[{radius}][x{scale}[%!]]
915 %       Manhattan Distance (also known as Rectilinear, City Block, or the Taxi
916 %       Cab distance metric), it is the distance needed when you can only
917 %       travel in horizontal or vertical directions only.  It is the
918 %       distance a 'Rook' in chess would have to travel, and results in a
919 %       diamond like distances, where diagonals are further than expected.
920 %
921 %    Octagonal:[{radius}][x{scale}[%!]]
922 %       An interleving of Manhatten and Chebyshev metrics producing an
923 %       increasing octagonally shaped distance.  Distances matches those of
924 %       the "Octagon" shaped kernel of the same radius.  The minimum radius
925 %       and default is 2, producing a 5x5 kernel.
926 %
927 %    Euclidean:[{radius}][x{scale}[%!]]
928 %       Euclidean distance is the 'direct' or 'as the crow flys' distance.
929 %       However by default the kernel size only has a radius of 1, which
930 %       limits the distance to 'Knight' like moves, with only orthogonal and
931 %       diagonal measurements being correct.  As such for the default kernel
932 %       you will get octagonal like distance function.
933 %
934 %       However using a larger radius such as "Euclidean:4" you will get a
935 %       much smoother distance gradient from the edge of the shape. Especially
936 %       if the image is pre-processed to include any anti-aliasing pixels.
937 %       Of course a larger kernel is slower to use, and not always needed.
938 %
939 %    The first three Distance Measuring Kernels will only generate distances
940 %    of exact multiples of {scale} in binary images. As such you can use a
941 %    scale of 1 without loosing any information.  However you also need some
942 %    scaling when handling non-binary anti-aliased shapes.
943 %
944 %    The "Euclidean" Distance Kernel however does generate a non-integer
945 %    fractional results, and as such scaling is vital even for binary shapes.
946 %
947 */
948
949 MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
950    const GeometryInfo *args)
951 {
952   KernelInfo
953     *kernel;
954
955   register ssize_t
956     i;
957
958   register ssize_t
959     u,
960     v;
961
962   double
963     nan = sqrt((double)-1.0);  /* Special Value : Not A Number */
964
965   /* Generate a new empty kernel if needed */
966   kernel=(KernelInfo *) NULL;
967   switch(type) {
968     case UndefinedKernel:    /* These should not call this function */
969     case UserDefinedKernel:
970       assert("Should not call this function" != (char *)NULL);
971       break;
972     case LaplacianKernel:   /* Named Descrete Convolution Kernels */
973     case SobelKernel:       /* these are defined using other kernels */
974     case RobertsKernel:
975     case PrewittKernel:
976     case CompassKernel:
977     case KirschKernel:
978     case FreiChenKernel:
979     case EdgesKernel:       /* Hit and Miss kernels */
980     case CornersKernel:
981     case DiagonalsKernel:
982     case LineEndsKernel:
983     case LineJunctionsKernel:
984     case RidgesKernel:
985     case ConvexHullKernel:
986     case SkeletonKernel:
987     case ThinSEKernel:
988       break;               /* A pre-generated kernel is not needed */
989 #if 0
990     /* set to 1 to do a compile-time check that we haven't missed anything */
991     case UnityKernel:
992     case GaussianKernel:
993     case DoGKernel:
994     case LoGKernel:
995     case BlurKernel:
996     case CometKernel:
997     case DiamondKernel:
998     case SquareKernel:
999     case RectangleKernel:
1000     case OctagonKernel:
1001     case DiskKernel:
1002     case PlusKernel:
1003     case CrossKernel:
1004     case RingKernel:
1005     case PeaksKernel:
1006     case ChebyshevKernel:
1007     case ManhattanKernel:
1008     case OctangonalKernel:
1009     case EuclideanKernel:
1010 #else
1011     default:
1012 #endif
1013       /* Generate the base Kernel Structure */
1014       kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
1015       if (kernel == (KernelInfo *) NULL)
1016         return(kernel);
1017       (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
1018       kernel->minimum = kernel->maximum = kernel->angle = 0.0;
1019       kernel->negative_range = kernel->positive_range = 0.0;
1020       kernel->type = type;
1021       kernel->next = (KernelInfo *) NULL;
1022       kernel->signature = MagickSignature;
1023       break;
1024   }
1025
1026   switch(type) {
1027     /*
1028       Convolution Kernels
1029     */
1030     case UnityKernel:
1031       {
1032         kernel->height = kernel->width = (size_t) 1;
1033         kernel->x = kernel->y = (ssize_t) 0;
1034         kernel->values=(MagickRealType *) AcquireAlignedMemory(1,
1035           sizeof(*kernel->values));
1036         if (kernel->values == (MagickRealType *) NULL)
1037           return(DestroyKernelInfo(kernel));
1038         kernel->maximum = kernel->values[0] = args->rho;
1039         break;
1040       }
1041       break;
1042     case GaussianKernel:
1043     case DoGKernel:
1044     case LoGKernel:
1045       { double
1046           sigma = fabs(args->sigma),
1047           sigma2 = fabs(args->xi),
1048           A, B, R;
1049
1050         if ( args->rho >= 1.0 )
1051           kernel->width = (size_t)args->rho*2+1;
1052         else if ( (type != DoGKernel) || (sigma >= sigma2) )
1053           kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
1054         else
1055           kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
1056         kernel->height = kernel->width;
1057         kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1058         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1059           kernel->height*sizeof(*kernel->values));
1060         if (kernel->values == (MagickRealType *) NULL)
1061           return(DestroyKernelInfo(kernel));
1062
1063         /* WARNING: The following generates a 'sampled gaussian' kernel.
1064          * What we really want is a 'discrete gaussian' kernel.
1065          *
1066          * How to do this is I don't know, but appears to be basied on the
1067          * Error Function 'erf()' (intergral of a gaussian)
1068          */
1069
1070         if ( type == GaussianKernel || type == DoGKernel )
1071           { /* Calculate a Gaussian,  OR positive half of a DoG */
1072             if ( sigma > MagickEpsilon )
1073               { A = 1.0/(2.0*sigma*sigma);  /* simplify loop expressions */
1074                 B = (double) (1.0/(Magick2PI*sigma*sigma));
1075                 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1076                   for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1077                       kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
1078               }
1079             else /* limiting case - a unity (normalized Dirac) kernel */
1080               { (void) ResetMagickMemory(kernel->values,0, (size_t)
1081                             kernel->width*kernel->height*sizeof(double));
1082                 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1083               }
1084           }
1085
1086         if ( type == DoGKernel )
1087           { /* Subtract a Negative Gaussian for "Difference of Gaussian" */
1088             if ( sigma2 > MagickEpsilon )
1089               { sigma = sigma2;                /* simplify loop expressions */
1090                 A = 1.0/(2.0*sigma*sigma);
1091                 B = (double) (1.0/(Magick2PI*sigma*sigma));
1092                 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1093                   for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1094                     kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
1095               }
1096             else /* limiting case - a unity (normalized Dirac) kernel */
1097               kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1098           }
1099
1100         if ( type == LoGKernel )
1101           { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
1102             if ( sigma > MagickEpsilon )
1103               { A = 1.0/(2.0*sigma*sigma);  /* simplify loop expressions */
1104                 B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma));
1105                 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1106                   for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1107                     { R = ((double)(u*u+v*v))*A;
1108                       kernel->values[i] = (1-R)*exp(-R)*B;
1109                     }
1110               }
1111             else /* special case - generate a unity kernel */
1112               { (void) ResetMagickMemory(kernel->values,0, (size_t)
1113                             kernel->width*kernel->height*sizeof(double));
1114                 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1115               }
1116           }
1117
1118         /* Note the above kernels may have been 'clipped' by a user defined
1119         ** radius, producing a smaller (darker) kernel.  Also for very small
1120         ** sigma's (> 0.1) the central value becomes larger than one, and thus
1121         ** producing a very bright kernel.
1122         **
1123         ** Normalization will still be needed.
1124         */
1125
1126         /* Normalize the 2D Gaussian Kernel
1127         **
1128         ** NB: a CorrelateNormalize performs a normal Normalize if
1129         ** there are no negative values.
1130         */
1131         CalcKernelMetaData(kernel);  /* the other kernel meta-data */
1132         ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1133
1134         break;
1135       }
1136     case BlurKernel:
1137       { double
1138           sigma = fabs(args->sigma),
1139           alpha, beta;
1140
1141         if ( args->rho >= 1.0 )
1142           kernel->width = (size_t)args->rho*2+1;
1143         else
1144           kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
1145         kernel->height = 1;
1146         kernel->x = (ssize_t) (kernel->width-1)/2;
1147         kernel->y = 0;
1148         kernel->negative_range = kernel->positive_range = 0.0;
1149         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1150           kernel->height*sizeof(*kernel->values));
1151         if (kernel->values == (MagickRealType *) NULL)
1152           return(DestroyKernelInfo(kernel));
1153
1154 #if 1
1155 #define KernelRank 3
1156         /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix).
1157         ** It generates a gaussian 3 times the width, and compresses it into
1158         ** the expected range.  This produces a closer normalization of the
1159         ** resulting kernel, especially for very low sigma values.
1160         ** As such while wierd it is prefered.
1161         **
1162         ** I am told this method originally came from Photoshop.
1163         **
1164         ** A properly normalized curve is generated (apart from edge clipping)
1165         ** even though we later normalize the result (for edge clipping)
1166         ** to allow the correct generation of a "Difference of Blurs".
1167         */
1168
1169         /* initialize */
1170         v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */
1171         (void) ResetMagickMemory(kernel->values,0, (size_t)
1172                      kernel->width*kernel->height*sizeof(double));
1173         /* Calculate a Positive 1D Gaussian */
1174         if ( sigma > MagickEpsilon )
1175           { sigma *= KernelRank;               /* simplify loop expressions */
1176             alpha = 1.0/(2.0*sigma*sigma);
1177             beta= (double) (1.0/(MagickSQ2PI*sigma ));
1178             for ( u=-v; u <= v; u++) {
1179               kernel->values[(u+v)/KernelRank] +=
1180                               exp(-((double)(u*u))*alpha)*beta;
1181             }
1182           }
1183         else /* special case - generate a unity kernel */
1184           kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1185 #else
1186         /* Direct calculation without curve averaging */
1187
1188         /* Calculate a Positive Gaussian */
1189         if ( sigma > MagickEpsilon )
1190           { alpha = 1.0/(2.0*sigma*sigma);    /* simplify loop expressions */
1191             beta = 1.0/(MagickSQ2PI*sigma);
1192             for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1193               kernel->values[i] = exp(-((double)(u*u))*alpha)*beta;
1194           }
1195         else /* special case - generate a unity kernel */
1196           { (void) ResetMagickMemory(kernel->values,0, (size_t)
1197                          kernel->width*kernel->height*sizeof(double));
1198             kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1199           }
1200 #endif
1201         /* Note the above kernel may have been 'clipped' by a user defined
1202         ** radius, producing a smaller (darker) kernel.  Also for very small
1203         ** sigma's (> 0.1) the central value becomes larger than one, and thus
1204         ** producing a very bright kernel.
1205         **
1206         ** Normalization will still be needed.
1207         */
1208
1209         /* Normalize the 1D Gaussian Kernel
1210         **
1211         ** NB: a CorrelateNormalize performs a normal Normalize if
1212         ** there are no negative values.
1213         */
1214         CalcKernelMetaData(kernel);  /* the other kernel meta-data */
1215         ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1216
1217         /* rotate the 1D kernel by given angle */
1218         RotateKernelInfo(kernel, args->xi );
1219         break;
1220       }
1221     case CometKernel:
1222       { double
1223           sigma = fabs(args->sigma),
1224           A;
1225
1226         if ( args->rho < 1.0 )
1227           kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
1228         else
1229           kernel->width = (size_t)args->rho;
1230         kernel->x = kernel->y = 0;
1231         kernel->height = 1;
1232         kernel->negative_range = kernel->positive_range = 0.0;
1233         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1234           kernel->height*sizeof(*kernel->values));
1235         if (kernel->values == (MagickRealType *) NULL)
1236           return(DestroyKernelInfo(kernel));
1237
1238         /* A comet blur is half a 1D gaussian curve, so that the object is
1239         ** blurred in one direction only.  This may not be quite the right
1240         ** curve to use so may change in the future. The function must be
1241         ** normalised after generation, which also resolves any clipping.
1242         **
1243         ** As we are normalizing and not subtracting gaussians,
1244         ** there is no need for a divisor in the gaussian formula
1245         **
1246         ** It is less comples
1247         */
1248         if ( sigma > MagickEpsilon )
1249           {
1250 #if 1
1251 #define KernelRank 3
1252             v = (ssize_t) kernel->width*KernelRank; /* start/end points */
1253             (void) ResetMagickMemory(kernel->values,0, (size_t)
1254                           kernel->width*sizeof(double));
1255             sigma *= KernelRank;            /* simplify the loop expression */
1256             A = 1.0/(2.0*sigma*sigma);
1257             /* B = 1.0/(MagickSQ2PI*sigma); */
1258             for ( u=0; u < v; u++) {
1259               kernel->values[u/KernelRank] +=
1260                   exp(-((double)(u*u))*A);
1261               /*  exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1262             }
1263             for (i=0; i < (ssize_t) kernel->width; i++)
1264               kernel->positive_range += kernel->values[i];
1265 #else
1266             A = 1.0/(2.0*sigma*sigma);     /* simplify the loop expression */
1267             /* B = 1.0/(MagickSQ2PI*sigma); */
1268             for ( i=0; i < (ssize_t) kernel->width; i++)
1269               kernel->positive_range +=
1270                 kernel->values[i] =
1271                   exp(-((double)(i*i))*A);
1272                 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1273 #endif
1274           }
1275         else /* special case - generate a unity kernel */
1276           { (void) ResetMagickMemory(kernel->values,0, (size_t)
1277                          kernel->width*kernel->height*sizeof(double));
1278             kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1279             kernel->positive_range = 1.0;
1280           }
1281
1282         kernel->minimum = 0.0;
1283         kernel->maximum = kernel->values[0];
1284         kernel->negative_range = 0.0;
1285
1286         ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1287         RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
1288         break;
1289       }
1290
1291     /*
1292       Convolution Kernels - Well Known Named Constant Kernels
1293     */
1294     case LaplacianKernel:
1295       { switch ( (int) args->rho ) {
1296           case 0:
1297           default: /* laplacian square filter -- default */
1298             kernel=ParseKernelArray("3: -1,-1,-1  -1,8,-1  -1,-1,-1");
1299             break;
1300           case 1:  /* laplacian diamond filter */
1301             kernel=ParseKernelArray("3: 0,-1,0  -1,4,-1  0,-1,0");
1302             break;
1303           case 2:
1304             kernel=ParseKernelArray("3: -2,1,-2  1,4,1  -2,1,-2");
1305             break;
1306           case 3:
1307             kernel=ParseKernelArray("3: 1,-2,1  -2,4,-2  1,-2,1");
1308             break;
1309           case 5:   /* a 5x5 laplacian */
1310             kernel=ParseKernelArray(
1311               "5: -4,-1,0,-1,-4  -1,2,3,2,-1  0,3,4,3,0  -1,2,3,2,-1  -4,-1,0,-1,-4");
1312             break;
1313           case 7:   /* a 7x7 laplacian */
1314             kernel=ParseKernelArray(
1315               "7:-10,-5,-2,-1,-2,-5,-10 -5,0,3,4,3,0,-5 -2,3,6,7,6,3,-2 -1,4,7,8,7,4,-1 -2,3,6,7,6,3,-2 -5,0,3,4,3,0,-5 -10,-5,-2,-1,-2,-5,-10" );
1316             break;
1317           case 15:  /* a 5x5 LoG (sigma approx 1.4) */
1318             kernel=ParseKernelArray(
1319               "5: 0,0,-1,0,0  0,-1,-2,-1,0  -1,-2,16,-2,-1  0,-1,-2,-1,0  0,0,-1,0,0");
1320             break;
1321           case 19:  /* a 9x9 LoG (sigma approx 1.4) */
1322             /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1323             kernel=ParseKernelArray(
1324               "9: 0,-1,-1,-2,-2,-2,-1,-1,0  -1,-2,-4,-5,-5,-5,-4,-2,-1  -1,-4,-5,-3,-0,-3,-5,-4,-1  -2,-5,-3,12,24,12,-3,-5,-2  -2,-5,-0,24,40,24,-0,-5,-2  -2,-5,-3,12,24,12,-3,-5,-2  -1,-4,-5,-3,-0,-3,-5,-4,-1  -1,-2,-4,-5,-5,-5,-4,-2,-1  0,-1,-1,-2,-2,-2,-1,-1,0");
1325             break;
1326         }
1327         if (kernel == (KernelInfo *) NULL)
1328           return(kernel);
1329         kernel->type = type;
1330         break;
1331       }
1332     case SobelKernel:
1333       { /* Simple Sobel Kernel */
1334         kernel=ParseKernelArray("3: 1,0,-1  2,0,-2  1,0,-1");
1335         if (kernel == (KernelInfo *) NULL)
1336           return(kernel);
1337         kernel->type = type;
1338         RotateKernelInfo(kernel, args->rho);
1339         break;
1340       }
1341     case RobertsKernel:
1342       {
1343         kernel=ParseKernelArray("3: 0,0,0  1,-1,0  0,0,0");
1344         if (kernel == (KernelInfo *) NULL)
1345           return(kernel);
1346         kernel->type = type;
1347         RotateKernelInfo(kernel, args->rho);
1348         break;
1349       }
1350     case PrewittKernel:
1351       {
1352         kernel=ParseKernelArray("3: 1,0,-1  1,0,-1  1,0,-1");
1353         if (kernel == (KernelInfo *) NULL)
1354           return(kernel);
1355         kernel->type = type;
1356         RotateKernelInfo(kernel, args->rho);
1357         break;
1358       }
1359     case CompassKernel:
1360       {
1361         kernel=ParseKernelArray("3: 1,1,-1  1,-2,-1  1,1,-1");
1362         if (kernel == (KernelInfo *) NULL)
1363           return(kernel);
1364         kernel->type = type;
1365         RotateKernelInfo(kernel, args->rho);
1366         break;
1367       }
1368     case KirschKernel:
1369       {
1370         kernel=ParseKernelArray("3: 5,-3,-3  5,0,-3  5,-3,-3");
1371         if (kernel == (KernelInfo *) NULL)
1372           return(kernel);
1373         kernel->type = type;
1374         RotateKernelInfo(kernel, args->rho);
1375         break;
1376       }
1377     case FreiChenKernel:
1378       /* Direction is set to be left to right positive */
1379       /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
1380       /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
1381       { switch ( (int) args->rho ) {
1382           default:
1383           case 0:
1384             kernel=ParseKernelArray("3: 1,0,-1  2,0,-2  1,0,-1");
1385             if (kernel == (KernelInfo *) NULL)
1386               return(kernel);
1387             kernel->type = type;
1388             kernel->values[3]+=(MagickRealType) MagickSQ2;
1389             kernel->values[5]-=(MagickRealType) MagickSQ2;
1390             CalcKernelMetaData(kernel);     /* recalculate meta-data */
1391             break;
1392           case 2:
1393             kernel=ParseKernelArray("3: 1,2,0  2,0,-2  0,-2,-1");
1394             if (kernel == (KernelInfo *) NULL)
1395               return(kernel);
1396             kernel->type = type;
1397             kernel->values[1] = kernel->values[3]+=(MagickRealType) MagickSQ2;
1398             kernel->values[5] = kernel->values[7]-=(MagickRealType) MagickSQ2;
1399             CalcKernelMetaData(kernel);     /* recalculate meta-data */
1400             ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1401             break;
1402           case 10:
1403             kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19");
1404             if (kernel == (KernelInfo *) NULL)
1405               return(kernel);
1406             break;
1407           case 1:
1408           case 11:
1409             kernel=ParseKernelArray("3: 1,0,-1  2,0,-2  1,0,-1");
1410             if (kernel == (KernelInfo *) NULL)
1411               return(kernel);
1412             kernel->type = type;
1413             kernel->values[3]+=(MagickRealType) MagickSQ2;
1414             kernel->values[5]-=(MagickRealType) MagickSQ2;
1415             CalcKernelMetaData(kernel);     /* recalculate meta-data */
1416             ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1417             break;
1418           case 12:
1419             kernel=ParseKernelArray("3: 1,2,1  0,0,0  1,2,1");
1420             if (kernel == (KernelInfo *) NULL)
1421               return(kernel);
1422             kernel->type = type;
1423             kernel->values[1]+=(MagickRealType) MagickSQ2;
1424             kernel->values[7]+=(MagickRealType) MagickSQ2;
1425             CalcKernelMetaData(kernel);
1426             ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1427             break;
1428           case 13:
1429             kernel=ParseKernelArray("3: 2,-1,0  -1,0,1  0,1,-2");
1430             if (kernel == (KernelInfo *) NULL)
1431               return(kernel);
1432             kernel->type = type;
1433             kernel->values[0]+=(MagickRealType) MagickSQ2;
1434             kernel->values[8]-=(MagickRealType) MagickSQ2;
1435             CalcKernelMetaData(kernel);
1436             ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1437             break;
1438           case 14:
1439             kernel=ParseKernelArray("3: 0,1,-2  -1,0,1  2,-1,0");
1440             if (kernel == (KernelInfo *) NULL)
1441               return(kernel);
1442             kernel->type = type;
1443             kernel->values[2]-=(MagickRealType) MagickSQ2;
1444             kernel->values[6]+=(MagickRealType) MagickSQ2;
1445             CalcKernelMetaData(kernel);
1446             ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1447             break;
1448           case 15:
1449             kernel=ParseKernelArray("3: 0,-1,0  1,0,1  0,-1,0");
1450             if (kernel == (KernelInfo *) NULL)
1451               return(kernel);
1452             kernel->type = type;
1453             ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1454             break;
1455           case 16:
1456             kernel=ParseKernelArray("3: 1,0,-1  0,0,0  -1,0,1");
1457             if (kernel == (KernelInfo *) NULL)
1458               return(kernel);
1459             kernel->type = type;
1460             ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1461             break;
1462           case 17:
1463             kernel=ParseKernelArray("3: 1,-2,1  -2,4,-2  -1,-2,1");
1464             if (kernel == (KernelInfo *) NULL)
1465               return(kernel);
1466             kernel->type = type;
1467             ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1468             break;
1469           case 18:
1470             kernel=ParseKernelArray("3: -2,1,-2  1,4,1  -2,1,-2");
1471             if (kernel == (KernelInfo *) NULL)
1472               return(kernel);
1473             kernel->type = type;
1474             ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1475             break;
1476           case 19:
1477             kernel=ParseKernelArray("3: 1,1,1  1,1,1  1,1,1");
1478             if (kernel == (KernelInfo *) NULL)
1479               return(kernel);
1480             kernel->type = type;
1481             ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1482             break;
1483         }
1484         if ( fabs(args->sigma) > MagickEpsilon )
1485           /* Rotate by correctly supplied 'angle' */
1486           RotateKernelInfo(kernel, args->sigma);
1487         else if ( args->rho > 30.0 || args->rho < -30.0 )
1488           /* Rotate by out of bounds 'type' */
1489           RotateKernelInfo(kernel, args->rho);
1490         break;
1491       }
1492
1493     /*
1494       Boolean or Shaped Kernels
1495     */
1496     case DiamondKernel:
1497       {
1498         if (args->rho < 1.0)
1499           kernel->width = kernel->height = 3;  /* default radius = 1 */
1500         else
1501           kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1502         kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1503
1504         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1505           kernel->height*sizeof(*kernel->values));
1506         if (kernel->values == (MagickRealType *) NULL)
1507           return(DestroyKernelInfo(kernel));
1508
1509         /* set all kernel values within diamond area to scale given */
1510         for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1511           for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1512             if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
1513               kernel->positive_range += kernel->values[i] = args->sigma;
1514             else
1515               kernel->values[i] = nan;
1516         kernel->minimum = kernel->maximum = args->sigma;   /* a flat shape */
1517         break;
1518       }
1519     case SquareKernel:
1520     case RectangleKernel:
1521       { double
1522           scale;
1523         if ( type == SquareKernel )
1524           {
1525             if (args->rho < 1.0)
1526               kernel->width = kernel->height = 3;  /* default radius = 1 */
1527             else
1528               kernel->width = kernel->height = (size_t) (2*args->rho+1);
1529             kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1530             scale = args->sigma;
1531           }
1532         else {
1533             /* NOTE: user defaults set in "AcquireKernelInfo()" */
1534             if ( args->rho < 1.0 || args->sigma < 1.0 )
1535               return(DestroyKernelInfo(kernel));    /* invalid args given */
1536             kernel->width = (size_t)args->rho;
1537             kernel->height = (size_t)args->sigma;
1538             if ( args->xi  < 0.0 || args->xi  > (double)kernel->width ||
1539                  args->psi < 0.0 || args->psi > (double)kernel->height )
1540               return(DestroyKernelInfo(kernel));    /* invalid args given */
1541             kernel->x = (ssize_t) args->xi;
1542             kernel->y = (ssize_t) args->psi;
1543             scale = 1.0;
1544           }
1545         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1546           kernel->height*sizeof(*kernel->values));
1547         if (kernel->values == (MagickRealType *) NULL)
1548           return(DestroyKernelInfo(kernel));
1549
1550         /* set all kernel values to scale given */
1551         u=(ssize_t) (kernel->width*kernel->height);
1552         for ( i=0; i < u; i++)
1553             kernel->values[i] = scale;
1554         kernel->minimum = kernel->maximum = scale;   /* a flat shape */
1555         kernel->positive_range = scale*u;
1556         break;
1557       }
1558       case OctagonKernel:
1559         {
1560           if (args->rho < 1.0)
1561             kernel->width = kernel->height = 5;  /* default radius = 2 */
1562           else
1563             kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1564           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1565
1566           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1567             kernel->height*sizeof(*kernel->values));
1568           if (kernel->values == (MagickRealType *) NULL)
1569             return(DestroyKernelInfo(kernel));
1570
1571           for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1572             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1573               if ( (labs((long) u)+labs((long) v)) <=
1574                         ((long)kernel->x + (long)(kernel->x/2)) )
1575                 kernel->positive_range += kernel->values[i] = args->sigma;
1576               else
1577                 kernel->values[i] = nan;
1578           kernel->minimum = kernel->maximum = args->sigma;  /* a flat shape */
1579           break;
1580         }
1581       case DiskKernel:
1582         {
1583           ssize_t
1584             limit = (ssize_t)(args->rho*args->rho);
1585
1586           if (args->rho < 0.4)           /* default radius approx 4.3 */
1587             kernel->width = kernel->height = 9L, limit = 18L;
1588           else
1589             kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1;
1590           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1591
1592           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1593             kernel->height*sizeof(*kernel->values));
1594           if (kernel->values == (MagickRealType *) NULL)
1595             return(DestroyKernelInfo(kernel));
1596
1597           for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1598             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1599               if ((u*u+v*v) <= limit)
1600                 kernel->positive_range += kernel->values[i] = args->sigma;
1601               else
1602                 kernel->values[i] = nan;
1603           kernel->minimum = kernel->maximum = args->sigma;   /* a flat shape */
1604           break;
1605         }
1606       case PlusKernel:
1607         {
1608           if (args->rho < 1.0)
1609             kernel->width = kernel->height = 5;  /* default radius 2 */
1610           else
1611             kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1612           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1613
1614           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1615             kernel->height*sizeof(*kernel->values));
1616           if (kernel->values == (MagickRealType *) NULL)
1617             return(DestroyKernelInfo(kernel));
1618
1619           /* set all kernel values along axises to given scale */
1620           for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1621             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1622               kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1623           kernel->minimum = kernel->maximum = args->sigma;   /* a flat shape */
1624           kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1625           break;
1626         }
1627       case CrossKernel:
1628         {
1629           if (args->rho < 1.0)
1630             kernel->width = kernel->height = 5;  /* default radius 2 */
1631           else
1632             kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1633           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1634
1635           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1636             kernel->height*sizeof(*kernel->values));
1637           if (kernel->values == (MagickRealType *) NULL)
1638             return(DestroyKernelInfo(kernel));
1639
1640           /* set all kernel values along axises to given scale */
1641           for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1642             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1643               kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1644           kernel->minimum = kernel->maximum = args->sigma;   /* a flat shape */
1645           kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1646           break;
1647         }
1648       /*
1649         HitAndMiss Kernels
1650       */
1651       case RingKernel:
1652       case PeaksKernel:
1653         {
1654           ssize_t
1655             limit1,
1656             limit2,
1657             scale;
1658
1659           if (args->rho < args->sigma)
1660             {
1661               kernel->width = ((size_t)args->sigma)*2+1;
1662               limit1 = (ssize_t)(args->rho*args->rho);
1663               limit2 = (ssize_t)(args->sigma*args->sigma);
1664             }
1665           else
1666             {
1667               kernel->width = ((size_t)args->rho)*2+1;
1668               limit1 = (ssize_t)(args->sigma*args->sigma);
1669               limit2 = (ssize_t)(args->rho*args->rho);
1670             }
1671           if ( limit2 <= 0 )
1672             kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1673
1674           kernel->height = kernel->width;
1675           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1676           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1677             kernel->height*sizeof(*kernel->values));
1678           if (kernel->values == (MagickRealType *) NULL)
1679             return(DestroyKernelInfo(kernel));
1680
1681           /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
1682           scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
1683           for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
1684             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1685               { ssize_t radius=u*u+v*v;
1686                 if (limit1 < radius && radius <= limit2)
1687                   kernel->positive_range += kernel->values[i] = (double) scale;
1688                 else
1689                   kernel->values[i] = nan;
1690               }
1691           kernel->minimum = kernel->maximum = (double) scale;
1692           if ( type == PeaksKernel ) {
1693             /* set the central point in the middle */
1694             kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1695             kernel->positive_range = 1.0;
1696             kernel->maximum = 1.0;
1697           }
1698           break;
1699         }
1700       case EdgesKernel:
1701         {
1702           kernel=AcquireKernelInfo("ThinSE:482");
1703           if (kernel == (KernelInfo *) NULL)
1704             return(kernel);
1705           kernel->type = type;
1706           ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */
1707           break;
1708         }
1709       case CornersKernel:
1710         {
1711           kernel=AcquireKernelInfo("ThinSE:87");
1712           if (kernel == (KernelInfo *) NULL)
1713             return(kernel);
1714           kernel->type = type;
1715           ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
1716           break;
1717         }
1718       case DiagonalsKernel:
1719         {
1720           switch ( (int) args->rho ) {
1721             case 0:
1722             default:
1723               { KernelInfo
1724                   *new_kernel;
1725                 kernel=ParseKernelArray("3: 0,0,0  0,-,1  1,1,-");
1726                 if (kernel == (KernelInfo *) NULL)
1727                   return(kernel);
1728                 kernel->type = type;
1729                 new_kernel=ParseKernelArray("3: 0,0,1  0,-,1  0,1,-");
1730                 if (new_kernel == (KernelInfo *) NULL)
1731                   return(DestroyKernelInfo(kernel));
1732                 new_kernel->type = type;
1733                 LastKernelInfo(kernel)->next = new_kernel;
1734                 ExpandMirrorKernelInfo(kernel);
1735                 return(kernel);
1736               }
1737             case 1:
1738               kernel=ParseKernelArray("3: 0,0,0  0,-,1  1,1,-");
1739               break;
1740             case 2:
1741               kernel=ParseKernelArray("3: 0,0,1  0,-,1  0,1,-");
1742               break;
1743           }
1744           if (kernel == (KernelInfo *) NULL)
1745             return(kernel);
1746           kernel->type = type;
1747           RotateKernelInfo(kernel, args->sigma);
1748           break;
1749         }
1750       case LineEndsKernel:
1751         { /* Kernels for finding the end of thin lines */
1752           switch ( (int) args->rho ) {
1753             case 0:
1754             default:
1755               /* set of kernels to find all end of lines */
1756               return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>"));
1757             case 1:
1758               /* kernel for 4-connected line ends - no rotation */
1759               kernel=ParseKernelArray("3: 0,0,-  0,1,1  0,0,-");
1760               break;
1761           case 2:
1762               /* kernel to add for 8-connected lines - no rotation */
1763               kernel=ParseKernelArray("3: 0,0,0  0,1,0  0,0,1");
1764               break;
1765           case 3:
1766               /* kernel to add for orthogonal line ends - does not find corners */
1767               kernel=ParseKernelArray("3: 0,0,0  0,1,1  0,0,0");
1768               break;
1769           case 4:
1770               /* traditional line end - fails on last T end */
1771               kernel=ParseKernelArray("3: 0,0,0  0,1,-  0,0,-");
1772               break;
1773           }
1774           if (kernel == (KernelInfo *) NULL)
1775             return(kernel);
1776           kernel->type = type;
1777           RotateKernelInfo(kernel, args->sigma);
1778           break;
1779         }
1780       case LineJunctionsKernel:
1781         { /* kernels for finding the junctions of multiple lines */
1782           switch ( (int) args->rho ) {
1783             case 0:
1784             default:
1785               /* set of kernels to find all line junctions */
1786               return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>"));
1787             case 1:
1788               /* Y Junction */
1789               kernel=ParseKernelArray("3: 1,-,1  -,1,-  -,1,-");
1790               break;
1791             case 2:
1792               /* Diagonal T Junctions */
1793               kernel=ParseKernelArray("3: 1,-,-  -,1,-  1,-,1");
1794               break;
1795             case 3:
1796               /* Orthogonal T Junctions */
1797               kernel=ParseKernelArray("3: -,-,-  1,1,1  -,1,-");
1798               break;
1799             case 4:
1800               /* Diagonal X Junctions */
1801               kernel=ParseKernelArray("3: 1,-,1  -,1,-  1,-,1");
1802               break;
1803             case 5:
1804               /* Orthogonal X Junctions - minimal diamond kernel */
1805               kernel=ParseKernelArray("3: -,1,-  1,1,1  -,1,-");
1806               break;
1807           }
1808           if (kernel == (KernelInfo *) NULL)
1809             return(kernel);
1810           kernel->type = type;
1811           RotateKernelInfo(kernel, args->sigma);
1812           break;
1813         }
1814       case RidgesKernel:
1815         { /* Ridges - Ridge finding kernels */
1816           KernelInfo
1817             *new_kernel;
1818           switch ( (int) args->rho ) {
1819             case 1:
1820             default:
1821               kernel=ParseKernelArray("3x1:0,1,0");
1822               if (kernel == (KernelInfo *) NULL)
1823                 return(kernel);
1824               kernel->type = type;
1825               ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
1826               break;
1827             case 2:
1828               kernel=ParseKernelArray("4x1:0,1,1,0");
1829               if (kernel == (KernelInfo *) NULL)
1830                 return(kernel);
1831               kernel->type = type;
1832               ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
1833
1834               /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */
1835               /* Unfortunatally we can not yet rotate a non-square kernel */
1836               /* But then we can't flip a non-symetrical kernel either */
1837               new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1838               if (new_kernel == (KernelInfo *) NULL)
1839                 return(DestroyKernelInfo(kernel));
1840               new_kernel->type = type;
1841               LastKernelInfo(kernel)->next = new_kernel;
1842               new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
1843               if (new_kernel == (KernelInfo *) NULL)
1844                 return(DestroyKernelInfo(kernel));
1845               new_kernel->type = type;
1846               LastKernelInfo(kernel)->next = new_kernel;
1847               new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
1848               if (new_kernel == (KernelInfo *) NULL)
1849                 return(DestroyKernelInfo(kernel));
1850               new_kernel->type = type;
1851               LastKernelInfo(kernel)->next = new_kernel;
1852               new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
1853               if (new_kernel == (KernelInfo *) NULL)
1854                 return(DestroyKernelInfo(kernel));
1855               new_kernel->type = type;
1856               LastKernelInfo(kernel)->next = new_kernel;
1857               new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
1858               if (new_kernel == (KernelInfo *) NULL)
1859                 return(DestroyKernelInfo(kernel));
1860               new_kernel->type = type;
1861               LastKernelInfo(kernel)->next = new_kernel;
1862               new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
1863               if (new_kernel == (KernelInfo *) NULL)
1864                 return(DestroyKernelInfo(kernel));
1865               new_kernel->type = type;
1866               LastKernelInfo(kernel)->next = new_kernel;
1867               new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
1868               if (new_kernel == (KernelInfo *) NULL)
1869                 return(DestroyKernelInfo(kernel));
1870               new_kernel->type = type;
1871               LastKernelInfo(kernel)->next = new_kernel;
1872               new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
1873               if (new_kernel == (KernelInfo *) NULL)
1874                 return(DestroyKernelInfo(kernel));
1875               new_kernel->type = type;
1876               LastKernelInfo(kernel)->next = new_kernel;
1877               break;
1878           }
1879           break;
1880         }
1881       case ConvexHullKernel:
1882         {
1883           KernelInfo
1884             *new_kernel;
1885           /* first set of 8 kernels */
1886           kernel=ParseKernelArray("3: 1,1,-  1,0,-  1,-,0");
1887           if (kernel == (KernelInfo *) NULL)
1888             return(kernel);
1889           kernel->type = type;
1890           ExpandRotateKernelInfo(kernel, 90.0);
1891           /* append the mirror versions too - no flip function yet */
1892           new_kernel=ParseKernelArray("3: 1,1,1  1,0,-  -,-,0");
1893           if (new_kernel == (KernelInfo *) NULL)
1894             return(DestroyKernelInfo(kernel));
1895           new_kernel->type = type;
1896           ExpandRotateKernelInfo(new_kernel, 90.0);
1897           LastKernelInfo(kernel)->next = new_kernel;
1898           break;
1899         }
1900       case SkeletonKernel:
1901         {
1902           switch ( (int) args->rho ) {
1903             case 1:
1904             default:
1905               /* Traditional Skeleton...
1906               ** A cyclically rotated single kernel
1907               */
1908               kernel=AcquireKernelInfo("ThinSE:482");
1909               if (kernel == (KernelInfo *) NULL)
1910                 return(kernel);
1911               kernel->type = type;
1912               ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */
1913               break;
1914             case 2:
1915               /* HIPR Variation of the cyclic skeleton
1916               ** Corners of the traditional method made more forgiving,
1917               ** but the retain the same cyclic order.
1918               */
1919               kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;");
1920               if (kernel == (KernelInfo *) NULL)
1921                 return(kernel);
1922               if (kernel->next == (KernelInfo *) NULL)
1923                 return(DestroyKernelInfo(kernel));
1924               kernel->type = type;
1925               kernel->next->type = type;
1926               ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */
1927               break;
1928             case 3:
1929               /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's
1930               ** "Connectivity-Preserving Morphological Image Thransformations"
1931               ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1932               **   http://www.leptonica.com/papers/conn.pdf
1933               */
1934               kernel=AcquireKernelInfo(
1935                             "ThinSE:41; ThinSE:42; ThinSE:43");
1936               if (kernel == (KernelInfo *) NULL)
1937                 return(kernel);
1938               kernel->type = type;
1939               kernel->next->type = type;
1940               kernel->next->next->type = type;
1941               ExpandMirrorKernelInfo(kernel); /* 12 kernels total */
1942               break;
1943            }
1944           break;
1945         }
1946       case ThinSEKernel:
1947         { /* Special kernels for general thinning, while preserving connections
1948           ** "Connectivity-Preserving Morphological Image Thransformations"
1949           ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1950           **   http://www.leptonica.com/papers/conn.pdf
1951           ** And
1952           **   http://tpgit.github.com/Leptonica/ccthin_8c_source.html
1953           **
1954           ** Note kernels do not specify the origin pixel, allowing them
1955           ** to be used for both thickening and thinning operations.
1956           */
1957           switch ( (int) args->rho ) {
1958             /* SE for 4-connected thinning */
1959             case 41: /* SE_4_1 */
1960               kernel=ParseKernelArray("3: -,-,1  0,-,1  -,-,1");
1961               break;
1962             case 42: /* SE_4_2 */
1963               kernel=ParseKernelArray("3: -,-,1  0,-,1  -,0,-");
1964               break;
1965             case 43: /* SE_4_3 */
1966               kernel=ParseKernelArray("3: -,0,-  0,-,1  -,-,1");
1967               break;
1968             case 44: /* SE_4_4 */
1969               kernel=ParseKernelArray("3: -,0,-  0,-,1  -,0,-");
1970               break;
1971             case 45: /* SE_4_5 */
1972               kernel=ParseKernelArray("3: -,0,1  0,-,1  -,0,-");
1973               break;
1974             case 46: /* SE_4_6 */
1975               kernel=ParseKernelArray("3: -,0,-  0,-,1  -,0,1");
1976               break;
1977             case 47: /* SE_4_7 */
1978               kernel=ParseKernelArray("3: -,1,1  0,-,1  -,0,-");
1979               break;
1980             case 48: /* SE_4_8 */
1981               kernel=ParseKernelArray("3: -,-,1  0,-,1  0,-,1");
1982               break;
1983             case 49: /* SE_4_9 */
1984               kernel=ParseKernelArray("3: 0,-,1  0,-,1  -,-,1");
1985               break;
1986             /* SE for 8-connected thinning - negatives of the above */
1987             case 81: /* SE_8_0 */
1988               kernel=ParseKernelArray("3: -,1,-  0,-,1  -,1,-");
1989               break;
1990             case 82: /* SE_8_2 */
1991               kernel=ParseKernelArray("3: -,1,-  0,-,1  0,-,-");
1992               break;
1993             case 83: /* SE_8_3 */
1994               kernel=ParseKernelArray("3: 0,-,-  0,-,1  -,1,-");
1995               break;
1996             case 84: /* SE_8_4 */
1997               kernel=ParseKernelArray("3: 0,-,-  0,-,1  0,-,-");
1998               break;
1999             case 85: /* SE_8_5 */
2000               kernel=ParseKernelArray("3: 0,-,1  0,-,1  0,-,-");
2001               break;
2002             case 86: /* SE_8_6 */
2003               kernel=ParseKernelArray("3: 0,-,-  0,-,1  0,-,1");
2004               break;
2005             case 87: /* SE_8_7 */
2006               kernel=ParseKernelArray("3: -,1,-  0,-,1  0,0,-");
2007               break;
2008             case 88: /* SE_8_8 */
2009               kernel=ParseKernelArray("3: -,1,-  0,-,1  0,1,-");
2010               break;
2011             case 89: /* SE_8_9 */
2012               kernel=ParseKernelArray("3: 0,1,-  0,-,1  -,1,-");
2013               break;
2014             /* Special combined SE kernels */
2015             case 423: /* SE_4_2 , SE_4_3 Combined Kernel */
2016               kernel=ParseKernelArray("3: -,-,1  0,-,-  -,0,-");
2017               break;
2018             case 823: /* SE_8_2 , SE_8_3 Combined Kernel */
2019               kernel=ParseKernelArray("3: -,1,-  -,-,1  0,-,-");
2020               break;
2021             case 481: /* SE_48_1 - General Connected Corner Kernel */
2022               kernel=ParseKernelArray("3: -,1,1  0,-,1  0,0,-");
2023               break;
2024             default:
2025             case 482: /* SE_48_2 - General Edge Kernel */
2026               kernel=ParseKernelArray("3: 0,-,1  0,-,1  0,-,1");
2027               break;
2028           }
2029           if (kernel == (KernelInfo *) NULL)
2030             return(kernel);
2031           kernel->type = type;
2032           RotateKernelInfo(kernel, args->sigma);
2033           break;
2034         }
2035       /*
2036         Distance Measuring Kernels
2037       */
2038       case ChebyshevKernel:
2039         {
2040           if (args->rho < 1.0)
2041             kernel->width = kernel->height = 3;  /* default radius = 1 */
2042           else
2043             kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2044           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2045
2046           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2047             kernel->height*sizeof(*kernel->values));
2048           if (kernel->values == (MagickRealType *) NULL)
2049             return(DestroyKernelInfo(kernel));
2050
2051           for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2052             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2053               kernel->positive_range += ( kernel->values[i] =
2054                   args->sigma*MagickMax(fabs((double)u),fabs((double)v)) );
2055           kernel->maximum = kernel->values[0];
2056           break;
2057         }
2058       case ManhattanKernel:
2059         {
2060           if (args->rho < 1.0)
2061             kernel->width = kernel->height = 3;  /* default radius = 1 */
2062           else
2063             kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2064           kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2065
2066           kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2067             kernel->height*sizeof(*kernel->values));
2068           if (kernel->values == (MagickRealType *) NULL)
2069             return(DestroyKernelInfo(kernel));
2070
2071           for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2072             for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2073               kernel->positive_range += ( kernel->values[i] =
2074                   args->sigma*(labs((long) u)+labs((long) v)) );
2075           kernel->maximum = kernel->values[0];
2076           break;
2077         }
2078       case OctagonalKernel:
2079       {
2080         if (args->rho < 2.0)
2081           kernel->width = kernel->height = 5;  /* default/minimum radius = 2 */
2082         else
2083           kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2084         kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2085
2086         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2087           kernel->height*sizeof(*kernel->values));
2088         if (kernel->values == (MagickRealType *) NULL)
2089           return(DestroyKernelInfo(kernel));
2090
2091         for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2092           for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2093             {
2094               double
2095                 r1 = MagickMax(fabs((double)u),fabs((double)v)),
2096                 r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5);
2097               kernel->positive_range += kernel->values[i] =
2098                         args->sigma*MagickMax(r1,r2);
2099             }
2100         kernel->maximum = kernel->values[0];
2101         break;
2102       }
2103     case EuclideanKernel:
2104       {
2105         if (args->rho < 1.0)
2106           kernel->width = kernel->height = 3;  /* default radius = 1 */
2107         else
2108           kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2109         kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2110
2111         kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2112           kernel->height*sizeof(*kernel->values));
2113         if (kernel->values == (MagickRealType *) NULL)
2114           return(DestroyKernelInfo(kernel));
2115
2116         for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2117           for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2118             kernel->positive_range += ( kernel->values[i] =
2119               args->sigma*sqrt((double)(u*u+v*v)) );
2120         kernel->maximum = kernel->values[0];
2121         break;
2122       }
2123     default:
2124       {
2125         /* No-Op Kernel - Basically just a single pixel on its own */
2126         kernel=ParseKernelArray("1:1");
2127         if (kernel == (KernelInfo *) NULL)
2128           return(kernel);
2129         kernel->type = UndefinedKernel;
2130         break;
2131       }
2132       break;
2133   }
2134   return(kernel);
2135 }
2136 \f
2137 /*
2138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2139 %                                                                             %
2140 %                                                                             %
2141 %                                                                             %
2142 %     C l o n e K e r n e l I n f o                                           %
2143 %                                                                             %
2144 %                                                                             %
2145 %                                                                             %
2146 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2147 %
2148 %  CloneKernelInfo() creates a new clone of the given Kernel List so that its
2149 %  can be modified without effecting the original.  The cloned kernel should
2150 %  be destroyed using DestoryKernelInfo() when no longer needed.
2151 %
2152 %  The format of the CloneKernelInfo method is:
2153 %
2154 %      KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2155 %
2156 %  A description of each parameter follows:
2157 %
2158 %    o kernel: the Morphology/Convolution kernel to be cloned
2159 %
2160 */
2161 MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2162 {
2163   register ssize_t
2164     i;
2165
2166   KernelInfo
2167     *new_kernel;
2168
2169   assert(kernel != (KernelInfo *) NULL);
2170   new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
2171   if (new_kernel == (KernelInfo *) NULL)
2172     return(new_kernel);
2173   *new_kernel=(*kernel); /* copy values in structure */
2174
2175   /* replace the values with a copy of the values */
2176   new_kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2177     kernel->height*sizeof(*kernel->values));
2178   if (new_kernel->values == (MagickRealType *) NULL)
2179     return(DestroyKernelInfo(new_kernel));
2180   for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
2181     new_kernel->values[i]=kernel->values[i];
2182
2183   /* Also clone the next kernel in the kernel list */
2184   if ( kernel->next != (KernelInfo *) NULL ) {
2185     new_kernel->next = CloneKernelInfo(kernel->next);
2186     if ( new_kernel->next == (KernelInfo *) NULL )
2187       return(DestroyKernelInfo(new_kernel));
2188   }
2189
2190   return(new_kernel);
2191 }
2192 \f
2193 /*
2194 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2195 %                                                                             %
2196 %                                                                             %
2197 %                                                                             %
2198 %     D e s t r o y K e r n e l I n f o                                       %
2199 %                                                                             %
2200 %                                                                             %
2201 %                                                                             %
2202 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2203 %
2204 %  DestroyKernelInfo() frees the memory used by a Convolution/Morphology
2205 %  kernel.
2206 %
2207 %  The format of the DestroyKernelInfo method is:
2208 %
2209 %      KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2210 %
2211 %  A description of each parameter follows:
2212 %
2213 %    o kernel: the Morphology/Convolution kernel to be destroyed
2214 %
2215 */
2216 MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2217 {
2218   assert(kernel != (KernelInfo *) NULL);
2219   if ( kernel->next != (KernelInfo *) NULL )
2220     kernel->next=DestroyKernelInfo(kernel->next);
2221   kernel->values=(MagickRealType *) RelinquishAlignedMemory(kernel->values);
2222   kernel=(KernelInfo *) RelinquishMagickMemory(kernel);
2223   return(kernel);
2224 }
2225 \f
2226 /*
2227 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2228 %                                                                             %
2229 %                                                                             %
2230 %                                                                             %
2231 +     E x p a n d M i r r o r K e r n e l I n f o                             %
2232 %                                                                             %
2233 %                                                                             %
2234 %                                                                             %
2235 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2236 %
2237 %  ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
2238 %  sequence of 90-degree rotated kernels but providing a reflected 180
2239 %  rotatation, before the -/+ 90-degree rotations.
2240 %
2241 %  This special rotation order produces a better, more symetrical thinning of
2242 %  objects.
2243 %
2244 %  The format of the ExpandMirrorKernelInfo method is:
2245 %
2246 %      void ExpandMirrorKernelInfo(KernelInfo *kernel)
2247 %
2248 %  A description of each parameter follows:
2249 %
2250 %    o kernel: the Morphology/Convolution kernel
2251 %
2252 % This function is only internel to this module, as it is not finalized,
2253 % especially with regard to non-orthogonal angles, and rotation of larger
2254 % 2D kernels.
2255 */
2256
2257 #if 0
2258 static void FlopKernelInfo(KernelInfo *kernel)
2259     { /* Do a Flop by reversing each row. */
2260       size_t
2261         y;
2262       register ssize_t
2263         x,r;
2264       register double
2265         *k,t;
2266
2267       for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
2268         for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
2269           t=k[x],  k[x]=k[r],  k[r]=t;
2270
2271       kernel->x = kernel->width - kernel->x - 1;
2272       angle = fmod(angle+180.0, 360.0);
2273     }
2274 #endif
2275
2276 static void ExpandMirrorKernelInfo(KernelInfo *kernel)
2277 {
2278   KernelInfo
2279     *clone,
2280     *last;
2281
2282   last = kernel;
2283
2284   clone = CloneKernelInfo(last);
2285   RotateKernelInfo(clone, 180);   /* flip */
2286   LastKernelInfo(last)->next = clone;
2287   last = clone;
2288
2289   clone = CloneKernelInfo(last);
2290   RotateKernelInfo(clone, 90);   /* transpose */
2291   LastKernelInfo(last)->next = clone;
2292   last = clone;
2293
2294   clone = CloneKernelInfo(last);
2295   RotateKernelInfo(clone, 180);  /* flop */
2296   LastKernelInfo(last)->next = clone;
2297
2298   return;
2299 }
2300 \f
2301 /*
2302 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2303 %                                                                             %
2304 %                                                                             %
2305 %                                                                             %
2306 +     E x p a n d R o t a t e K e r n e l I n f o                             %
2307 %                                                                             %
2308 %                                                                             %
2309 %                                                                             %
2310 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2311 %
2312 %  ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
2313 %  incrementally by the angle given, until the kernel repeats.
2314 %
2315 %  WARNING: 45 degree rotations only works for 3x3 kernels.
2316 %  While 90 degree roatations only works for linear and square kernels
2317 %
2318 %  The format of the ExpandRotateKernelInfo method is:
2319 %
2320 %      void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
2321 %
2322 %  A description of each parameter follows:
2323 %
2324 %    o kernel: the Morphology/Convolution kernel
2325 %
2326 %    o angle: angle to rotate in degrees
2327 %
2328 % This function is only internel to this module, as it is not finalized,
2329 % especially with regard to non-orthogonal angles, and rotation of larger
2330 % 2D kernels.
2331 */
2332
2333 /* Internal Routine - Return true if two kernels are the same */
2334 static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
2335      const KernelInfo *kernel2)
2336 {
2337   register size_t
2338     i;
2339
2340   /* check size and origin location */
2341   if (    kernel1->width != kernel2->width
2342        || kernel1->height != kernel2->height
2343        || kernel1->x != kernel2->x
2344        || kernel1->y != kernel2->y )
2345     return MagickFalse;
2346
2347   /* check actual kernel values */
2348   for (i=0; i < (kernel1->width*kernel1->height); i++) {
2349     /* Test for Nan equivalence */
2350     if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
2351       return MagickFalse;
2352     if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
2353       return MagickFalse;
2354     /* Test actual values are equivalent */
2355     if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
2356       return MagickFalse;
2357   }
2358
2359   return MagickTrue;
2360 }
2361
2362 static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
2363 {
2364   KernelInfo
2365     *clone,
2366     *last;
2367
2368   last = kernel;
2369   while(1) {
2370     clone = CloneKernelInfo(last);
2371     RotateKernelInfo(clone, angle);
2372     if ( SameKernelInfo(kernel, clone) == MagickTrue )
2373       break;
2374     LastKernelInfo(last)->next = clone;
2375     last = clone;
2376   }
2377   clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
2378   return;
2379 }
2380 \f
2381 /*
2382 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2383 %                                                                             %
2384 %                                                                             %
2385 %                                                                             %
2386 +     C a l c M e t a K e r n a l I n f o                                     %
2387 %                                                                             %
2388 %                                                                             %
2389 %                                                                             %
2390 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2391 %
2392 %  CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2393 %  using the kernel values.  This should only ne used if it is not possible to
2394 %  calculate that meta-data in some easier way.
2395 %
2396 %  It is important that the meta-data is correct before ScaleKernelInfo() is
2397 %  used to perform kernel normalization.
2398 %
2399 %  The format of the CalcKernelMetaData method is:
2400 %
2401 %      void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2402 %
2403 %  A description of each parameter follows:
2404 %
2405 %    o kernel: the Morphology/Convolution kernel to modify
2406 %
2407 %  WARNING: Minimum and Maximum values are assumed to include zero, even if
2408 %  zero is not part of the kernel (as in Gaussian Derived kernels). This
2409 %  however is not true for flat-shaped morphological kernels.
2410 %
2411 %  WARNING: Only the specific kernel pointed to is modified, not a list of
2412 %  multiple kernels.
2413 %
2414 % This is an internal function and not expected to be useful outside this
2415 % module.  This could change however.
2416 */
2417 static void CalcKernelMetaData(KernelInfo *kernel)
2418 {
2419   register size_t
2420     i;
2421
2422   kernel->minimum = kernel->maximum = 0.0;
2423   kernel->negative_range = kernel->positive_range = 0.0;
2424   for (i=0; i < (kernel->width*kernel->height); i++)
2425     {
2426       if ( fabs(kernel->values[i]) < MagickEpsilon )
2427         kernel->values[i] = 0.0;
2428       ( kernel->values[i] < 0)
2429           ?  ( kernel->negative_range += kernel->values[i] )
2430           :  ( kernel->positive_range += kernel->values[i] );
2431       Minimize(kernel->minimum, kernel->values[i]);
2432       Maximize(kernel->maximum, kernel->values[i]);
2433     }
2434
2435   return;
2436 }
2437 \f
2438 /*
2439 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2440 %                                                                             %
2441 %                                                                             %
2442 %                                                                             %
2443 %     M o r p h o l o g y A p p l y                                           %
2444 %                                                                             %
2445 %                                                                             %
2446 %                                                                             %
2447 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2448 %
2449 %  MorphologyApply() applies a morphological method, multiple times using
2450 %  a list of multiple kernels.  This is the method that should be called by
2451 %  other 'operators' that internally use morphology operations as part of
2452 %  their processing.
2453 %
2454 %  It is basically equivalent to as MorphologyImage() (see below) but
2455 %  without any user controls.  This allows internel programs to use this
2456 %  function, to actually perform a specific task without possible interference
2457 %  by any API user supplied settings.
2458 %
2459 %  It is MorphologyImage() task to extract any such user controls, and
2460 %  pass them to this function for processing.
2461 %
2462 %  More specifically all given kernels should already be scaled, normalised,
2463 %  and blended appropriatally before being parred to this routine. The
2464 %  appropriate bias, and compose (typically 'UndefinedComposeOp') given.
2465 %
2466 %  The format of the MorphologyApply method is:
2467 %
2468 %      Image *MorphologyApply(const Image *image,MorphologyMethod method,
2469 %        const ssize_t iterations,const KernelInfo *kernel,
2470 %        const CompositeMethod compose,const double bias,
2471 %        ExceptionInfo *exception)
2472 %
2473 %  A description of each parameter follows:
2474 %
2475 %    o image: the source image
2476 %
2477 %    o method: the morphology method to be applied.
2478 %
2479 %    o iterations: apply the operation this many times (or no change).
2480 %                  A value of -1 means loop until no change found.
2481 %                  How this is applied may depend on the morphology method.
2482 %                  Typically this is a value of 1.
2483 %
2484 %    o channel: the channel type.
2485 %
2486 %    o kernel: An array of double representing the morphology kernel.
2487 %
2488 %    o compose: How to handle or merge multi-kernel results.
2489 %          If 'UndefinedCompositeOp' use default for the Morphology method.
2490 %          If 'NoCompositeOp' force image to be re-iterated by each kernel.
2491 %          Otherwise merge the results using the compose method given.
2492 %
2493 %    o bias: Convolution Output Bias.
2494 %
2495 %    o exception: return any errors or warnings in this structure.
2496 %
2497 */
2498
2499 /* Apply a Morphology Primative to an image using the given kernel.
2500 ** Two pre-created images must be provided, and no image is created.
2501 ** It returns the number of pixels that changed between the images
2502 ** for result convergence determination.
2503 */
2504 static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image,
2505   const MorphologyMethod method,const KernelInfo *kernel,const double bias,
2506   ExceptionInfo *exception)
2507 {
2508 #define MorphologyTag  "Morphology/Image"
2509
2510   CacheView
2511     *image_view,
2512     *morphology_view;
2513
2514   ssize_t
2515     y, offx, offy;
2516
2517   size_t
2518     virt_width,
2519     changed;
2520
2521   MagickBooleanType
2522     status;
2523
2524   MagickOffsetType
2525     progress;
2526
2527   assert(image != (Image *) NULL);
2528   assert(image->signature == MagickSignature);
2529   assert(morphology_image != (Image *) NULL);
2530   assert(morphology_image->signature == MagickSignature);
2531   assert(kernel != (KernelInfo *) NULL);
2532   assert(kernel->signature == MagickSignature);
2533   assert(exception != (ExceptionInfo *) NULL);
2534   assert(exception->signature == MagickSignature);
2535
2536   status=MagickTrue;
2537   changed=0;
2538   progress=0;
2539
2540   image_view=AcquireVirtualCacheView(image,exception);
2541   morphology_view=AcquireAuthenticCacheView(morphology_image,exception);
2542   virt_width=image->columns+kernel->width-1;
2543
2544   /* Some methods (including convolve) needs use a reflected kernel.
2545    * Adjust 'origin' offsets to loop though kernel as a reflection.
2546    */
2547   offx = kernel->x;
2548   offy = kernel->y;
2549   switch(method) {
2550     case ConvolveMorphology:
2551     case DilateMorphology:
2552     case DilateIntensityMorphology:
2553     case IterativeDistanceMorphology:
2554       /* kernel needs to used with reflection about origin */
2555       offx = (ssize_t) kernel->width-offx-1;
2556       offy = (ssize_t) kernel->height-offy-1;
2557       break;
2558     case ErodeMorphology:
2559     case ErodeIntensityMorphology:
2560     case HitAndMissMorphology:
2561     case ThinningMorphology:
2562     case ThickenMorphology:
2563       /* kernel is used as is, without reflection */
2564       break;
2565     default:
2566       assert("Not a Primitive Morphology Method" != (char *) NULL);
2567       break;
2568   }
2569
2570   if ( method == ConvolveMorphology && kernel->width == 1 )
2571   { /* Special handling (for speed) of vertical (blur) kernels.
2572     ** This performs its handling in columns rather than in rows.
2573     ** This is only done for convolve as it is the only method that
2574     ** generates very large 1-D vertical kernels (such as a 'BlurKernel')
2575     **
2576     ** Timing tests (on single CPU laptop)
2577     ** Using a vertical 1-d Blue with normal row-by-row (below)
2578     **   time convert logo: -morphology Convolve Blur:0x10+90 null:
2579     **      0.807u
2580     ** Using this column method
2581     **   time convert logo: -morphology Convolve Blur:0x10+90 null:
2582     **      0.620u
2583     **
2584     ** Anthony Thyssen, 14 June 2010
2585     */
2586     register ssize_t
2587       x;
2588
2589 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2590     #pragma omp parallel for schedule(static,4) shared(progress,status) \
2591       if ((image->rows*image->columns) > 8192) \
2592         num_threads(GetMagickResourceLimit(ThreadResource))
2593 #endif
2594     for (x=0; x < (ssize_t) image->columns; x++)
2595     {
2596       register const Quantum
2597         *restrict p;
2598
2599       register Quantum
2600         *restrict q;
2601
2602       register ssize_t
2603         y;
2604
2605       ssize_t
2606         r;
2607
2608       if (status == MagickFalse)
2609         continue;
2610       p=GetCacheViewVirtualPixels(image_view,x,-offy,1,image->rows+
2611         kernel->height-1,exception);
2612       q=GetCacheViewAuthenticPixels(morphology_view,x,0,1,
2613         morphology_image->rows,exception);
2614       if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2615         {
2616           status=MagickFalse;
2617           continue;
2618         }
2619       /* offset to origin in 'p'. while 'q' points to it directly */
2620       r = offy;
2621
2622       for (y=0; y < (ssize_t) image->rows; y++)
2623       {
2624         PixelInfo
2625           result;
2626
2627         register ssize_t
2628           v;
2629
2630         register const double
2631           *restrict k;
2632
2633         register const Quantum
2634           *restrict k_pixels;
2635
2636         /* Copy input image to the output image for unused channels
2637         * This removes need for 'cloning' a new image every iteration
2638         */
2639         SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2640           GetPixelChannels(image)),q);
2641         SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2642           GetPixelChannels(image)),q);
2643         SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2644           GetPixelChannels(image)),q);
2645         if (image->colorspace == CMYKColorspace)
2646           SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2647             GetPixelChannels(image)),q);
2648
2649         /* Set the bias of the weighted average output */
2650         result.red     =
2651         result.green   =
2652         result.blue    =
2653         result.alpha =
2654         result.black   = bias;
2655
2656
2657         /* Weighted Average of pixels using reflected kernel
2658         **
2659         ** NOTE for correct working of this operation for asymetrical
2660         ** kernels, the kernel needs to be applied in its reflected form.
2661         ** That is its values needs to be reversed.
2662         */
2663         k = &kernel->values[ kernel->height-1 ];
2664         k_pixels = p;
2665         if ( (image->channel_mask != DefaultChannels) ||
2666              (image->matte == MagickFalse) )
2667           { /* No 'Sync' involved.
2668             ** Convolution is just a simple greyscale channel operation
2669             */
2670             for (v=0; v < (ssize_t) kernel->height; v++) {
2671               if ( IsNan(*k) ) continue;
2672               result.red     += (*k)*GetPixelRed(image,k_pixels);
2673               result.green   += (*k)*GetPixelGreen(image,k_pixels);
2674               result.blue    += (*k)*GetPixelBlue(image,k_pixels);
2675               if (image->colorspace == CMYKColorspace)
2676                 result.black+=(*k)*GetPixelBlack(image,k_pixels);
2677               result.alpha += (*k)*GetPixelAlpha(image,k_pixels);
2678               k--;
2679               k_pixels+=GetPixelChannels(image);
2680             }
2681             if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2682               SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
2683             if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2684               SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
2685             if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2686               SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
2687             if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2688                 (image->colorspace == CMYKColorspace))
2689               SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
2690             if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2691                 (image->matte == MagickTrue))
2692               SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2693           }
2694         else
2695           { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2696             ** Weight the color channels with Alpha Channel so that
2697             ** transparent pixels are not part of the results.
2698             */
2699             MagickRealType
2700               alpha,  /* alpha weighting for colors : alpha  */
2701               gamma;  /* divisor, sum of color alpha weighting */
2702             size_t
2703               count;  /* alpha valus collected, number kernel values */
2704
2705             count=0;
2706             gamma=0.0;
2707             for (v=0; v < (ssize_t) kernel->height; v++) {
2708               if ( IsNan(*k) ) continue;
2709               alpha=QuantumScale*GetPixelAlpha(image,k_pixels);
2710               gamma += alpha; /* normalize alpha weights only */
2711               count++;        /* number of alpha values collected */
2712               alpha*=(*k);    /* include kernel weighting now */
2713               result.red     += alpha*GetPixelRed(image,k_pixels);
2714               result.green   += alpha*GetPixelGreen(image,k_pixels);
2715               result.blue    += alpha*GetPixelBlue(image,k_pixels);
2716               if (image->colorspace == CMYKColorspace)
2717                 result.black += alpha*GetPixelBlack(image,k_pixels);
2718               result.alpha   += (*k)*GetPixelAlpha(image,k_pixels);
2719               k--;
2720               k_pixels+=GetPixelChannels(image);
2721             }
2722             /* Sync'ed channels, all channels are modified */
2723             gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2724             SetPixelRed(morphology_image,ClampToQuantum(gamma*result.red),q);
2725             SetPixelGreen(morphology_image,ClampToQuantum(gamma*result.green),q);
2726             SetPixelBlue(morphology_image,ClampToQuantum(gamma*result.blue),q);
2727             if (image->colorspace == CMYKColorspace)
2728               SetPixelBlack(morphology_image,ClampToQuantum(gamma*result.black),q);
2729             SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2730           }
2731
2732         /* Count up changed pixels */
2733         if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q))
2734             || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q))
2735             || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q))
2736             || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q))
2737             || ((image->colorspace == CMYKColorspace) &&
2738                 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
2739           changed++;  /* The pixel was changed in some way! */
2740         p+=GetPixelChannels(image);
2741         q+=GetPixelChannels(morphology_image);
2742       } /* y */
2743       if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
2744         status=MagickFalse;
2745       if (image->progress_monitor != (MagickProgressMonitor) NULL)
2746         {
2747           MagickBooleanType
2748             proceed;
2749
2750 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2751           #pragma omp critical (MagickCore_MorphologyImage)
2752 #endif
2753           proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
2754           if (proceed == MagickFalse)
2755             status=MagickFalse;
2756         }
2757     } /* x */
2758     morphology_image->type=image->type;
2759     morphology_view=DestroyCacheView(morphology_view);
2760     image_view=DestroyCacheView(image_view);
2761     return(status ? (ssize_t) changed : 0);
2762   }
2763
2764   /*
2765   ** Normal handling of horizontal or rectangular kernels (row by row)
2766   */
2767 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2768   #pragma omp parallel for schedule(static,4) shared(progress,status) \
2769     if ((image->rows*image->columns) > 8192) \
2770       num_threads(GetMagickResourceLimit(ThreadResource))
2771 #endif
2772   for (y=0; y < (ssize_t) image->rows; y++)
2773   {
2774     register const Quantum
2775       *restrict p;
2776
2777     register Quantum
2778       *restrict q;
2779
2780     register ssize_t
2781       x;
2782
2783     size_t
2784       r;
2785
2786     if (status == MagickFalse)
2787       continue;
2788     p=GetCacheViewVirtualPixels(image_view, -offx, y-offy, virt_width,
2789       kernel->height,  exception);
2790     q=GetCacheViewAuthenticPixels(morphology_view,0,y,
2791       morphology_image->columns,1,exception);
2792     if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2793       {
2794         status=MagickFalse;
2795         continue;
2796       }
2797     /* offset to origin in 'p'. while 'q' points to it directly */
2798     r = virt_width*offy + offx;
2799
2800     for (x=0; x < (ssize_t) image->columns; x++)
2801     {
2802        ssize_t
2803         v;
2804
2805       register ssize_t
2806         u;
2807
2808       register const double
2809         *restrict k;
2810
2811       register const Quantum
2812         *restrict k_pixels;
2813
2814       PixelInfo
2815         result,
2816         min,
2817         max;
2818
2819       /* Copy input image to the output image for unused channels
2820        * This removes need for 'cloning' a new image every iteration
2821        */
2822       SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2823         GetPixelChannels(image)),q);
2824       SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2825         GetPixelChannels(image)),q);
2826       SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2827         GetPixelChannels(image)),q);
2828       if (image->colorspace == CMYKColorspace)
2829         SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2830           GetPixelChannels(image)),q);
2831
2832       /* Defaults */
2833       min.red     =
2834       min.green   =
2835       min.blue    =
2836       min.alpha =
2837       min.black   = (MagickRealType) QuantumRange;
2838       max.red     =
2839       max.green   =
2840       max.blue    =
2841       max.alpha =
2842       max.black   = (MagickRealType) 0;
2843       /* default result is the original pixel value */
2844       result.red     = (MagickRealType) GetPixelRed(image,p+r*GetPixelChannels(image));
2845       result.green   = (MagickRealType) GetPixelGreen(image,p+r*GetPixelChannels(image));
2846       result.blue    = (MagickRealType) GetPixelBlue(image,p+r*GetPixelChannels(image));
2847       result.black   = 0.0;
2848       if (image->colorspace == CMYKColorspace)
2849         result.black = (MagickRealType) GetPixelBlack(image,p+r*GetPixelChannels(image));
2850       result.alpha=(MagickRealType) GetPixelAlpha(image,p+r*GetPixelChannels(image));
2851
2852       switch (method) {
2853         case ConvolveMorphology:
2854           /* Set the bias of the weighted average output */
2855           result.red     =
2856           result.green   =
2857           result.blue    =
2858           result.alpha =
2859           result.black   = bias;
2860           break;
2861         case DilateIntensityMorphology:
2862         case ErodeIntensityMorphology:
2863           /* use a boolean flag indicating when first match found */
2864           result.red = 0.0;  /* result is not used otherwise */
2865           break;
2866         default:
2867           break;
2868       }
2869
2870       switch ( method ) {
2871         case ConvolveMorphology:
2872             /* Weighted Average of pixels using reflected kernel
2873             **
2874             ** NOTE for correct working of this operation for asymetrical
2875             ** kernels, the kernel needs to be applied in its reflected form.
2876             ** That is its values needs to be reversed.
2877             **
2878             ** Correlation is actually the same as this but without reflecting
2879             ** the kernel, and thus 'lower-level' that Convolution.  However
2880             ** as Convolution is the more common method used, and it does not
2881             ** really cost us much in terms of processing to use a reflected
2882             ** kernel, so it is Convolution that is implemented.
2883             **
2884             ** Correlation will have its kernel reflected before calling
2885             ** this function to do a Convolve.
2886             **
2887             ** For more details of Correlation vs Convolution see
2888             **   http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
2889             */
2890             k = &kernel->values[ kernel->width*kernel->height-1 ];
2891             k_pixels = p;
2892             if ( (image->channel_mask != DefaultChannels) ||
2893                  (image->matte == MagickFalse) )
2894               { /* No 'Sync' involved.
2895                 ** Convolution is simple greyscale channel operation
2896                 */
2897                 for (v=0; v < (ssize_t) kernel->height; v++) {
2898                   for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2899                     if ( IsNan(*k) ) continue;
2900                     result.red     += (*k)*
2901                       GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2902                     result.green   += (*k)*
2903                       GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2904                     result.blue    += (*k)*
2905                       GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2906                     if (image->colorspace == CMYKColorspace)
2907                       result.black += (*k)*
2908                         GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2909                     result.alpha += (*k)*
2910                       GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2911                   }
2912                   k_pixels += virt_width*GetPixelChannels(image);
2913                 }
2914                 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2915                   SetPixelRed(morphology_image,ClampToQuantum(result.red),
2916                     q);
2917                 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2918                   SetPixelGreen(morphology_image,ClampToQuantum(result.green),
2919                     q);
2920                 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2921                   SetPixelBlue(morphology_image,ClampToQuantum(result.blue),
2922                     q);
2923                 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2924                     (image->colorspace == CMYKColorspace))
2925                   SetPixelBlack(morphology_image,ClampToQuantum(result.black),
2926                     q);
2927                 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2928                     (image->matte == MagickTrue))
2929                   SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),
2930                     q);
2931               }
2932             else
2933               { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2934                 ** Weight the color channels with Alpha Channel so that
2935                 ** transparent pixels are not part of the results.
2936                 */
2937                 MagickRealType
2938                   alpha,  /* alpha weighting for colors : alpha  */
2939                   gamma;  /* divisor, sum of color alpha weighting */
2940                 size_t
2941                   count;  /* alpha valus collected, number kernel values */
2942
2943                 count=0;
2944                 gamma=0.0;
2945                 for (v=0; v < (ssize_t) kernel->height; v++) {
2946                   for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2947                     if ( IsNan(*k) ) continue;
2948                     alpha=QuantumScale*GetPixelAlpha(image,
2949                                 k_pixels+u*GetPixelChannels(image));
2950                     gamma += alpha;    /* normalize alpha weights only */
2951                     count++;           /* number of alpha values collected */
2952                     alpha=alpha*(*k);  /* include kernel weighting now */
2953                     result.red     += alpha*
2954                       GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2955                     result.green   += alpha*
2956                       GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2957                     result.blue    += alpha*
2958                       GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2959                     if (image->colorspace == CMYKColorspace)
2960                       result.black += alpha*
2961                         GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2962                     result.alpha   += (*k)*
2963                       GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2964                   }
2965                   k_pixels += virt_width*GetPixelChannels(image);
2966                 }
2967                 /* Sync'ed channels, all channels are modified */
2968                 gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2969                 SetPixelRed(morphology_image,
2970                   ClampToQuantum(gamma*result.red),q);
2971                 SetPixelGreen(morphology_image,
2972                   ClampToQuantum(gamma*result.green),q);
2973                 SetPixelBlue(morphology_image,
2974                   ClampToQuantum(gamma*result.blue),q);
2975                 if (image->colorspace == CMYKColorspace)
2976                   SetPixelBlack(morphology_image,
2977                     ClampToQuantum(gamma*result.black),q);
2978                 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2979               }
2980             break;
2981
2982         case ErodeMorphology:
2983             /* Minimum Value within kernel neighbourhood
2984             **
2985             ** NOTE that the kernel is not reflected for this operation!
2986             **
2987             ** NOTE: in normal Greyscale Morphology, the kernel value should
2988             ** be added to the real value, this is currently not done, due to
2989             ** the nature of the boolean kernels being used.
2990             */
2991             k = kernel->values;
2992             k_pixels = p;
2993             for (v=0; v < (ssize_t) kernel->height; v++) {
2994               for (u=0; u < (ssize_t) kernel->width; u++, k++) {
2995                 if ( IsNan(*k) || (*k) < 0.5 ) continue;
2996                 Minimize(min.red,     (double)
2997                   GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
2998                 Minimize(min.green,   (double)
2999                   GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3000                 Minimize(min.blue,    (double)
3001                   GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3002                 Minimize(min.alpha,   (double)
3003                   GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3004                 if (image->colorspace == CMYKColorspace)
3005                   Minimize(min.black,  (double)
3006                     GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3007               }
3008               k_pixels += virt_width*GetPixelChannels(image);
3009             }
3010             break;
3011
3012         case DilateMorphology:
3013             /* Maximum Value within kernel neighbourhood
3014             **
3015             ** NOTE for correct working of this operation for asymetrical
3016             ** kernels, the kernel needs to be applied in its reflected form.
3017             ** That is its values needs to be reversed.
3018             **
3019             ** NOTE: in normal Greyscale Morphology, the kernel value should
3020             ** be added to the real value, this is currently not done, due to
3021             ** the nature of the boolean kernels being used.
3022             **
3023             */
3024             k = &kernel->values[ kernel->width*kernel->height-1 ];
3025             k_pixels = p;
3026             for (v=0; v < (ssize_t) kernel->height; v++) {
3027               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3028                 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3029                 Maximize(max.red,     (double)
3030                   GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3031                 Maximize(max.green,   (double)
3032                   GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3033                 Maximize(max.blue,    (double)
3034                   GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3035                 Maximize(max.alpha,   (double)
3036                   GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3037                 if (image->colorspace == CMYKColorspace)
3038                   Maximize(max.black,   (double)
3039                     GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3040               }
3041               k_pixels += virt_width*GetPixelChannels(image);
3042             }
3043             break;
3044
3045         case HitAndMissMorphology:
3046         case ThinningMorphology:
3047         case ThickenMorphology:
3048             /* Minimum of Foreground Pixel minus Maxumum of Background Pixels
3049             **
3050             ** NOTE that the kernel is not reflected for this operation,
3051             ** and consists of both foreground and background pixel
3052             ** neighbourhoods, 0.0 for background, and 1.0 for foreground
3053             ** with either Nan or 0.5 values for don't care.
3054             **
3055             ** Note that this will never produce a meaningless negative
3056             ** result.  Such results can cause Thinning/Thicken to not work
3057             ** correctly when used against a greyscale image.
3058             */
3059             k = kernel->values;
3060             k_pixels = p;
3061             for (v=0; v < (ssize_t) kernel->height; v++) {
3062               for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3063                 if ( IsNan(*k) ) continue;
3064                 if ( (*k) > 0.7 )
3065                 { /* minimim of foreground pixels */
3066                   Minimize(min.red,     (double)
3067                     GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3068                   Minimize(min.green,   (double)
3069                     GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3070                   Minimize(min.blue,    (double)
3071                     GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3072                   Minimize(min.alpha,(double)
3073                     GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3074                   if ( image->colorspace == CMYKColorspace)
3075                     Minimize(min.black,(double)
3076                       GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3077                 }
3078                 else if ( (*k) < 0.3 )
3079                 { /* maximum of background pixels */
3080                   Maximize(max.red,     (double)
3081                     GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3082                   Maximize(max.green,   (double)
3083                     GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3084                   Maximize(max.blue,    (double)
3085                     GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3086                   Maximize(max.alpha,(double)
3087                     GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3088                   if (image->colorspace == CMYKColorspace)
3089                     Maximize(max.black,   (double)
3090                       GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3091                 }
3092               }
3093               k_pixels += virt_width*GetPixelChannels(image);
3094             }
3095             /* Pattern Match if difference is positive */
3096             min.red     -= max.red;     Maximize( min.red,     0.0 );
3097             min.green   -= max.green;   Maximize( min.green,   0.0 );
3098             min.blue    -= max.blue;    Maximize( min.blue,    0.0 );
3099             min.black   -= max.black;   Maximize( min.black,   0.0 );
3100             min.alpha -= max.alpha; Maximize( min.alpha, 0.0 );
3101             break;
3102
3103         case ErodeIntensityMorphology:
3104             /* Select Pixel with Minimum Intensity within kernel neighbourhood
3105             **
3106             ** WARNING: the intensity test fails for CMYK and does not
3107             ** take into account the moderating effect of the alpha channel
3108             ** on the intensity.
3109             **
3110             ** NOTE that the kernel is not reflected for this operation!
3111             */
3112             k = kernel->values;
3113             k_pixels = p;
3114             for (v=0; v < (ssize_t) kernel->height; v++) {
3115               for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3116                 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3117                 if ( result.red == 0.0 ||
3118                      GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) < GetPixelIntensity(morphology_image,q) ) {
3119                   /* copy the whole pixel - no channel selection */
3120                   SetPixelRed(morphology_image,GetPixelRed(image,
3121                     k_pixels+u*GetPixelChannels(image)),q);
3122                   SetPixelGreen(morphology_image,GetPixelGreen(image,
3123                     k_pixels+u*GetPixelChannels(image)),q);
3124                   SetPixelBlue(morphology_image,GetPixelBlue(image,
3125                     k_pixels+u*GetPixelChannels(image)),q);
3126                   SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3127                     k_pixels+u*GetPixelChannels(image)),q);
3128                   if ( result.red > 0.0 ) changed++;
3129                   result.red = 1.0;
3130                 }
3131               }
3132               k_pixels += virt_width*GetPixelChannels(image);
3133             }
3134             break;
3135
3136         case DilateIntensityMorphology:
3137             /* Select Pixel with Maximum Intensity within kernel neighbourhood
3138             **
3139             ** WARNING: the intensity test fails for CMYK and does not
3140             ** take into account the moderating effect of the alpha channel
3141             ** on the intensity (yet).
3142             **
3143             ** NOTE for correct working of this operation for asymetrical
3144             ** kernels, the kernel needs to be applied in its reflected form.
3145             ** That is its values needs to be reversed.
3146             */
3147             k = &kernel->values[ kernel->width*kernel->height-1 ];
3148             k_pixels = p;
3149             for (v=0; v < (ssize_t) kernel->height; v++) {
3150               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3151                 if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */
3152                 if ( result.red == 0.0 ||
3153                      GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) > GetPixelIntensity(morphology_image,q) ) {
3154                   /* copy the whole pixel - no channel selection */
3155                   SetPixelRed(morphology_image,GetPixelRed(image,
3156                     k_pixels+u*GetPixelChannels(image)),q);
3157                   SetPixelGreen(morphology_image,GetPixelGreen(image,
3158                     k_pixels+u*GetPixelChannels(image)),q);
3159                   SetPixelBlue(morphology_image,GetPixelBlue(image,
3160                     k_pixels+u*GetPixelChannels(image)),q);
3161                   SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3162                     k_pixels+u*GetPixelChannels(image)),q);
3163                   if ( result.red > 0.0 ) changed++;
3164                   result.red = 1.0;
3165                 }
3166               }
3167               k_pixels += virt_width*GetPixelChannels(image);
3168             }
3169             break;
3170
3171         case IterativeDistanceMorphology:
3172             /* Work out an iterative distance from black edge of a white image
3173             ** shape.  Essentually white values are decreased to the smallest
3174             ** 'distance from edge' it can find.
3175             **
3176             ** It works by adding kernel values to the neighbourhood, and and
3177             ** select the minimum value found. The kernel is rotated before
3178             ** use, so kernel distances match resulting distances, when a user
3179             ** provided asymmetric kernel is applied.
3180             **
3181             **
3182             ** This code is almost identical to True GrayScale Morphology But
3183             ** not quite.
3184             **
3185             ** GreyDilate  Kernel values added, maximum value found Kernel is
3186             ** rotated before use.
3187             **
3188             ** GrayErode:  Kernel values subtracted and minimum value found No
3189             ** kernel rotation used.
3190             **
3191             ** Note the the Iterative Distance method is essentially a
3192             ** GrayErode, but with negative kernel values, and kernel
3193             ** rotation applied.
3194             */
3195             k = &kernel->values[ kernel->width*kernel->height-1 ];
3196             k_pixels = p;
3197             for (v=0; v < (ssize_t) kernel->height; v++) {
3198               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3199                 if ( IsNan(*k) ) continue;
3200                 Minimize(result.red,     (*k)+(double)
3201                      GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3202                 Minimize(result.green,   (*k)+(double)
3203                      GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3204                 Minimize(result.blue,    (*k)+(double)
3205                      GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3206                 Minimize(result.alpha,   (*k)+(double)
3207                      GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3208                 if ( image->colorspace == CMYKColorspace)
3209                   Maximize(result.black, (*k)+(double)
3210                       GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3211               }
3212               k_pixels += virt_width*GetPixelChannels(image);
3213             }
3214             break;
3215
3216         case UndefinedMorphology:
3217         default:
3218             break; /* Do nothing */
3219       }
3220       /* Final mathematics of results (combine with original image?)
3221       **
3222       ** NOTE: Difference Morphology operators Edge* and *Hat could also
3223       ** be done here but works better with iteration as a image difference
3224       ** in the controling function (below).  Thicken and Thinning however
3225       ** should be done here so thay can be iterated correctly.
3226       */
3227       switch ( method ) {
3228         case HitAndMissMorphology:
3229         case ErodeMorphology:
3230           result = min;    /* minimum of neighbourhood */
3231           break;
3232         case DilateMorphology:
3233           result = max;    /* maximum of neighbourhood */
3234           break;
3235         case ThinningMorphology:
3236           /* subtract pattern match from original */
3237           result.red     -= min.red;
3238           result.green   -= min.green;
3239           result.blue    -= min.blue;
3240           result.black   -= min.black;
3241           result.alpha   -= min.alpha;
3242           break;
3243         case ThickenMorphology:
3244           /* Add the pattern matchs to the original */
3245           result.red     += min.red;
3246           result.green   += min.green;
3247           result.blue    += min.blue;
3248           result.black   += min.black;
3249           result.alpha   += min.alpha;
3250           break;
3251         default:
3252           /* result directly calculated or assigned */
3253           break;
3254       }
3255       /* Assign the resulting pixel values - Clamping Result */
3256       switch ( method ) {
3257         case UndefinedMorphology:
3258         case ConvolveMorphology:
3259         case DilateIntensityMorphology:
3260         case ErodeIntensityMorphology:
3261           break;  /* full pixel was directly assigned - not a channel method */
3262         default:
3263           if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3264             SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
3265           if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3266             SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
3267           if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3268             SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
3269           if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3270               (image->colorspace == CMYKColorspace))
3271             SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
3272           if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
3273               (image->matte == MagickTrue))
3274             SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
3275           break;
3276       }
3277       /* Count up changed pixels */
3278       if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q)) ||
3279           (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q)) ||
3280           (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q)) ||
3281           (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q)) ||
3282           ((image->colorspace == CMYKColorspace) &&
3283            (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
3284         changed++;  /* The pixel was changed in some way! */
3285       p+=GetPixelChannels(image);
3286       q+=GetPixelChannels(morphology_image);
3287     } /* x */
3288     if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
3289       status=MagickFalse;
3290     if (image->progress_monitor != (MagickProgressMonitor) NULL)
3291       {
3292         MagickBooleanType
3293           proceed;
3294
3295 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3296         #pragma omp critical (MagickCore_MorphologyImage)
3297 #endif
3298         proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
3299         if (proceed == MagickFalse)
3300           status=MagickFalse;
3301       }
3302   } /* y */
3303   morphology_view=DestroyCacheView(morphology_view);
3304   image_view=DestroyCacheView(image_view);
3305   return(status ? (ssize_t)changed : -1);
3306 }
3307
3308 /* This is almost identical to the MorphologyPrimative() function above,
3309 ** but will apply the primitive directly to the actual image using two
3310 ** passes, once in each direction, with the results of the previous (and
3311 ** current) row being re-used.
3312 **
3313 ** That is after each row is 'Sync'ed' into the image, the next row will
3314 ** make use of those values as part of the calculation of the next row.
3315 ** It then repeats, but going in the oppisite (bottom-up) direction.
3316 **
3317 ** Because of this 're-use of results' this function can not make use
3318 ** of multi-threaded, parellel processing.
3319 */
3320 static ssize_t MorphologyPrimitiveDirect(Image *image,
3321   const MorphologyMethod method,const KernelInfo *kernel,
3322   ExceptionInfo *exception)
3323 {
3324   CacheView
3325     *auth_view,
3326     *virt_view;
3327
3328   MagickBooleanType
3329     status;
3330
3331   MagickOffsetType
3332     progress;
3333
3334   ssize_t
3335     y, offx, offy;
3336
3337   size_t
3338     virt_width,
3339     changed;
3340
3341   status=MagickTrue;
3342   changed=0;
3343   progress=0;
3344
3345   assert(image != (Image *) NULL);
3346   assert(image->signature == MagickSignature);
3347   assert(kernel != (KernelInfo *) NULL);
3348   assert(kernel->signature == MagickSignature);
3349   assert(exception != (ExceptionInfo *) NULL);
3350   assert(exception->signature == MagickSignature);
3351
3352   /* Some methods (including convolve) needs use a reflected kernel.
3353    * Adjust 'origin' offsets to loop though kernel as a reflection.
3354    */
3355   offx = kernel->x;
3356   offy = kernel->y;
3357   switch(method) {
3358     case DistanceMorphology:
3359     case VoronoiMorphology:
3360       /* kernel needs to used with reflection about origin */
3361       offx = (ssize_t) kernel->width-offx-1;
3362       offy = (ssize_t) kernel->height-offy-1;
3363       break;
3364 #if 0
3365     case ?????Morphology:
3366       /* kernel is used as is, without reflection */
3367       break;
3368 #endif
3369     default:
3370       assert("Not a PrimativeDirect Morphology Method" != (char *) NULL);
3371       break;
3372   }
3373
3374   /* DO NOT THREAD THIS CODE! */
3375   /* two views into same image (virtual, and actual) */
3376   virt_view=AcquireVirtualCacheView(image,exception);
3377   auth_view=AcquireAuthenticCacheView(image,exception);
3378   virt_width=image->columns+kernel->width-1;
3379
3380   for (y=0; y < (ssize_t) image->rows; y++)
3381   {
3382     register const Quantum
3383       *restrict p;
3384
3385     register Quantum
3386       *restrict q;
3387
3388     register ssize_t
3389       x;
3390
3391     ssize_t
3392       r;
3393
3394     /* NOTE read virtual pixels, and authentic pixels, from the same image!
3395     ** we read using virtual to get virtual pixel handling, but write back
3396     ** into the same image.
3397     **
3398     ** Only top half of kernel is processed as we do a single pass downward
3399     ** through the image iterating the distance function as we go.
3400     */
3401     if (status == MagickFalse)
3402       break;
3403     p=GetCacheViewVirtualPixels(virt_view,-offx,y-offy,virt_width,(size_t)
3404       offy+1,exception);
3405     q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3406       exception);
3407     if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3408       status=MagickFalse;
3409     if (status == MagickFalse)
3410       break;
3411
3412     /* offset to origin in 'p'. while 'q' points to it directly */
3413     r = (ssize_t) virt_width*offy + offx;
3414
3415     for (x=0; x < (ssize_t) image->columns; x++)
3416     {
3417       ssize_t
3418         v;
3419
3420       register ssize_t
3421         u;
3422
3423       register const double
3424         *restrict k;
3425
3426       register const Quantum
3427         *restrict k_pixels;
3428
3429       PixelInfo
3430         result;
3431
3432       /* Starting Defaults */
3433       GetPixelInfo(image,&result);
3434       GetPixelInfoPixel(image,q,&result);
3435       if ( method != VoronoiMorphology )
3436         result.alpha = QuantumRange - result.alpha;
3437
3438       switch ( method ) {
3439         case DistanceMorphology:
3440             /* Add kernel Value and select the minimum value found. */
3441             k = &kernel->values[ kernel->width*kernel->height-1 ];
3442             k_pixels = p;
3443             for (v=0; v <= (ssize_t) offy; v++) {
3444               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3445                 if ( IsNan(*k) ) continue;
3446                 Minimize(result.red,     (*k)+
3447                   GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3448                 Minimize(result.green,   (*k)+
3449                   GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3450                 Minimize(result.blue,    (*k)+
3451                   GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3452                 if (image->colorspace == CMYKColorspace)
3453                   Minimize(result.black,(*k)+
3454                     GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3455                 Minimize(result.alpha, (*k)+
3456                   GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3457               }
3458               k_pixels += virt_width*GetPixelChannels(image);
3459             }
3460             /* repeat with the just processed pixels of this row */
3461             k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3462             k_pixels = q-offx*GetPixelChannels(image);
3463               for (u=0; u < (ssize_t) offx; u++, k--) {
3464                 if ( x+u-offx < 0 ) continue;  /* off the edge! */
3465                 if ( IsNan(*k) ) continue;
3466                 Minimize(result.red,     (*k)+
3467                   GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3468                 Minimize(result.green,   (*k)+
3469                   GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3470                 Minimize(result.blue,    (*k)+
3471                   GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3472                 if (image->colorspace == CMYKColorspace)
3473                   Minimize(result.black,(*k)+
3474                     GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3475                 Minimize(result.alpha,(*k)+
3476                   GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3477               }
3478             break;
3479         case VoronoiMorphology:
3480             /* Apply Distance to 'Matte' channel, while coping the color
3481             ** values of the closest pixel.
3482             **
3483             ** This is experimental, and realy the 'alpha' component should
3484             ** be completely separate 'masking' channel so that alpha can
3485             ** also be used as part of the results.
3486             */
3487             k = &kernel->values[ kernel->width*kernel->height-1 ];
3488             k_pixels = p;
3489             for (v=0; v <= (ssize_t) offy; v++) {
3490               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3491                 if ( IsNan(*k) ) continue;
3492                 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3493                   {
3494                     GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3495                       &result);
3496                     result.alpha += *k;
3497                   }
3498               }
3499               k_pixels += virt_width*GetPixelChannels(image);
3500             }
3501             /* repeat with the just processed pixels of this row */
3502             k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3503             k_pixels = q-offx*GetPixelChannels(image);
3504               for (u=0; u < (ssize_t) offx; u++, k--) {
3505                 if ( x+u-offx < 0 ) continue;  /* off the edge! */
3506                 if ( IsNan(*k) ) continue;
3507                 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3508                   {
3509                     GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3510                       &result);
3511                     result.alpha += *k;
3512                   }
3513               }
3514             break;
3515         default:
3516           /* result directly calculated or assigned */
3517           break;
3518       }
3519       /* Assign the resulting pixel values - Clamping Result */
3520       switch ( method ) {
3521         case VoronoiMorphology:
3522           SetPixelInfoPixel(image,&result,q);
3523           break;
3524         default:
3525           if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3526             SetPixelRed(image,ClampToQuantum(result.red),q);
3527           if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3528             SetPixelGreen(image,ClampToQuantum(result.green),q);
3529           if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3530             SetPixelBlue(image,ClampToQuantum(result.blue),q);
3531           if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3532               (image->colorspace == CMYKColorspace))
3533             SetPixelBlack(image,ClampToQuantum(result.black),q);
3534           if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3535               (image->matte == MagickTrue))
3536             SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3537           break;
3538       }
3539       /* Count up changed pixels */
3540       if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q)) ||
3541           (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q)) ||
3542           (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q)) ||
3543           (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q)) ||
3544           ((image->colorspace == CMYKColorspace) &&
3545            (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3546         changed++;  /* The pixel was changed in some way! */
3547
3548       p+=GetPixelChannels(image); /* increment pixel buffers */
3549       q+=GetPixelChannels(image);
3550     } /* x */
3551
3552     if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3553       status=MagickFalse;
3554     if (image->progress_monitor != (MagickProgressMonitor) NULL)
3555       if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3556                 == MagickFalse )
3557         status=MagickFalse;
3558
3559   } /* y */
3560
3561   /* Do the reversed pass through the image */
3562   for (y=(ssize_t)image->rows-1; y >= 0; y--)
3563   {
3564     register const Quantum
3565       *restrict p;
3566
3567     register Quantum
3568       *restrict q;
3569
3570     register ssize_t
3571       x;
3572
3573     ssize_t
3574       r;
3575
3576     if (status == MagickFalse)
3577       break;
3578     /* NOTE read virtual pixels, and authentic pixels, from the same image!
3579     ** we read using virtual to get virtual pixel handling, but write back
3580     ** into the same image.
3581     **
3582     ** Only the bottom half of the kernel will be processes as we
3583     ** up the image.
3584     */
3585     p=GetCacheViewVirtualPixels(virt_view,-offx,y,virt_width,(size_t)
3586       kernel->y+1,exception);
3587     q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3588       exception);
3589     if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3590       status=MagickFalse;
3591     if (status == MagickFalse)
3592       break;
3593
3594     /* adjust positions to end of row */
3595     p += (image->columns-1)*GetPixelChannels(image);
3596     q += (image->columns-1)*GetPixelChannels(image);
3597
3598     /* offset to origin in 'p'. while 'q' points to it directly */
3599     r = offx;
3600
3601     for (x=(ssize_t)image->columns-1; x >= 0; x--)
3602     {
3603       ssize_t
3604         v;
3605
3606       register ssize_t
3607         u;
3608
3609       register const double
3610         *restrict k;
3611
3612       register const Quantum
3613         *restrict k_pixels;
3614
3615       PixelInfo
3616         result;
3617
3618       /* Default - previously modified pixel */
3619       GetPixelInfo(image,&result);
3620       GetPixelInfoPixel(image,q,&result);
3621       if ( method != VoronoiMorphology )
3622         result.alpha = QuantumRange - result.alpha;
3623
3624       switch ( method ) {
3625         case DistanceMorphology:
3626             /* Add kernel Value and select the minimum value found. */
3627             k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3628             k_pixels = p;
3629             for (v=offy; v < (ssize_t) kernel->height; v++) {
3630               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3631                 if ( IsNan(*k) ) continue;
3632                 Minimize(result.red,     (*k)+
3633                   GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3634                 Minimize(result.green,   (*k)+
3635                   GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3636                 Minimize(result.blue,    (*k)+
3637                   GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3638                 if ( image->colorspace == CMYKColorspace)
3639                   Minimize(result.black,(*k)+
3640                     GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3641                 Minimize(result.alpha, (*k)+
3642                   GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3643               }
3644               k_pixels += virt_width*GetPixelChannels(image);
3645             }
3646             /* repeat with the just processed pixels of this row */
3647             k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3648             k_pixels = q-offx*GetPixelChannels(image);
3649               for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3650                 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3651                 if ( IsNan(*k) ) continue;
3652                 Minimize(result.red,     (*k)+
3653                   GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3654                 Minimize(result.green,   (*k)+
3655                   GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3656                 Minimize(result.blue,    (*k)+
3657                   GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3658                 if ( image->colorspace == CMYKColorspace)
3659                   Minimize(result.black,   (*k)+
3660                     GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3661                 Minimize(result.alpha, (*k)+
3662                   GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3663               }
3664             break;
3665         case VoronoiMorphology:
3666             /* Apply Distance to 'Matte' channel, coping the closest color.
3667             **
3668             ** This is experimental, and realy the 'alpha' component should
3669             ** be completely separate 'masking' channel.
3670             */
3671             k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3672             k_pixels = p;
3673             for (v=offy; v < (ssize_t) kernel->height; v++) {
3674               for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3675                 if ( IsNan(*k) ) continue;
3676                 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3677                   {
3678                     GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3679                       &result);
3680                     result.alpha += *k;
3681                   }
3682               }
3683               k_pixels += virt_width*GetPixelChannels(image);
3684             }
3685             /* repeat with the just processed pixels of this row */
3686             k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3687             k_pixels = q-offx*GetPixelChannels(image);
3688               for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3689                 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3690                 if ( IsNan(*k) ) continue;
3691                 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3692                   {
3693                     GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3694                       &result);
3695                     result.alpha += *k;
3696                   }
3697               }
3698             break;
3699         default:
3700           /* result directly calculated or assigned */
3701           break;
3702       }
3703       /* Assign the resulting pixel values - Clamping Result */
3704       switch ( method ) {
3705         case VoronoiMorphology:
3706           SetPixelInfoPixel(image,&result,q);
3707           break;
3708         default:
3709           if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3710             SetPixelRed(image,ClampToQuantum(result.red),q);
3711           if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3712             SetPixelGreen(image,ClampToQuantum(result.green),q);
3713           if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3714             SetPixelBlue(image,ClampToQuantum(result.blue),q);
3715           if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3716               (image->colorspace == CMYKColorspace))
3717             SetPixelBlack(image,ClampToQuantum(result.black),q);
3718           if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3719               (image->matte == MagickTrue))
3720             SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3721           break;
3722       }
3723       /* Count up changed pixels */
3724       if (   (GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q))
3725           || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q))
3726           || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q))
3727           || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q))
3728           || ((image->colorspace == CMYKColorspace) &&
3729               (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3730         changed++;  /* The pixel was changed in some way! */
3731
3732       p-=GetPixelChannels(image); /* go backward through pixel buffers */
3733       q-=GetPixelChannels(image);
3734     } /* x */
3735     if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3736       status=MagickFalse;
3737     if (image->progress_monitor != (MagickProgressMonitor) NULL)
3738       if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3739                 == MagickFalse )
3740         status=MagickFalse;
3741
3742   } /* y */
3743
3744   auth_view=DestroyCacheView(auth_view);
3745   virt_view=DestroyCacheView(virt_view);
3746   return(status ? (ssize_t) changed : -1);
3747 }
3748
3749 /* Apply a Morphology by calling one of the above low level primitive
3750 ** application functions.  This function handles any iteration loops,
3751 ** composition or re-iteration of results, and compound morphology methods
3752 ** that is based on multiple low-level (staged) morphology methods.
3753 **
3754 ** Basically this provides the complex glue between the requested morphology
3755 ** method and raw low-level implementation (above).
3756 */
3757 MagickPrivate Image *MorphologyApply(const Image *image,
3758   const MorphologyMethod method, const ssize_t iterations,
3759   const KernelInfo *kernel, const CompositeOperator compose,const double bias,
3760   ExceptionInfo *exception)
3761 {
3762   CompositeOperator
3763     curr_compose;
3764
3765   Image
3766     *curr_image,    /* Image we are working with or iterating */
3767     *work_image,    /* secondary image for primitive iteration */
3768     *save_image,    /* saved image - for 'edge' method only */
3769     *rslt_image;    /* resultant image - after multi-kernel handling */
3770
3771   KernelInfo
3772     *reflected_kernel, /* A reflected copy of the kernel (if needed) */
3773     *norm_kernel,      /* the current normal un-reflected kernel */
3774     *rflt_kernel,      /* the current reflected kernel (if needed) */
3775     *this_kernel;      /* the kernel being applied */
3776
3777   MorphologyMethod
3778     primitive;      /* the current morphology primitive being applied */
3779
3780   CompositeOperator
3781     rslt_compose;   /* multi-kernel compose method for results to use */
3782
3783   MagickBooleanType
3784     special,        /* do we use a direct modify function? */
3785     verbose;        /* verbose output of results */
3786
3787   size_t
3788     method_loop,    /* Loop 1: number of compound method iterations (norm 1) */
3789     method_limit,   /*         maximum number of compound method iterations */
3790     kernel_number,  /* Loop 2: the kernel number being applied */
3791     stage_loop,     /* Loop 3: primitive loop for compound morphology */
3792     stage_limit,    /*         how many primitives are in this compound */
3793     kernel_loop,    /* Loop 4: iterate the kernel over image */
3794     kernel_limit,   /*         number of times to iterate kernel */
3795     count,          /* total count of primitive steps applied */
3796     kernel_changed, /* total count of changed using iterated kernel */
3797     method_changed; /* total count of changed over method iteration */
3798
3799   ssize_t
3800     changed;        /* number pixels changed by last primitive operation */
3801
3802   char
3803     v_info[80];
3804
3805   assert(image != (Image *) NULL);
3806   assert(image->signature == MagickSignature);
3807   assert(kernel != (KernelInfo *) NULL);
3808   assert(kernel->signature == MagickSignature);
3809   assert(exception != (ExceptionInfo *) NULL);
3810   assert(exception->signature == MagickSignature);
3811
3812   count = 0;      /* number of low-level morphology primitives performed */
3813   if ( iterations == 0 )
3814     return((Image *)NULL);   /* null operation - nothing to do! */
3815
3816   kernel_limit = (size_t) iterations;
3817   if ( iterations < 0 )  /* negative interations = infinite (well alomst) */
3818      kernel_limit = image->columns>image->rows ? image->columns : image->rows;
3819
3820   verbose = IsStringTrue(GetImageArtifact(image,"verbose"));
3821
3822   /* initialise for cleanup */
3823   curr_image = (Image *) image;
3824   curr_compose = image->compose;
3825   (void) curr_compose;
3826   work_image = save_image = rslt_image = (Image *) NULL;
3827   reflected_kernel = (KernelInfo *) NULL;
3828
3829   /* Initialize specific methods
3830    * + which loop should use the given iteratations
3831    * + how many primitives make up the compound morphology
3832    * + multi-kernel compose method to use (by default)
3833    */
3834   method_limit = 1;       /* just do method once, unless otherwise set */
3835   stage_limit = 1;        /* assume method is not a compound */
3836   special = MagickFalse;   /* assume it is NOT a direct modify primitive */
3837   rslt_compose = compose; /* and we are composing multi-kernels as given */
3838   switch( method ) {
3839     case SmoothMorphology:  /* 4 primitive compound morphology */
3840       stage_limit = 4;
3841       break;
3842     case OpenMorphology:    /* 2 primitive compound morphology */
3843     case OpenIntensityMorphology:
3844     case TopHatMorphology:
3845     case CloseMorphology:
3846     case CloseIntensityMorphology:
3847     case BottomHatMorphology:
3848     case EdgeMorphology:
3849       stage_limit = 2;
3850       break;
3851     case HitAndMissMorphology:
3852       rslt_compose = LightenCompositeOp;  /* Union of multi-kernel results */
3853       /* FALL THUR */
3854     case ThinningMorphology:
3855     case ThickenMorphology:
3856       method_limit = kernel_limit;  /* iterate the whole method */
3857       kernel_limit = 1;             /* do not do kernel iteration  */
3858       break;
3859     case DistanceMorphology:
3860     case VoronoiMorphology:
3861       special = MagickTrue;         /* use special direct primative */
3862       break;
3863     default:
3864       break;
3865   }
3866
3867   /* Apply special methods with special requirments
3868   ** For example, single run only, or post-processing requirements
3869   */
3870   if ( special == MagickTrue )
3871     {
3872       rslt_image=CloneImage(image,0,0,MagickTrue,exception);
3873       if (rslt_image == (Image *) NULL)
3874         goto error_cleanup;
3875       if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse)
3876         goto error_cleanup;
3877
3878       changed = MorphologyPrimitiveDirect(rslt_image, method,
3879          kernel, exception);
3880
3881       if ( IfMagickTrue(verbose) )
3882         (void) (void) FormatLocaleFile(stderr,
3883           "%s:%.20g.%.20g #%.20g => Changed %.20g\n",
3884           CommandOptionToMnemonic(MagickMorphologyOptions, method),
3885           1.0,0.0,1.0, (double) changed);
3886
3887       if ( changed < 0 )
3888         goto error_cleanup;
3889
3890       if ( method == VoronoiMorphology ) {
3891         /* Preserve the alpha channel of input image - but turned off */
3892         (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3893           exception);
3894         (void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp,
3895           MagickTrue,0,0,exception);
3896         (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3897           exception);
3898       }
3899       goto exit_cleanup;
3900     }
3901
3902   /* Handle user (caller) specified multi-kernel composition method */
3903   if ( compose != UndefinedCompositeOp )
3904     rslt_compose = compose;  /* override default composition for method */
3905   if ( rslt_compose == UndefinedCompositeOp )
3906     rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
3907
3908   /* Some methods require a reflected kernel to use with primitives.
3909    * Create the reflected kernel for those methods. */
3910   switch ( method ) {
3911     case CorrelateMorphology:
3912     case CloseMorphology:
3913     case CloseIntensityMorphology:
3914     case BottomHatMorphology:
3915     case SmoothMorphology:
3916       reflected_kernel = CloneKernelInfo(kernel);
3917       if (reflected_kernel == (KernelInfo *) NULL)
3918         goto error_cleanup;
3919       RotateKernelInfo(reflected_kernel,180);
3920       break;
3921     default:
3922       break;
3923   }
3924
3925   /* Loops around more primitive morpholgy methods
3926   **  erose, dilate, open, close, smooth, edge, etc...
3927   */
3928   /* Loop 1:  iterate the compound method */
3929   method_loop = 0;
3930   method_changed = 1;
3931   while ( method_loop < method_limit && method_changed > 0 ) {
3932     method_loop++;
3933     method_changed = 0;
3934
3935     /* Loop 2:  iterate over each kernel in a multi-kernel list */
3936     norm_kernel = (KernelInfo *) kernel;
3937     this_kernel = (KernelInfo *) kernel;
3938     rflt_kernel = reflected_kernel;
3939
3940     kernel_number = 0;
3941     while ( norm_kernel != NULL ) {
3942
3943       /* Loop 3: Compound Morphology Staging - Select Primative to apply */
3944       stage_loop = 0;          /* the compound morphology stage number */
3945       while ( stage_loop < stage_limit ) {
3946         stage_loop++;   /* The stage of the compound morphology */
3947
3948         /* Select primitive morphology for this stage of compound method */
3949         this_kernel = norm_kernel; /* default use unreflected kernel */
3950         primitive = method;        /* Assume method is a primitive */
3951         switch( method ) {
3952           case ErodeMorphology:      /* just erode */
3953           case EdgeInMorphology:     /* erode and image difference */
3954             primitive = ErodeMorphology;
3955             break;
3956           case DilateMorphology:     /* just dilate */
3957           case EdgeOutMorphology:    /* dilate and image difference */
3958             primitive = DilateMorphology;
3959             break;
3960           case OpenMorphology:       /* erode then dialate */
3961           case TopHatMorphology:     /* open and image difference */
3962             primitive = ErodeMorphology;
3963             if ( stage_loop == 2 )
3964               primitive = DilateMorphology;
3965             break;
3966           case OpenIntensityMorphology:
3967             primitive = ErodeIntensityMorphology;
3968             if ( stage_loop == 2 )
3969               primitive = DilateIntensityMorphology;
3970             break;
3971           case CloseMorphology:      /* dilate, then erode */
3972           case BottomHatMorphology:  /* close and image difference */
3973             this_kernel = rflt_kernel; /* use the reflected kernel */
3974             primitive = DilateMorphology;
3975             if ( stage_loop == 2 )
3976               primitive = ErodeMorphology;
3977             break;
3978           case CloseIntensityMorphology:
3979             this_kernel = rflt_kernel; /* use the reflected kernel */
3980             primitive = DilateIntensityMorphology;
3981             if ( stage_loop == 2 )
3982               primitive = ErodeIntensityMorphology;
3983             break;
3984           case SmoothMorphology:         /* open, close */
3985             switch ( stage_loop ) {
3986               case 1: /* start an open method, which starts with Erode */
3987                 primitive = ErodeMorphology;
3988                 break;
3989               case 2:  /* now Dilate the Erode */
3990                 primitive = DilateMorphology;
3991                 break;
3992               case 3:  /* Reflect kernel a close */
3993                 this_kernel = rflt_kernel; /* use the reflected kernel */
3994                 primitive = DilateMorphology;
3995                 break;
3996               case 4:  /* Finish the Close */
3997                 this_kernel = rflt_kernel; /* use the reflected kernel */
3998                 primitive = ErodeMorphology;
3999                 break;
4000             }
4001             break;
4002           case EdgeMorphology:        /* dilate and erode difference */
4003             primitive = DilateMorphology;
4004             if ( stage_loop == 2 ) {
4005               save_image = curr_image;      /* save the image difference */
4006               curr_image = (Image *) image;
4007               primitive = ErodeMorphology;
4008             }
4009             break;
4010           case CorrelateMorphology:
4011             /* A Correlation is a Convolution with a reflected kernel.
4012             ** However a Convolution is a weighted sum using a reflected
4013             ** kernel.  It may seem stange to convert a Correlation into a
4014             ** Convolution as the Correlation is the simplier method, but
4015             ** Convolution is much more commonly used, and it makes sense to
4016             ** implement it directly so as to avoid the need to duplicate the
4017             ** kernel when it is not required (which is typically the
4018             ** default).
4019             */
4020             this_kernel = rflt_kernel; /* use the reflected kernel */
4021             primitive = ConvolveMorphology;
4022             break;
4023           default:
4024             break;
4025         }
4026         assert( this_kernel != (KernelInfo *) NULL );
4027
4028         /* Extra information for debugging compound operations */
4029         if ( IfMagickTrue(verbose) ) {
4030           if ( stage_limit > 1 )
4031             (void) FormatLocaleString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ",
4032              CommandOptionToMnemonic(MagickMorphologyOptions,method),(double)
4033              method_loop,(double) stage_loop);
4034           else if ( primitive != method )
4035             (void) FormatLocaleString(v_info, MaxTextExtent, "%s:%.20g -> ",
4036               CommandOptionToMnemonic(MagickMorphologyOptions, method),(double)
4037               method_loop);
4038           else
4039             v_info[0] = '\0';
4040         }
4041
4042         /* Loop 4: Iterate the kernel with primitive */
4043         kernel_loop = 0;
4044         kernel_changed = 0;
4045         changed = 1;
4046         while ( kernel_loop < kernel_limit && changed > 0 ) {
4047           kernel_loop++;     /* the iteration of this kernel */
4048
4049           /* Create a clone as the destination image, if not yet defined */
4050           if ( work_image == (Image *) NULL )
4051             {
4052               work_image=CloneImage(image,0,0,MagickTrue,exception);
4053               if (work_image == (Image *) NULL)
4054                 goto error_cleanup;
4055               if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse)
4056                 goto error_cleanup;
4057               /* work_image->type=image->type; ??? */
4058             }
4059
4060           /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
4061           count++;
4062           changed = MorphologyPrimitive(curr_image, work_image, primitive,
4063                        this_kernel, bias, exception);
4064
4065           if ( IfMagickTrue(verbose) ) {
4066             if ( kernel_loop > 1 )
4067               (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */
4068             (void) (void) FormatLocaleFile(stderr,
4069               "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
4070               v_info,CommandOptionToMnemonic(MagickMorphologyOptions,
4071               primitive),(this_kernel == rflt_kernel ) ? "*" : "",
4072               (double) (method_loop+kernel_loop-1),(double) kernel_number,
4073               (double) count,(double) changed);
4074           }
4075           if ( changed < 0 )
4076             goto error_cleanup;
4077           kernel_changed += changed;
4078           method_changed += changed;
4079
4080           /* prepare next loop */
4081           { Image *tmp = work_image;   /* swap images for iteration */
4082             work_image = curr_image;
4083             curr_image = tmp;
4084           }
4085           if ( work_image == image )
4086             work_image = (Image *) NULL; /* replace input 'image' */
4087
4088         } /* End Loop 4: Iterate the kernel with primitive */
4089
4090         if ( IfMagickTrue(verbose) && kernel_changed != (size_t)changed )
4091           (void) FormatLocaleFile(stderr, "   Total %.20g",(double) kernel_changed);
4092         if ( IfMagickTrue(verbose) && stage_loop < stage_limit )
4093           (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */
4094
4095 #if 0
4096     (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
4097     (void) FormatLocaleFile(stderr, "      curr =0x%lx\n", (unsigned long)curr_image);
4098     (void) FormatLocaleFile(stderr, "      work =0x%lx\n", (unsigned long)work_image);
4099     (void) FormatLocaleFile(stderr, "      save =0x%lx\n", (unsigned long)save_image);
4100     (void) FormatLocaleFile(stderr, "      union=0x%lx\n", (unsigned long)rslt_image);
4101 #endif
4102
4103       } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
4104
4105       /*  Final Post-processing for some Compound Methods
4106       **
4107       ** The removal of any 'Sync' channel flag in the Image Compositon
4108       ** below ensures the methematical compose method is applied in a
4109       ** purely mathematical way, and only to the selected channels.
4110       ** Turn off SVG composition 'alpha blending'.
4111       */
4112       switch( method ) {
4113         case EdgeOutMorphology:
4114         case EdgeInMorphology:
4115         case TopHatMorphology:
4116         case BottomHatMorphology:
4117           if ( IfMagickTrue(verbose) )
4118             (void) FormatLocaleFile(stderr,
4119               "\n%s: Difference with original image",CommandOptionToMnemonic(
4120               MagickMorphologyOptions, method) );
4121           (void) CompositeImage(curr_image,image,DifferenceCompositeOp,
4122             MagickTrue,0,0,exception);
4123           break;
4124         case EdgeMorphology:
4125           if ( IfMagickTrue(verbose) )
4126             (void) FormatLocaleFile(stderr,
4127               "\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic(
4128               MagickMorphologyOptions, method) );
4129           (void) CompositeImage(curr_image,save_image,DifferenceCompositeOp,
4130             MagickTrue,0,0,exception);
4131           save_image = DestroyImage(save_image); /* finished with save image */
4132           break;
4133         default:
4134           break;
4135       }
4136
4137       /* multi-kernel handling:  re-iterate, or compose results */
4138       if ( kernel->next == (KernelInfo *) NULL )
4139         rslt_image = curr_image;   /* just return the resulting image */
4140       else if ( rslt_compose == NoCompositeOp )
4141         { if ( IfMagickTrue(verbose) ) {
4142             if ( this_kernel->next != (KernelInfo *) NULL )
4143               (void) FormatLocaleFile(stderr, " (re-iterate)");
4144             else
4145               (void) FormatLocaleFile(stderr, " (done)");
4146           }
4147           rslt_image = curr_image; /* return result, and re-iterate */
4148         }
4149       else if ( rslt_image == (Image *) NULL)
4150         { if ( IfMagickTrue(verbose) )
4151             (void) FormatLocaleFile(stderr, " (save for compose)");
4152           rslt_image = curr_image;
4153           curr_image = (Image *) image;  /* continue with original image */
4154         }
4155       else
4156         { /* Add the new 'current' result to the composition
4157           **
4158           ** The removal of any 'Sync' channel flag in the Image Compositon
4159           ** below ensures the methematical compose method is applied in a
4160           ** purely mathematical way, and only to the selected channels.
4161           ** IE: Turn off SVG composition 'alpha blending'.
4162           */
4163           if ( IfMagickTrue(verbose) )
4164             (void) FormatLocaleFile(stderr, " (compose \"%s\")",
4165               CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) );
4166           (void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue,
4167             0,0,exception);
4168           curr_image = DestroyImage(curr_image);
4169           curr_image = (Image *) image;  /* continue with original image */
4170         }
4171       if ( IfMagickTrue(verbose) )
4172         (void) FormatLocaleFile(stderr, "\n");
4173
4174       /* loop to the next kernel in a multi-kernel list */
4175       norm_kernel = norm_kernel->next;
4176       if ( rflt_kernel != (KernelInfo *) NULL )
4177         rflt_kernel = rflt_kernel->next;
4178       kernel_number++;
4179     } /* End Loop 2: Loop over each kernel */
4180
4181   } /* End Loop 1: compound method interation */
4182
4183   goto exit_cleanup;
4184
4185   /* Yes goto's are bad, but it makes cleanup lot more efficient */
4186 error_cleanup:
4187   if ( curr_image == rslt_image )
4188     curr_image = (Image *) NULL;
4189   if ( rslt_image != (Image *) NULL )
4190     rslt_image = DestroyImage(rslt_image);
4191 exit_cleanup:
4192   if ( curr_image == rslt_image || curr_image == image )
4193     curr_image = (Image *) NULL;
4194   if ( curr_image != (Image *) NULL )
4195     curr_image = DestroyImage(curr_image);
4196   if ( work_image != (Image *) NULL )
4197     work_image = DestroyImage(work_image);
4198   if ( save_image != (Image *) NULL )
4199     save_image = DestroyImage(save_image);
4200   if ( reflected_kernel != (KernelInfo *) NULL )
4201     reflected_kernel = DestroyKernelInfo(reflected_kernel);
4202   return(rslt_image);
4203 }
4204
4205 \f
4206 /*
4207 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4208 %                                                                             %
4209 %                                                                             %
4210 %                                                                             %
4211 %     M o r p h o l o g y I m a g e                                           %
4212 %                                                                             %
4213 %                                                                             %
4214 %                                                                             %
4215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4216 %
4217 %  MorphologyImage() applies a user supplied kernel to the image
4218 %  according to the given mophology method.
4219 %
4220 %  This function applies any and all user defined settings before calling
4221 %  the above internal function MorphologyApply().
4222 %
4223 %  User defined settings include...
4224 %    * Output Bias for Convolution and correlation ("-define convolve:bias=??")
4225 %    * Kernel Scale/normalize settings             ("-define convolve:scale=??")
4226 %      This can also includes the addition of a scaled unity kernel.
4227 %    * Show Kernel being applied                   ("-define showkernel=1")
4228 %
4229 %  Other operators that do not want user supplied options interfering,
4230 %  especially "convolve:bias" and "showkernel" should use MorphologyApply()
4231 %  directly.
4232 %
4233 %  The format of the MorphologyImage method is:
4234 %
4235 %      Image *MorphologyImage(const Image *image,MorphologyMethod method,
4236 %        const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
4237 %
4238 %  A description of each parameter follows:
4239 %
4240 %    o image: the image.
4241 %
4242 %    o method: the morphology method to be applied.
4243 %
4244 %    o iterations: apply the operation this many times (or no change).
4245 %                  A value of -1 means loop until no change found.
4246 %                  How this is applied may depend on the morphology method.
4247 %                  Typically this is a value of 1.
4248 %
4249 %    o kernel: An array of double representing the morphology kernel.
4250 %              Warning: kernel may be normalized for the Convolve method.
4251 %
4252 %    o exception: return any errors or warnings in this structure.
4253 %
4254 */
4255 MagickExport Image *MorphologyImage(const Image *image,
4256   const MorphologyMethod method,const ssize_t iterations,
4257   const KernelInfo *kernel,ExceptionInfo *exception)
4258 {
4259   KernelInfo
4260     *curr_kernel;
4261
4262   CompositeOperator
4263     compose;
4264
4265   Image
4266     *morphology_image;
4267
4268   double
4269     bias;
4270
4271   curr_kernel = (KernelInfo *) kernel;
4272   bias=0.0;
4273   compose = (ssize_t)UndefinedCompositeOp;  /* use default for method */
4274
4275   /* Apply Convolve/Correlate Normalization and Scaling Factors.
4276    * This is done BEFORE the ShowKernelInfo() function is called so that
4277    * users can see the results of the 'option:convolve:scale' option.
4278    */
4279   if ( method == ConvolveMorphology || method == CorrelateMorphology ) {
4280       const char
4281         *artifact;
4282
4283       /* Get the bias value as it will be needed */
4284       artifact = GetImageArtifact(image,"convolve:bias");
4285       if ( artifact != (const char *) NULL) {
4286         if (IfMagickFalse(IsGeometry(artifact)))
4287           (void) ThrowMagickException(exception,GetMagickModule(),
4288                OptionWarning,"InvalidSetting","'%s' '%s'",
4289                "convolve:bias",artifact);
4290         else
4291           bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0);
4292       }
4293
4294       /* Scale kernel according to user wishes */
4295       artifact = GetImageArtifact(image,"convolve:scale");
4296       if ( artifact != (const char *)NULL ) {
4297         if (IfMagickFalse(IsGeometry(artifact)))
4298           (void) ThrowMagickException(exception,GetMagickModule(),
4299                OptionWarning,"InvalidSetting","'%s' '%s'",
4300                "convolve:scale",artifact);
4301         else {
4302           if ( curr_kernel == kernel )
4303             curr_kernel = CloneKernelInfo(kernel);
4304           if (curr_kernel == (KernelInfo *) NULL)
4305             return((Image *) NULL);
4306           ScaleGeometryKernelInfo(curr_kernel, artifact);
4307         }
4308       }
4309     }
4310
4311   /* display the (normalized) kernel via stderr */
4312   if ( IfStringTrue(GetImageArtifact(image,"showkernel"))
4313     || IfStringTrue(GetImageArtifact(image,"convolve:showkernel"))
4314     || IfStringTrue(GetImageArtifact(image,"morphology:showkernel")) )
4315     ShowKernelInfo(curr_kernel);
4316
4317   /* Override the default handling of multi-kernel morphology results
4318    * If 'Undefined' use the default method
4319    * If 'None' (default for 'Convolve') re-iterate previous result
4320    * Otherwise merge resulting images using compose method given.
4321    * Default for 'HitAndMiss' is 'Lighten'.
4322    */
4323   { const char
4324       *artifact;
4325     ssize_t
4326       parse;
4327
4328     artifact = GetImageArtifact(image,"morphology:compose");
4329     if ( artifact != (const char *) NULL) {
4330       parse=ParseCommandOption(MagickComposeOptions,
4331         MagickFalse,artifact);
4332       if ( parse < 0 )
4333         (void) ThrowMagickException(exception,GetMagickModule(),
4334              OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'",
4335              "morphology:compose",artifact);
4336       else
4337         compose=(CompositeOperator)parse;
4338     }
4339   }
4340   /* Apply the Morphology */
4341   morphology_image = MorphologyApply(image,method,iterations,
4342     curr_kernel,compose,bias,exception);
4343
4344   /* Cleanup and Exit */
4345   if ( curr_kernel != kernel )
4346     curr_kernel=DestroyKernelInfo(curr_kernel);
4347   return(morphology_image);
4348 }
4349 \f
4350 /*
4351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4352 %                                                                             %
4353 %                                                                             %
4354 %                                                                             %
4355 +     R o t a t e K e r n e l I n f o                                         %
4356 %                                                                             %
4357 %                                                                             %
4358 %                                                                             %
4359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4360 %
4361 %  RotateKernelInfo() rotates the kernel by the angle given.
4362 %
4363 %  Currently it is restricted to 90 degree angles, of either 1D kernels
4364 %  or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
4365 %  It will ignore usless rotations for specific 'named' built-in kernels.
4366 %
4367 %  The format of the RotateKernelInfo method is:
4368 %
4369 %      void RotateKernelInfo(KernelInfo *kernel, double angle)
4370 %
4371 %  A description of each parameter follows:
4372 %
4373 %    o kernel: the Morphology/Convolution kernel
4374 %
4375 %    o angle: angle to rotate in degrees
4376 %
4377 % This function is currently internal to this module only, but can be exported
4378 % to other modules if needed.
4379 */
4380 static void RotateKernelInfo(KernelInfo *kernel, double angle)
4381 {
4382   /* angle the lower kernels first */
4383   if ( kernel->next != (KernelInfo *) NULL)
4384     RotateKernelInfo(kernel->next, angle);
4385
4386   /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
4387   **
4388   ** TODO: expand beyond simple 90 degree rotates, flips and flops
4389   */
4390
4391   /* Modulus the angle */
4392   angle = fmod(angle, 360.0);
4393   if ( angle < 0 )
4394     angle += 360.0;
4395
4396   if ( 337.5 < angle || angle <= 22.5 )
4397     return;   /* Near zero angle - no change! - At least not at this time */
4398
4399   /* Handle special cases */
4400   switch (kernel->type) {
4401     /* These built-in kernels are cylindrical kernels, rotating is useless */
4402     case GaussianKernel:
4403     case DoGKernel:
4404     case LoGKernel:
4405     case DiskKernel:
4406     case PeaksKernel:
4407     case LaplacianKernel:
4408     case ChebyshevKernel:
4409     case ManhattanKernel:
4410     case EuclideanKernel:
4411       return;
4412
4413     /* These may be rotatable at non-90 angles in the future */
4414     /* but simply rotating them in multiples of 90 degrees is useless */
4415     case SquareKernel:
4416     case DiamondKernel:
4417     case PlusKernel:
4418     case CrossKernel:
4419       return;
4420
4421     /* These only allows a +/-90 degree rotation (by transpose) */
4422     /* A 180 degree rotation is useless */
4423     case BlurKernel:
4424       if ( 135.0 < angle && angle <= 225.0 )
4425         return;
4426       if ( 225.0 < angle && angle <= 315.0 )
4427         angle -= 180;
4428       break;
4429
4430     default:
4431       break;
4432   }
4433   /* Attempt rotations by 45 degrees  -- 3x3 kernels only */
4434   if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
4435     {
4436       if ( kernel->width == 3 && kernel->height == 3 )
4437         { /* Rotate a 3x3 square by 45 degree angle */
4438           MagickRealType t  = kernel->values[0];
4439           kernel->values[0] = kernel->values[3];
4440           kernel->values[3] = kernel->values[6];
4441           kernel->values[6] = kernel->values[7];
4442           kernel->values[7] = kernel->values[8];
4443           kernel->values[8] = kernel->values[5];
4444           kernel->values[5] = kernel->values[2];
4445           kernel->values[2] = kernel->values[1];
4446           kernel->values[1] = t;
4447           /* rotate non-centered origin */
4448           if ( kernel->x != 1 || kernel->y != 1 ) {
4449             ssize_t x,y;
4450             x = (ssize_t) kernel->x-1;
4451             y = (ssize_t) kernel->y-1;
4452                  if ( x == y  ) x = 0;
4453             else if ( x == 0  ) x = -y;
4454             else if ( x == -y ) y = 0;
4455             else if ( y == 0  ) y = x;
4456             kernel->x = (ssize_t) x+1;
4457             kernel->y = (ssize_t) y+1;
4458           }
4459           angle = fmod(angle+315.0, 360.0);  /* angle reduced 45 degrees */
4460           kernel->angle = fmod(kernel->angle+45.0, 360.0);
4461         }
4462       else
4463         perror("Unable to rotate non-3x3 kernel by 45 degrees");
4464     }
4465   if ( 45.0 < fmod(angle, 180.0)  && fmod(angle,180.0) <= 135.0 )
4466     {
4467       if ( kernel->width == 1 || kernel->height == 1 )
4468         { /* Do a transpose of a 1 dimensional kernel,
4469           ** which results in a fast 90 degree rotation of some type.
4470           */
4471           ssize_t
4472             t;
4473           t = (ssize_t) kernel->width;
4474           kernel->width = kernel->height;
4475           kernel->height = (size_t) t;
4476           t = kernel->x;
4477           kernel->x = kernel->y;
4478           kernel->y = t;
4479           if ( kernel->width == 1 ) {
4480             angle = fmod(angle+270.0, 360.0);     /* angle reduced 90 degrees */
4481             kernel->angle = fmod(kernel->angle+90.0, 360.0);
4482           } else {
4483             angle = fmod(angle+90.0, 360.0);   /* angle increased 90 degrees */
4484             kernel->angle = fmod(kernel->angle+270.0, 360.0);
4485           }
4486         }
4487       else if ( kernel->width == kernel->height )
4488         { /* Rotate a square array of values by 90 degrees */
4489           { register size_t
4490               i,j,x,y;
4491             register double
4492               *k,t;
4493             k=kernel->values;
4494             for( i=0, x=kernel->width-1;  i<=x;   i++, x--)
4495               for( j=0, y=kernel->height-1;  j<y;   j++, y--)
4496                 { t                    = k[i+j*kernel->width];
4497                   k[i+j*kernel->width] = k[j+x*kernel->width];
4498                   k[j+x*kernel->width] = k[x+y*kernel->width];
4499                   k[x+y*kernel->width] = k[y+i*kernel->width];
4500                   k[y+i*kernel->width] = t;
4501                 }
4502           }
4503           /* rotate the origin - relative to center of array */
4504           { register ssize_t x,y;
4505             x = (ssize_t) (kernel->x*2-kernel->width+1);
4506             y = (ssize_t) (kernel->y*2-kernel->height+1);
4507             kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2;
4508             kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2;
4509           }
4510           angle = fmod(angle+270.0, 360.0);     /* angle reduced 90 degrees */
4511           kernel->angle = fmod(kernel->angle+90.0, 360.0);
4512         }
4513       else
4514         perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
4515     }
4516   if ( 135.0 < angle && angle <= 225.0 )
4517     {
4518       /* For a 180 degree rotation - also know as a reflection
4519        * This is actually a very very common operation!
4520        * Basically all that is needed is a reversal of the kernel data!
4521        * And a reflection of the origon
4522        */
4523       double
4524         t;
4525
4526       register double
4527         *k;
4528
4529       ssize_t
4530         i,
4531         j;
4532
4533       k=kernel->values;
4534       j=(ssize_t) (kernel->width*kernel->height-1);
4535       for (i=0;  i < j;  i++, j--)
4536         t=k[i],  k[i]=k[j],  k[j]=t;
4537
4538       kernel->x = (ssize_t) kernel->width  - kernel->x - 1;
4539       kernel->y = (ssize_t) kernel->height - kernel->y - 1;
4540       angle = fmod(angle-180.0, 360.0);   /* angle+180 degrees */
4541       kernel->angle = fmod(kernel->angle+180.0, 360.0);
4542     }
4543   /* At this point angle should at least between -45 (315) and +45 degrees
4544    * In the future some form of non-orthogonal angled rotates could be
4545    * performed here, posibily with a linear kernel restriction.
4546    */
4547
4548   return;
4549 }
4550 \f
4551 /*
4552 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4553 %                                                                             %
4554 %                                                                             %
4555 %                                                                             %
4556 %     S c a l e G e o m e t r y K e r n e l I n f o                           %
4557 %                                                                             %
4558 %                                                                             %
4559 %                                                                             %
4560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4561 %
4562 %  ScaleGeometryKernelInfo() takes a geometry argument string, typically
4563 %  provided as a  "-set option:convolve:scale {geometry}" user setting,
4564 %  and modifies the kernel according to the parsed arguments of that setting.
4565 %
4566 %  The first argument (and any normalization flags) are passed to
4567 %  ScaleKernelInfo() to scale/normalize the kernel.  The second argument
4568 %  is then passed to UnityAddKernelInfo() to add a scled unity kernel
4569 %  into the scaled/normalized kernel.
4570 %
4571 %  The format of the ScaleGeometryKernelInfo method is:
4572 %
4573 %      void ScaleGeometryKernelInfo(KernelInfo *kernel,
4574 %        const double scaling_factor,const MagickStatusType normalize_flags)
4575 %
4576 %  A description of each parameter follows:
4577 %
4578 %    o kernel: the Morphology/Convolution kernel to modify
4579 %
4580 %    o geometry:
4581 %             The geometry string to parse, typically from the user provided
4582 %             "-set option:convolve:scale {geometry}" setting.
4583 %
4584 */
4585 MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
4586      const char *geometry)
4587 {
4588   //GeometryFlags
4589   MagickStatusType
4590     flags;
4591
4592   GeometryInfo
4593     args;
4594
4595   SetGeometryInfo(&args);
4596   flags = ParseGeometry(geometry, &args);
4597
4598 #if 0
4599   /* For Debugging Geometry Input */
4600   (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
4601        flags, args.rho, args.sigma, args.xi, args.psi );
4602 #endif
4603
4604   if ( (flags & PercentValue) != 0 )      /* Handle Percentage flag*/
4605     args.rho *= 0.01,  args.sigma *= 0.01;
4606
4607   if ( (flags & RhoValue) == 0 )          /* Set Defaults for missing args */
4608     args.rho = 1.0;
4609   if ( (flags & SigmaValue) == 0 )
4610     args.sigma = 0.0;
4611
4612   /* Scale/Normalize the input kernel */
4613   ScaleKernelInfo(kernel, args.rho, flags);
4614
4615   /* Add Unity Kernel, for blending with original */
4616   if ( (flags & SigmaValue) != 0 )
4617     UnityAddKernelInfo(kernel, args.sigma);
4618
4619   return;
4620 }
4621 /*
4622 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4623 %                                                                             %
4624 %                                                                             %
4625 %                                                                             %
4626 %     S c a l e K e r n e l I n f o                                           %
4627 %                                                                             %
4628 %                                                                             %
4629 %                                                                             %
4630 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4631 %
4632 %  ScaleKernelInfo() scales the given kernel list by the given amount, with or
4633 %  without normalization of the sum of the kernel values (as per given flags).
4634 %
4635 %  By default (no flags given) the values within the kernel is scaled
4636 %  directly using given scaling factor without change.
4637 %
4638 %  If either of the two 'normalize_flags' are given the kernel will first be
4639 %  normalized and then further scaled by the scaling factor value given.
4640 %
4641 %  Kernel normalization ('normalize_flags' given) is designed to ensure that
4642 %  any use of the kernel scaling factor with 'Convolve' or 'Correlate'
4643 %  morphology methods will fall into -1.0 to +1.0 range.  Note that for
4644 %  non-HDRI versions of IM this may cause images to have any negative results
4645 %  clipped, unless some 'bias' is used.
4646 %
4647 %  More specifically.  Kernels which only contain positive values (such as a
4648 %  'Gaussian' kernel) will be scaled so that those values sum to +1.0,
4649 %  ensuring a 0.0 to +1.0 output range for non-HDRI images.
4650 %
4651 %  For Kernels that contain some negative values, (such as 'Sharpen' kernels)
4652 %  the kernel will be scaled by the absolute of the sum of kernel values, so
4653 %  that it will generally fall within the +/- 1.0 range.
4654 %
4655 %  For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
4656 %  will be scaled by just the sum of the postive values, so that its output
4657 %  range will again fall into the  +/- 1.0 range.
4658 %
4659 %  For special kernels designed for locating shapes using 'Correlate', (often
4660 %  only containing +1 and -1 values, representing foreground/brackground
4661 %  matching) a special normalization method is provided to scale the positive
4662 %  values separately to those of the negative values, so the kernel will be
4663 %  forced to become a zero-sum kernel better suited to such searches.
4664 %
4665 %  WARNING: Correct normalization of the kernel assumes that the '*_range'
4666 %  attributes within the kernel structure have been correctly set during the
4667 %  kernels creation.
4668 %
4669 %  NOTE: The values used for 'normalize_flags' have been selected specifically
4670 %  to match the use of geometry options, so that '!' means NormalizeValue, '^'
4671 %  means CorrelateNormalizeValue.  All other GeometryFlags values are ignored.
4672 %
4673 %  The format of the ScaleKernelInfo method is:
4674 %
4675 %      void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
4676 %               const MagickStatusType normalize_flags )
4677 %
4678 %  A description of each parameter follows:
4679 %
4680 %    o kernel: the Morphology/Convolution kernel
4681 %
4682 %    o scaling_factor:
4683 %             multiply all values (after normalization) by this factor if not
4684 %             zero.  If the kernel is normalized regardless of any flags.
4685 %
4686 %    o normalize_flags:
4687 %             GeometryFlags defining normalization method to use.
4688 %             specifically: NormalizeValue, CorrelateNormalizeValue,
4689 %                           and/or PercentValue
4690 %
4691 */
4692 MagickExport void ScaleKernelInfo(KernelInfo *kernel,
4693   const double scaling_factor,const GeometryFlags normalize_flags)
4694 {
4695   register ssize_t
4696     i;
4697
4698   register double
4699     pos_scale,
4700     neg_scale;
4701
4702   /* do the other kernels in a multi-kernel list first */
4703   if ( kernel->next != (KernelInfo *) NULL)
4704     ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
4705
4706   /* Normalization of Kernel */
4707   pos_scale = 1.0;
4708   if ( (normalize_flags&NormalizeValue) != 0 ) {
4709     if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon )
4710       /* non-zero-summing kernel (generally positive) */
4711       pos_scale = fabs(kernel->positive_range + kernel->negative_range);
4712     else
4713       /* zero-summing kernel */
4714       pos_scale = kernel->positive_range;
4715   }
4716   /* Force kernel into a normalized zero-summing kernel */
4717   if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
4718     pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon )
4719                  ? kernel->positive_range : 1.0;
4720     neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon )
4721                  ? -kernel->negative_range : 1.0;
4722   }
4723   else
4724     neg_scale = pos_scale;
4725
4726   /* finialize scaling_factor for positive and negative components */
4727   pos_scale = scaling_factor/pos_scale;
4728   neg_scale = scaling_factor/neg_scale;
4729
4730   for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
4731     if ( ! IsNan(kernel->values[i]) )
4732       kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
4733
4734   /* convolution output range */
4735   kernel->positive_range *= pos_scale;
4736   kernel->negative_range *= neg_scale;
4737   /* maximum and minimum values in kernel */
4738   kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
4739   kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
4740
4741   /* swap kernel settings if user's scaling factor is negative */
4742   if ( scaling_factor < MagickEpsilon ) {
4743     double t;
4744     t = kernel->positive_range;
4745     kernel->positive_range = kernel->negative_range;
4746     kernel->negative_range = t;
4747     t = kernel->maximum;
4748     kernel->maximum = kernel->minimum;
4749     kernel->minimum = 1;
4750   }
4751
4752   return;
4753 }
4754 \f
4755 /*
4756 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4757 %                                                                             %
4758 %                                                                             %
4759 %                                                                             %
4760 %     S h o w K e r n e l I n f o                                             %
4761 %                                                                             %
4762 %                                                                             %
4763 %                                                                             %
4764 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4765 %
4766 %  ShowKernelInfo() outputs the details of the given kernel defination to
4767 %  standard error, generally due to a users 'showkernel' option request.
4768 %
4769 %  The format of the ShowKernel method is:
4770 %
4771 %      void ShowKernelInfo(const KernelInfo *kernel)
4772 %
4773 %  A description of each parameter follows:
4774 %
4775 %    o kernel: the Morphology/Convolution kernel
4776 %
4777 */
4778 MagickPrivate void ShowKernelInfo(const KernelInfo *kernel)
4779 {
4780   const KernelInfo
4781     *k;
4782
4783   size_t
4784     c, i, u, v;
4785
4786   for (c=0, k=kernel;  k != (KernelInfo *) NULL;  c++, k=k->next ) {
4787
4788     (void) FormatLocaleFile(stderr, "Kernel");
4789     if ( kernel->next != (KernelInfo *) NULL )
4790       (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c );
4791     (void) FormatLocaleFile(stderr, " \"%s",
4792           CommandOptionToMnemonic(MagickKernelOptions, k->type) );
4793     if ( fabs(k->angle) > MagickEpsilon )
4794       (void) FormatLocaleFile(stderr, "@%lg", k->angle);
4795     (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long)
4796       k->width,(unsigned long) k->height,(long) k->x,(long) k->y);
4797     (void) FormatLocaleFile(stderr,
4798           " with values from %.*lg to %.*lg\n",
4799           GetMagickPrecision(), k->minimum,
4800           GetMagickPrecision(), k->maximum);
4801     (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg",
4802           GetMagickPrecision(), k->negative_range,
4803           GetMagickPrecision(), k->positive_range);
4804     if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
4805       (void) FormatLocaleFile(stderr, " (Zero-Summing)\n");
4806     else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
4807       (void) FormatLocaleFile(stderr, " (Normalized)\n");
4808     else
4809       (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n",
4810           GetMagickPrecision(), k->positive_range+k->negative_range);
4811     for (i=v=0; v < k->height; v++) {
4812       (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v );
4813       for (u=0; u < k->width; u++, i++)
4814         if ( IsNan(k->values[i]) )
4815           (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan");
4816         else
4817           (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3,
4818               GetMagickPrecision(), k->values[i]);
4819       (void) FormatLocaleFile(stderr,"\n");
4820     }
4821   }
4822 }
4823 \f
4824 /*
4825 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4826 %                                                                             %
4827 %                                                                             %
4828 %                                                                             %
4829 %     U n i t y A d d K e r n a l I n f o                                     %
4830 %                                                                             %
4831 %                                                                             %
4832 %                                                                             %
4833 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4834 %
4835 %  UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
4836 %  to the given pre-scaled and normalized Kernel.  This in effect adds that
4837 %  amount of the original image into the resulting convolution kernel.  This
4838 %  value is usually provided by the user as a percentage value in the
4839 %  'convolve:scale' setting.
4840 %
4841 %  The resulting effect is to convert the defined kernels into blended
4842 %  soft-blurs, unsharp kernels or into sharpening kernels.
4843 %
4844 %  The format of the UnityAdditionKernelInfo method is:
4845 %
4846 %      void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
4847 %
4848 %  A description of each parameter follows:
4849 %
4850 %    o kernel: the Morphology/Convolution kernel
4851 %
4852 %    o scale:
4853 %             scaling factor for the unity kernel to be added to
4854 %             the given kernel.
4855 %
4856 */
4857 MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
4858   const double scale)
4859 {
4860   /* do the other kernels in a multi-kernel list first */
4861   if ( kernel->next != (KernelInfo *) NULL)
4862     UnityAddKernelInfo(kernel->next, scale);
4863
4864   /* Add the scaled unity kernel to the existing kernel */
4865   kernel->values[kernel->x+kernel->y*kernel->width] += scale;
4866   CalcKernelMetaData(kernel);  /* recalculate the meta-data */
4867
4868   return;
4869 }
4870 \f
4871 /*
4872 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4873 %                                                                             %
4874 %                                                                             %
4875 %                                                                             %
4876 %     Z e r o K e r n e l N a n s                                             %
4877 %                                                                             %
4878 %                                                                             %
4879 %                                                                             %
4880 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4881 %
4882 %  ZeroKernelNans() replaces any special 'nan' value that may be present in
4883 %  the kernel with a zero value.  This is typically done when the kernel will
4884 %  be used in special hardware (GPU) convolution processors, to simply
4885 %  matters.
4886 %
4887 %  The format of the ZeroKernelNans method is:
4888 %
4889 %      void ZeroKernelNans (KernelInfo *kernel)
4890 %
4891 %  A description of each parameter follows:
4892 %
4893 %    o kernel: the Morphology/Convolution kernel
4894 %
4895 */
4896 MagickPrivate void ZeroKernelNans(KernelInfo *kernel)
4897 {
4898   register size_t
4899     i;
4900
4901   /* do the other kernels in a multi-kernel list first */
4902   if ( kernel->next != (KernelInfo *) NULL)
4903     ZeroKernelNans(kernel->next);
4904
4905   for (i=0; i < (kernel->width*kernel->height); i++)
4906     if ( IsNan(kernel->values[i]) )
4907       kernel->values[i] = 0.0;
4908
4909   return;
4910 }