source: ImageMagick/branches/ImageMagick-6/magick/morphology.c @ 7369

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