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