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