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