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