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