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