2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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 %
13 % MagickCore Morphology Methods %
20 % Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization %
21 % dedicated to making software imaging solutions freely available. %
23 % You may not use this file except in compliance with the License. You may %
24 % obtain a copy of the License at %
26 % http://www.imagemagick.org/script/license.php %
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. %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 % Morpology is the the application of various kernels, of any size and even
37 % shape, to a image in various ways (typically binary, but not always).
39 % Convolution (weighted sum or average) is just one specific type of
40 % morphology. Just one that is very common for image bluring and sharpening
41 % effects. Not only 2D Gaussian blurring, but also 2-pass 1D Blurring.
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.
52 #include "MagickCore/studio.h"
53 #include "MagickCore/artifact.h"
54 #include "MagickCore/cache-view.h"
55 #include "MagickCore/color-private.h"
56 #include "MagickCore/enhance.h"
57 #include "MagickCore/exception.h"
58 #include "MagickCore/exception-private.h"
59 #include "MagickCore/gem.h"
60 #include "MagickCore/gem-private.h"
61 #include "MagickCore/hashmap.h"
62 #include "MagickCore/image.h"
63 #include "MagickCore/image-private.h"
64 #include "MagickCore/list.h"
65 #include "MagickCore/magick.h"
66 #include "MagickCore/memory_.h"
67 #include "MagickCore/monitor-private.h"
68 #include "MagickCore/morphology.h"
69 #include "MagickCore/morphology-private.h"
70 #include "MagickCore/option.h"
71 #include "MagickCore/pixel-accessor.h"
72 #include "MagickCore/prepress.h"
73 #include "MagickCore/quantize.h"
74 #include "MagickCore/resource_.h"
75 #include "MagickCore/registry.h"
76 #include "MagickCore/semaphore.h"
77 #include "MagickCore/splay-tree.h"
78 #include "MagickCore/statistic.h"
79 #include "MagickCore/string_.h"
80 #include "MagickCore/string-private.h"
81 #include "MagickCore/thread-private.h"
82 #include "MagickCore/token.h"
83 #include "MagickCore/utility.h"
84 #include "MagickCore/utility-private.h"
88 ** The following test is for special floating point numbers of value NaN (not
89 ** a number), that may be used within a Kernel Definition. NaN's are defined
90 ** as part of the IEEE standard for floating point number representation.
92 ** These are used as a Kernel value to mean that this kernel position is not
93 ** part of the kernel neighbourhood for convolution or morphology processing,
94 ** and thus should be ignored. This allows the use of 'shaped' kernels.
96 ** The special properity that two NaN's are never equal, even if they are from
97 ** the same variable allow you to test if a value is special NaN value.
99 ** This macro IsNaN() is thus is only true if the value given is NaN.
101 #define IsNan(a) ((a)!=(a))
104 Other global definitions used by module.
106 static inline double MagickMin(const double x,const double y)
108 return( x < y ? x : y);
110 static inline double MagickMax(const double x,const double y)
112 return( x > y ? x : y);
114 #define Minimize(assign,value) assign=MagickMin(assign,value)
115 #define Maximize(assign,value) assign=MagickMax(assign,value)
117 /* Currently these are only internal to this module */
119 CalcKernelMetaData(KernelInfo *),
120 ExpandMirrorKernelInfo(KernelInfo *),
121 ExpandRotateKernelInfo(KernelInfo *, const double),
122 RotateKernelInfo(KernelInfo *, double);
125 /* Quick function to find last kernel in a kernel list */
126 static inline KernelInfo *LastKernelInfo(KernelInfo *kernel)
128 while (kernel->next != (KernelInfo *) NULL)
129 kernel = kernel->next;
134 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
138 % A c q u i r e K e r n e l I n f o %
142 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
144 % AcquireKernelInfo() takes the given string (generally supplied by the
145 % user) and converts it into a Morphology/Convolution Kernel. This allows
146 % users to specify a kernel from a number of pre-defined kernels, or to fully
147 % specify their own kernel for a specific Convolution or Morphology
150 % The kernel so generated can be any rectangular array of floating point
151 % values (doubles) with the 'control point' or 'pixel being affected'
152 % anywhere within that array of values.
154 % Previously IM was restricted to a square of odd size using the exact
155 % center as origin, this is no longer the case, and any rectangular kernel
156 % with any value being declared the origin. This in turn allows the use of
157 % highly asymmetrical kernels.
159 % The floating point values in the kernel can also include a special value
160 % known as 'nan' or 'not a number' to indicate that this value is not part
161 % of the kernel array. This allows you to shaped the kernel within its
162 % rectangular area. That is 'nan' values provide a 'mask' for the kernel
163 % shape. However at least one non-nan value must be provided for correct
164 % working of a kernel.
166 % The returned kernel should be freed using the DestroyKernelInfo() when you
167 % are finished with it. Do not free this memory yourself.
169 % Input kernel defintion strings can consist of any of three types.
172 % Select from one of the built in kernels, using the name and
173 % geometry arguments supplied. See AcquireKernelBuiltIn()
175 % "WxH[+X+Y][@><]:num, num, num ..."
176 % a kernel of size W by H, with W*H floating point numbers following.
177 % the 'center' can be optionally be defined at +X+Y (such that +0+0
178 % is top left corner). If not defined the pixel in the center, for
179 % odd sizes, or to the immediate top or left of center for even sizes
180 % is automatically selected.
182 % "num, num, num, num, ..."
183 % list of floating point numbers defining an 'old style' odd sized
184 % square kernel. At least 9 values should be provided for a 3x3
185 % square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc.
186 % Values can be space or comma separated. This is not recommended.
188 % You can define a 'list of kernels' which can be used by some morphology
189 % operators A list is defined as a semi-colon separated list kernels.
191 % " kernel ; kernel ; kernel ; "
193 % Any extra ';' characters, at start, end or between kernel defintions are
196 % The special flags will expand a single kernel, into a list of rotated
197 % kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree
198 % cyclic rotations, while a '>' will generate a list of 90-degree rotations.
199 % The '<' also exands using 90-degree rotates, but giving a 180-degree
200 % reflected kernel before the +/- 90-degree rotations, which can be important
201 % for Thinning operations.
203 % Note that 'name' kernels will start with an alphabetic character while the
204 % new kernel specification has a ':' character in its specification string.
205 % If neither is the case, it is assumed an old style of a simple list of
206 % numbers generating a odd-sized square kernel has been given.
208 % The format of the AcquireKernal method is:
210 % KernelInfo *AcquireKernelInfo(const char *kernel_string)
212 % A description of each parameter follows:
214 % o kernel_string: the Morphology/Convolution kernel wanted.
218 /* This was separated so that it could be used as a separate
219 ** array input handling function, such as for -color-matrix
221 static KernelInfo *ParseKernelArray(const char *kernel_string)
227 token[MaxTextExtent];
237 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
245 kernel=(KernelInfo *) AcquireQuantumMemory(1,sizeof(*kernel));
246 if (kernel == (KernelInfo *)NULL)
248 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
249 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
250 kernel->negative_range = kernel->positive_range = 0.0;
251 kernel->type = UserDefinedKernel;
252 kernel->next = (KernelInfo *) NULL;
253 kernel->signature = MagickSignature;
254 if (kernel_string == (const char *) NULL)
257 /* find end of this specific kernel definition string */
258 end = strchr(kernel_string, ';');
259 if ( end == (char *) NULL )
260 end = strchr(kernel_string, '\0');
262 /* clear flags - for Expanding kernel lists thorugh rotations */
265 /* Has a ':' in argument - New user kernel specification
266 FUTURE: this split on ':' could be done by StringToken()
268 p = strchr(kernel_string, ':');
269 if ( p != (char *) NULL && p < end)
271 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
272 memcpy(token, kernel_string, (size_t) (p-kernel_string));
273 token[p-kernel_string] = '\0';
274 SetGeometryInfo(&args);
275 flags = ParseGeometry(token, &args);
277 /* Size handling and checks of geometry settings */
278 if ( (flags & WidthValue) == 0 ) /* if no width then */
279 args.rho = args.sigma; /* then width = height */
280 if ( args.rho < 1.0 ) /* if width too small */
281 args.rho = 1.0; /* then width = 1 */
282 if ( args.sigma < 1.0 ) /* if height too small */
283 args.sigma = args.rho; /* then height = width */
284 kernel->width = (size_t)args.rho;
285 kernel->height = (size_t)args.sigma;
287 /* Offset Handling and Checks */
288 if ( args.xi < 0.0 || args.psi < 0.0 )
289 return(DestroyKernelInfo(kernel));
290 kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi
291 : (ssize_t) (kernel->width-1)/2;
292 kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi
293 : (ssize_t) (kernel->height-1)/2;
294 if ( kernel->x >= (ssize_t) kernel->width ||
295 kernel->y >= (ssize_t) kernel->height )
296 return(DestroyKernelInfo(kernel));
298 p++; /* advance beyond the ':' */
301 { /* ELSE - Old old specification, forming odd-square kernel */
302 /* count up number of values given */
303 p=(const char *) kernel_string;
304 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
305 p++; /* ignore "'" chars for convolve filter usage - Cristy */
306 for (i=0; p < end; i++)
308 GetMagickToken(p,&p,token);
310 GetMagickToken(p,&p,token);
312 /* set the size of the kernel - old sized square */
313 kernel->width = kernel->height= (size_t) sqrt((double) i+1.0);
314 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
315 p=(const char *) kernel_string;
316 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
317 p++; /* ignore "'" chars for convolve filter usage - Cristy */
320 /* Read in the kernel values from rest of input string argument */
321 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
322 kernel->height*sizeof(*kernel->values));
323 if (kernel->values == (double *) NULL)
324 return(DestroyKernelInfo(kernel));
325 kernel->minimum = +MagickHuge;
326 kernel->maximum = -MagickHuge;
327 kernel->negative_range = kernel->positive_range = 0.0;
328 for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++)
330 GetMagickToken(p,&p,token);
332 GetMagickToken(p,&p,token);
333 if ( LocaleCompare("nan",token) == 0
334 || LocaleCompare("-",token) == 0 ) {
335 kernel->values[i] = nan; /* this value is not part of neighbourhood */
338 kernel->values[i] = StringToDouble(token,(char **) NULL);
339 ( kernel->values[i] < 0)
340 ? ( kernel->negative_range += kernel->values[i] )
341 : ( kernel->positive_range += kernel->values[i] );
342 Minimize(kernel->minimum, kernel->values[i]);
343 Maximize(kernel->maximum, kernel->values[i]);
347 /* sanity check -- no more values in kernel definition */
348 GetMagickToken(p,&p,token);
349 if ( *token != '\0' && *token != ';' && *token != '\'' )
350 return(DestroyKernelInfo(kernel));
353 /* this was the old method of handling a incomplete kernel */
354 if ( i < (ssize_t) (kernel->width*kernel->height) ) {
355 Minimize(kernel->minimum, kernel->values[i]);
356 Maximize(kernel->maximum, kernel->values[i]);
357 for ( ; i < (ssize_t) (kernel->width*kernel->height); i++)
358 kernel->values[i]=0.0;
361 /* Number of values for kernel was not enough - Report Error */
362 if ( i < (ssize_t) (kernel->width*kernel->height) )
363 return(DestroyKernelInfo(kernel));
366 /* check that we recieved at least one real (non-nan) value! */
367 if ( kernel->minimum == MagickHuge )
368 return(DestroyKernelInfo(kernel));
370 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */
371 ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */
372 else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
373 ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */
374 else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
375 ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */
380 static KernelInfo *ParseKernelName(const char *kernel_string)
383 token[MaxTextExtent];
401 /* Parse special 'named' kernel */
402 GetMagickToken(kernel_string,&p,token);
403 type=ParseCommandOption(MagickKernelOptions,MagickFalse,token);
404 if ( type < 0 || type == UserDefinedKernel )
405 return((KernelInfo *)NULL); /* not a valid named kernel */
407 while (((isspace((int) ((unsigned char) *p)) != 0) ||
408 (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
411 end = strchr(p, ';'); /* end of this kernel defintion */
412 if ( end == (char *) NULL )
413 end = strchr(p, '\0');
415 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
416 memcpy(token, p, (size_t) (end-p));
418 SetGeometryInfo(&args);
419 flags = ParseGeometry(token, &args);
422 /* For Debugging Geometry Input */
423 (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
424 flags, args.rho, args.sigma, args.xi, args.psi );
427 /* special handling of missing values in input string */
429 /* Shape Kernel Defaults */
431 if ( (flags & WidthValue) == 0 )
432 args.rho = 1.0; /* Default scale = 1.0, zero is valid */
440 if ( (flags & HeightValue) == 0 )
441 args.sigma = 1.0; /* Default scale = 1.0, zero is valid */
444 if ( (flags & XValue) == 0 )
445 args.xi = 1.0; /* Default scale = 1.0, zero is valid */
447 case RectangleKernel: /* Rectangle - set size defaults */
448 if ( (flags & WidthValue) == 0 ) /* if no width then */
449 args.rho = args.sigma; /* then width = height */
450 if ( args.rho < 1.0 ) /* if width too small */
451 args.rho = 3; /* then width = 3 */
452 if ( args.sigma < 1.0 ) /* if height too small */
453 args.sigma = args.rho; /* then height = width */
454 if ( (flags & XValue) == 0 ) /* center offset if not defined */
455 args.xi = (double)(((ssize_t)args.rho-1)/2);
456 if ( (flags & YValue) == 0 )
457 args.psi = (double)(((ssize_t)args.sigma-1)/2);
459 /* Distance Kernel Defaults */
460 case ChebyshevKernel:
461 case ManhattanKernel:
462 case OctagonalKernel:
463 case EuclideanKernel:
464 if ( (flags & HeightValue) == 0 ) /* no distance scale */
465 args.sigma = 100.0; /* default distance scaling */
466 else if ( (flags & AspectValue ) != 0 ) /* '!' flag */
467 args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */
468 else if ( (flags & PercentValue ) != 0 ) /* '%' flag */
469 args.sigma *= QuantumRange/100.0; /* percentage of color range */
475 kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args);
476 if ( kernel == (KernelInfo *) NULL )
479 /* global expand to rotated kernel list - only for single kernels */
480 if ( kernel->next == (KernelInfo *) NULL ) {
481 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */
482 ExpandRotateKernelInfo(kernel, 45.0);
483 else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
484 ExpandRotateKernelInfo(kernel, 90.0);
485 else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
486 ExpandMirrorKernelInfo(kernel);
492 MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string)
500 token[MaxTextExtent];
508 if (kernel_string == (const char *) NULL)
509 return(ParseKernelArray(kernel_string));
514 while ( GetMagickToken(p,NULL,token), *token != '\0' ) {
516 /* ignore extra or multiple ';' kernel separators */
517 if ( *token != ';' ) {
519 /* tokens starting with alpha is a Named kernel */
520 if (isalpha((int) *token) != 0)
521 new_kernel = ParseKernelName(p);
522 else /* otherwise a user defined kernel array */
523 new_kernel = ParseKernelArray(p);
525 /* Error handling -- this is not proper error handling! */
526 if ( new_kernel == (KernelInfo *) NULL ) {
527 (void) FormatLocaleFile(stderr, "Failed to parse kernel number #%.20g\n",
528 (double) kernel_number);
529 if ( kernel != (KernelInfo *) NULL )
530 kernel=DestroyKernelInfo(kernel);
531 return((KernelInfo *) NULL);
534 /* initialise or append the kernel list */
535 if ( kernel == (KernelInfo *) NULL )
538 LastKernelInfo(kernel)->next = new_kernel;
541 /* look for the next kernel in list */
543 if ( p == (char *) NULL )
553 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
557 % A c q u i r e K e r n e l B u i l t I n %
561 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
563 % AcquireKernelBuiltIn() returned one of the 'named' built-in types of
564 % kernels used for special purposes such as gaussian blurring, skeleton
565 % pruning, and edge distance determination.
567 % They take a KernelType, and a set of geometry style arguments, which were
568 % typically decoded from a user supplied string, or from a more complex
569 % Morphology Method that was requested.
571 % The format of the AcquireKernalBuiltIn method is:
573 % KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
574 % const GeometryInfo args)
576 % A description of each parameter follows:
578 % o type: the pre-defined type of kernel wanted
580 % o args: arguments defining or modifying the kernel
582 % Convolution Kernels
585 % The a No-Op or Scaling single element kernel.
587 % Gaussian:{radius},{sigma}
588 % Generate a two-dimensional gaussian kernel, as used by -gaussian.
589 % The sigma for the curve is required. The resulting kernel is
592 % If 'sigma' is zero, you get a single pixel on a field of zeros.
594 % NOTE: that the 'radius' is optional, but if provided can limit (clip)
595 % the final size of the resulting kernel to a square 2*radius+1 in size.
596 % The radius should be at least 2 times that of the sigma value, or
597 % sever clipping and aliasing may result. If not given or set to 0 the
598 % radius will be determined so as to produce the best minimal error
599 % result, which is usally much larger than is normally needed.
601 % LoG:{radius},{sigma}
602 % "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
603 % The supposed ideal edge detection, zero-summing kernel.
605 % An alturnative to this kernel is to use a "DoG" with a sigma ratio of
606 % approx 1.6 (according to wikipedia).
608 % DoG:{radius},{sigma1},{sigma2}
609 % "Difference of Gaussians" Kernel.
610 % As "Gaussian" but with a gaussian produced by 'sigma2' subtracted
611 % from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1.
612 % The result is a zero-summing kernel.
614 % Blur:{radius},{sigma}[,{angle}]
615 % Generates a 1 dimensional or linear gaussian blur, at the angle given
616 % (current restricted to orthogonal angles). If a 'radius' is given the
617 % kernel is clipped to a width of 2*radius+1. Kernel can be rotated
618 % by a 90 degree angle.
620 % If 'sigma' is zero, you get a single pixel on a field of zeros.
622 % Note that two convolutions with two "Blur" kernels perpendicular to
623 % each other, is equivalent to a far larger "Gaussian" kernel with the
624 % same sigma value, However it is much faster to apply. This is how the
625 % "-blur" operator actually works.
627 % Comet:{width},{sigma},{angle}
628 % Blur in one direction only, much like how a bright object leaves
629 % a comet like trail. The Kernel is actually half a gaussian curve,
630 % Adding two such blurs in opposite directions produces a Blur Kernel.
631 % Angle can be rotated in multiples of 90 degrees.
633 % Note that the first argument is the width of the kernel and not the
634 % radius of the kernel.
636 % # Still to be implemented...
640 % # Set kernel values using a resize filter, and given scale (sigma)
641 % # Cylindrical or Linear. Is this possible with an image?
644 % Named Constant Convolution Kernels
646 % All these are unscaled, zero-summing kernels by default. As such for
647 % non-HDRI version of ImageMagick some form of normalization, user scaling,
648 % and biasing the results is recommended, to prevent the resulting image
651 % The 3x3 kernels (most of these) can be circularly rotated in multiples of
652 % 45 degrees to generate the 8 angled varients of each of the kernels.
655 % Discrete Lapacian Kernels, (without normalization)
656 % Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood)
657 % Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood)
658 % Type 2 : 3x3 with center:4 edge:1 corner:-2
659 % Type 3 : 3x3 with center:4 edge:-2 corner:1
660 % Type 5 : 5x5 laplacian
661 % Type 7 : 7x7 laplacian
662 % Type 15 : 5x5 LoG (sigma approx 1.4)
663 % Type 19 : 9x9 LoG (sigma approx 1.4)
666 % Sobel 'Edge' convolution kernel (3x3)
672 % Roberts convolution kernel (3x3)
678 % Prewitt Edge convolution kernel (3x3)
684 % Prewitt's "Compass" convolution kernel (3x3)
690 % Kirsch's "Compass" convolution kernel (3x3)
696 % Frei-Chen Edge Detector is based on a kernel that is similar to
697 % the Sobel Kernel, but is designed to be isotropic. That is it takes
698 % into account the distance of the diagonal in the kernel.
701 % | sqrt(2), 0, -sqrt(2) |
704 % FreiChen:{type},{angle}
706 % Frei-Chen Pre-weighted kernels...
708 % Type 0: default un-nomalized version shown above.
710 % Type 1: Orthogonal Kernel (same as type 11 below)
712 % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
715 % Type 2: Diagonal form of Kernel...
717 % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
720 % However this kernel is als at the heart of the FreiChen Edge Detection
721 % Process which uses a set of 9 specially weighted kernel. These 9
722 % kernels not be normalized, but directly applied to the image. The
723 % results is then added together, to produce the intensity of an edge in
724 % a specific direction. The square root of the pixel value can then be
725 % taken as the cosine of the edge, and at least 2 such runs at 90 degrees
726 % from each other, both the direction and the strength of the edge can be
729 % Type 10: All 9 of the following pre-weighted kernels...
731 % Type 11: | 1, 0, -1 |
732 % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
735 % Type 12: | 1, sqrt(2), 1 |
736 % | 0, 0, 0 | / 2*sqrt(2)
739 % Type 13: | sqrt(2), -1, 0 |
740 % | -1, 0, 1 | / 2*sqrt(2)
743 % Type 14: | 0, 1, -sqrt(2) |
744 % | -1, 0, 1 | / 2*sqrt(2)
747 % Type 15: | 0, -1, 0 |
751 % Type 16: | 1, 0, -1 |
755 % Type 17: | 1, -2, 1 |
759 % Type 18: | -2, 1, -2 |
763 % Type 19: | 1, 1, 1 |
767 % The first 4 are for edge detection, the next 4 are for line detection
768 % and the last is to add a average component to the results.
770 % Using a special type of '-1' will return all 9 pre-weighted kernels
771 % as a multi-kernel list, so that you can use them directly (without
772 % normalization) with the special "-set option:morphology:compose Plus"
773 % setting to apply the full FreiChen Edge Detection Technique.
775 % If 'type' is large it will be taken to be an actual rotation angle for
776 % the default FreiChen (type 0) kernel. As such FreiChen:45 will look
777 % like a Sobel:45 but with 'sqrt(2)' instead of '2' values.
779 % WARNING: The above was layed out as per
780 % http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf
781 % But rotated 90 degrees so direction is from left rather than the top.
782 % I have yet to find any secondary confirmation of the above. The only
783 % other source found was actual source code at
784 % http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf
785 % Neigher paper defineds the kernels in a way that looks locical or
786 % correct when taken as a whole.
790 % Diamond:[{radius}[,{scale}]]
791 % Generate a diamond shaped kernel with given radius to the points.
792 % Kernel size will again be radius*2+1 square and defaults to radius 1,
793 % generating a 3x3 kernel that is slightly larger than a square.
795 % Square:[{radius}[,{scale}]]
796 % Generate a square shaped kernel of size radius*2+1, and defaulting
797 % to a 3x3 (radius 1).
799 % Octagon:[{radius}[,{scale}]]
800 % Generate octagonal shaped kernel of given radius and constant scale.
801 % Default radius is 3 producing a 7x7 kernel. A radius of 1 will result
802 % in "Diamond" kernel.
804 % Disk:[{radius}[,{scale}]]
805 % Generate a binary disk, thresholded at the radius given, the radius
806 % may be a float-point value. Final Kernel size is floor(radius)*2+1
807 % square. A radius of 5.3 is the default.
809 % NOTE: That a low radii Disk kernels produce the same results as
810 % many of the previously defined kernels, but differ greatly at larger
811 % radii. Here is a table of equivalences...
812 % "Disk:1" => "Diamond", "Octagon:1", or "Cross:1"
813 % "Disk:1.5" => "Square"
814 % "Disk:2" => "Diamond:2"
815 % "Disk:2.5" => "Octagon"
816 % "Disk:2.9" => "Square:2"
817 % "Disk:3.5" => "Octagon:3"
818 % "Disk:4.5" => "Octagon:4"
819 % "Disk:5.4" => "Octagon:5"
820 % "Disk:6.4" => "Octagon:6"
821 % All other Disk shapes are unique to this kernel, but because a "Disk"
822 % is more circular when using a larger radius, using a larger radius is
823 % preferred over iterating the morphological operation.
825 % Rectangle:{geometry}
826 % Simply generate a rectangle of 1's with the size given. You can also
827 % specify the location of the 'control point', otherwise the closest
828 % pixel to the center of the rectangle is selected.
830 % Properly centered and odd sized rectangles work the best.
832 % Symbol Dilation Kernels
834 % These kernel is not a good general morphological kernel, but is used
835 % more for highlighting and marking any single pixels in an image using,
836 % a "Dilate" method as appropriate.
838 % For the same reasons iterating these kernels does not produce the
839 % same result as using a larger radius for the symbol.
841 % Plus:[{radius}[,{scale}]]
842 % Cross:[{radius}[,{scale}]]
843 % Generate a kernel in the shape of a 'plus' or a 'cross' with
844 % a each arm the length of the given radius (default 2).
846 % NOTE: "plus:1" is equivalent to a "Diamond" kernel.
848 % Ring:{radius1},{radius2}[,{scale}]
849 % A ring of the values given that falls between the two radii.
850 % Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
851 % This is the 'edge' pixels of the default "Disk" kernel,
852 % More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
854 % Hit and Miss Kernels
856 % Peak:radius1,radius2
857 % Find any peak larger than the pixels the fall between the two radii.
858 % The default ring of pixels is as per "Ring".
860 % Find flat orthogonal edges of a binary shape
862 % Find 90 degree corners of a binary shape
864 % A special kernel to thin the 'outside' of diagonals
866 % Find end points of lines (for pruning a skeletion)
867 % Two types of lines ends (default to both) can be searched for
868 % Type 0: All line ends
869 % Type 1: single kernel for 4-conneected line ends
870 % Type 2: single kernel for simple line ends
872 % Find three line junctions (within a skeletion)
873 % Type 0: all line junctions
874 % Type 1: Y Junction kernel
875 % Type 2: Diagonal T Junction kernel
876 % Type 3: Orthogonal T Junction kernel
877 % Type 4: Diagonal X Junction kernel
878 % Type 5: Orthogonal + Junction kernel
880 % Find single pixel ridges or thin lines
881 % Type 1: Fine single pixel thick lines and ridges
882 % Type 2: Find two pixel thick lines and ridges
884 % Octagonal Thickening Kernel, to generate convex hulls of 45 degrees
886 % Traditional skeleton generating kernels.
887 % Type 1: Tradional Skeleton kernel (4 connected skeleton)
888 % Type 2: HIPR2 Skeleton kernel (8 connected skeleton)
889 % Type 3: Thinning skeleton based on a ressearch paper by
890 % Dan S. Bloomberg (Default Type)
892 % A huge variety of Thinning Kernels designed to preserve conectivity.
893 % many other kernel sets use these kernels as source definitions.
894 % Type numbers are 41-49, 81-89, 481, and 482 which are based on
895 % the super and sub notations used in the source research paper.
897 % Distance Measuring Kernels
899 % Different types of distance measuring methods, which are used with the
900 % a 'Distance' morphology method for generating a gradient based on
901 % distance from an edge of a binary shape, though there is a technique
902 % for handling a anti-aliased shape.
904 % See the 'Distance' Morphological Method, for information of how it is
907 % Chebyshev:[{radius}][x{scale}[%!]]
908 % Chebyshev Distance (also known as Tchebychev or Chessboard distance)
909 % is a value of one to any neighbour, orthogonal or diagonal. One why
910 % of thinking of it is the number of squares a 'King' or 'Queen' in
911 % chess needs to traverse reach any other position on a chess board.
912 % It results in a 'square' like distance function, but one where
913 % diagonals are given a value that is closer than expected.
915 % Manhattan:[{radius}][x{scale}[%!]]
916 % Manhattan Distance (also known as Rectilinear, City Block, or the Taxi
917 % Cab distance metric), it is the distance needed when you can only
918 % travel in horizontal or vertical directions only. It is the
919 % distance a 'Rook' in chess would have to travel, and results in a
920 % diamond like distances, where diagonals are further than expected.
922 % Octagonal:[{radius}][x{scale}[%!]]
923 % An interleving of Manhatten and Chebyshev metrics producing an
924 % increasing octagonally shaped distance. Distances matches those of
925 % the "Octagon" shaped kernel of the same radius. The minimum radius
926 % and default is 2, producing a 5x5 kernel.
928 % Euclidean:[{radius}][x{scale}[%!]]
929 % Euclidean distance is the 'direct' or 'as the crow flys' distance.
930 % However by default the kernel size only has a radius of 1, which
931 % limits the distance to 'Knight' like moves, with only orthogonal and
932 % diagonal measurements being correct. As such for the default kernel
933 % you will get octagonal like distance function.
935 % However using a larger radius such as "Euclidean:4" you will get a
936 % much smoother distance gradient from the edge of the shape. Especially
937 % if the image is pre-processed to include any anti-aliasing pixels.
938 % Of course a larger kernel is slower to use, and not always needed.
940 % The first three Distance Measuring Kernels will only generate distances
941 % of exact multiples of {scale} in binary images. As such you can use a
942 % scale of 1 without loosing any information. However you also need some
943 % scaling when handling non-binary anti-aliased shapes.
945 % The "Euclidean" Distance Kernel however does generate a non-integer
946 % fractional results, and as such scaling is vital even for binary shapes.
950 MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
951 const GeometryInfo *args)
964 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
966 /* Generate a new empty kernel if needed */
967 kernel=(KernelInfo *) NULL;
969 case UndefinedKernel: /* These should not call this function */
970 case UserDefinedKernel:
971 assert("Should not call this function" != (char *)NULL);
973 case LaplacianKernel: /* Named Descrete Convolution Kernels */
974 case SobelKernel: /* these are defined using other kernels */
980 case EdgesKernel: /* Hit and Miss kernels */
982 case DiagonalsKernel:
984 case LineJunctionsKernel:
986 case ConvexHullKernel:
989 break; /* A pre-generated kernel is not needed */
991 /* set to 1 to do a compile-time check that we haven't missed anything */
1000 case RectangleKernel:
1007 case ChebyshevKernel:
1008 case ManhattanKernel:
1009 case OctangonalKernel:
1010 case EuclideanKernel:
1014 /* Generate the base Kernel Structure */
1015 kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
1016 if (kernel == (KernelInfo *) NULL)
1018 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
1019 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
1020 kernel->negative_range = kernel->positive_range = 0.0;
1021 kernel->type = type;
1022 kernel->next = (KernelInfo *) NULL;
1023 kernel->signature = MagickSignature;
1033 kernel->height = kernel->width = (size_t) 1;
1034 kernel->x = kernel->y = (ssize_t) 0;
1035 kernel->values=(double *) AcquireAlignedMemory(1,
1036 sizeof(*kernel->values));
1037 if (kernel->values == (double *) NULL)
1038 return(DestroyKernelInfo(kernel));
1039 kernel->maximum = kernel->values[0] = args->rho;
1043 case GaussianKernel:
1047 sigma = fabs(args->sigma),
1048 sigma2 = fabs(args->xi),
1051 if ( args->rho >= 1.0 )
1052 kernel->width = (size_t)args->rho*2+1;
1053 else if ( (type != DoGKernel) || (sigma >= sigma2) )
1054 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
1056 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
1057 kernel->height = kernel->width;
1058 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1059 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1060 kernel->height*sizeof(*kernel->values));
1061 if (kernel->values == (double *) NULL)
1062 return(DestroyKernelInfo(kernel));
1064 /* WARNING: The following generates a 'sampled gaussian' kernel.
1065 * What we really want is a 'discrete gaussian' kernel.
1067 * How to do this is I don't know, but appears to be basied on the
1068 * Error Function 'erf()' (intergral of a gaussian)
1071 if ( type == GaussianKernel || type == DoGKernel )
1072 { /* Calculate a Gaussian, OR positive half of a DoG */
1073 if ( sigma > MagickEpsilon )
1074 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1075 B = (double) (1.0/(Magick2PI*sigma*sigma));
1076 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1077 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1078 kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
1080 else /* limiting case - a unity (normalized Dirac) kernel */
1081 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1082 kernel->width*kernel->height*sizeof(double));
1083 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1087 if ( type == DoGKernel )
1088 { /* Subtract a Negative Gaussian for "Difference of Gaussian" */
1089 if ( sigma2 > MagickEpsilon )
1090 { sigma = sigma2; /* simplify loop expressions */
1091 A = 1.0/(2.0*sigma*sigma);
1092 B = (double) (1.0/(Magick2PI*sigma*sigma));
1093 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1094 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1095 kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
1097 else /* limiting case - a unity (normalized Dirac) kernel */
1098 kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1101 if ( type == LoGKernel )
1102 { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
1103 if ( sigma > MagickEpsilon )
1104 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1105 B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma));
1106 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1107 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1108 { R = ((double)(u*u+v*v))*A;
1109 kernel->values[i] = (1-R)*exp(-R)*B;
1112 else /* special case - generate a unity kernel */
1113 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1114 kernel->width*kernel->height*sizeof(double));
1115 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1119 /* Note the above kernels may have been 'clipped' by a user defined
1120 ** radius, producing a smaller (darker) kernel. Also for very small
1121 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1122 ** producing a very bright kernel.
1124 ** Normalization will still be needed.
1127 /* Normalize the 2D Gaussian Kernel
1129 ** NB: a CorrelateNormalize performs a normal Normalize if
1130 ** there are no negative values.
1132 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1133 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1139 sigma = fabs(args->sigma),
1142 if ( args->rho >= 1.0 )
1143 kernel->width = (size_t)args->rho*2+1;
1145 kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
1147 kernel->x = (ssize_t) (kernel->width-1)/2;
1149 kernel->negative_range = kernel->positive_range = 0.0;
1150 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1151 kernel->height*sizeof(*kernel->values));
1152 if (kernel->values == (double *) NULL)
1153 return(DestroyKernelInfo(kernel));
1156 #define KernelRank 3
1157 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix).
1158 ** It generates a gaussian 3 times the width, and compresses it into
1159 ** the expected range. This produces a closer normalization of the
1160 ** resulting kernel, especially for very low sigma values.
1161 ** As such while wierd it is prefered.
1163 ** I am told this method originally came from Photoshop.
1165 ** A properly normalized curve is generated (apart from edge clipping)
1166 ** even though we later normalize the result (for edge clipping)
1167 ** to allow the correct generation of a "Difference of Blurs".
1171 v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */
1172 (void) ResetMagickMemory(kernel->values,0, (size_t)
1173 kernel->width*kernel->height*sizeof(double));
1174 /* Calculate a Positive 1D Gaussian */
1175 if ( sigma > MagickEpsilon )
1176 { sigma *= KernelRank; /* simplify loop expressions */
1177 alpha = 1.0/(2.0*sigma*sigma);
1178 beta= (double) (1.0/(MagickSQ2PI*sigma ));
1179 for ( u=-v; u <= v; u++) {
1180 kernel->values[(u+v)/KernelRank] +=
1181 exp(-((double)(u*u))*alpha)*beta;
1184 else /* special case - generate a unity kernel */
1185 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1187 /* Direct calculation without curve averaging
1188 This is equivelent to a KernelRank of 1 */
1190 /* Calculate a Positive Gaussian */
1191 if ( sigma > MagickEpsilon )
1192 { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1193 beta = 1.0/(MagickSQ2PI*sigma);
1194 for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1195 kernel->values[i] = exp(-((double)(u*u))*alpha)*beta;
1197 else /* special case - generate a unity kernel */
1198 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1199 kernel->width*kernel->height*sizeof(double));
1200 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1203 /* Note the above kernel may have been 'clipped' by a user defined
1204 ** radius, producing a smaller (darker) kernel. Also for very small
1205 ** sigma's (> 0.1) the central value becomes larger than one, as a
1206 ** result of not generating a actual 'discrete' kernel, and thus
1207 ** producing a very bright 'impulse'.
1209 ** Becuase of these two factors Normalization is required!
1212 /* Normalize the 1D Gaussian Kernel
1214 ** NB: a CorrelateNormalize performs a normal Normalize if
1215 ** there are no negative values.
1217 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1218 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1220 /* rotate the 1D kernel by given angle */
1221 RotateKernelInfo(kernel, args->xi );
1226 sigma = fabs(args->sigma),
1229 if ( args->rho < 1.0 )
1230 kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
1232 kernel->width = (size_t)args->rho;
1233 kernel->x = kernel->y = 0;
1235 kernel->negative_range = kernel->positive_range = 0.0;
1236 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1237 kernel->height*sizeof(*kernel->values));
1238 if (kernel->values == (double *) NULL)
1239 return(DestroyKernelInfo(kernel));
1241 /* A comet blur is half a 1D gaussian curve, so that the object is
1242 ** blurred in one direction only. This may not be quite the right
1243 ** curve to use so may change in the future. The function must be
1244 ** normalised after generation, which also resolves any clipping.
1246 ** As we are normalizing and not subtracting gaussians,
1247 ** there is no need for a divisor in the gaussian formula
1249 ** It is less comples
1251 if ( sigma > MagickEpsilon )
1254 #define KernelRank 3
1255 v = (ssize_t) kernel->width*KernelRank; /* start/end points */
1256 (void) ResetMagickMemory(kernel->values,0, (size_t)
1257 kernel->width*sizeof(double));
1258 sigma *= KernelRank; /* simplify the loop expression */
1259 A = 1.0/(2.0*sigma*sigma);
1260 /* B = 1.0/(MagickSQ2PI*sigma); */
1261 for ( u=0; u < v; u++) {
1262 kernel->values[u/KernelRank] +=
1263 exp(-((double)(u*u))*A);
1264 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1266 for (i=0; i < (ssize_t) kernel->width; i++)
1267 kernel->positive_range += kernel->values[i];
1269 A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
1270 /* B = 1.0/(MagickSQ2PI*sigma); */
1271 for ( i=0; i < (ssize_t) kernel->width; i++)
1272 kernel->positive_range +=
1273 kernel->values[i] = exp(-((double)(i*i))*A);
1274 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1277 else /* special case - generate a unity kernel */
1278 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1279 kernel->width*kernel->height*sizeof(double));
1280 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1281 kernel->positive_range = 1.0;
1284 kernel->minimum = 0.0;
1285 kernel->maximum = kernel->values[0];
1286 kernel->negative_range = 0.0;
1288 ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1289 RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
1294 Convolution Kernels - Well Known Named Constant Kernels
1296 case LaplacianKernel:
1297 { switch ( (int) args->rho ) {
1299 default: /* laplacian square filter -- default */
1300 kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
1302 case 1: /* laplacian diamond filter */
1303 kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
1306 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1309 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
1311 case 5: /* a 5x5 laplacian */
1312 kernel=ParseKernelArray(
1313 "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");
1315 case 7: /* a 7x7 laplacian */
1316 kernel=ParseKernelArray(
1317 "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" );
1319 case 15: /* a 5x5 LoG (sigma approx 1.4) */
1320 kernel=ParseKernelArray(
1321 "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");
1323 case 19: /* a 9x9 LoG (sigma approx 1.4) */
1324 /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1325 kernel=ParseKernelArray(
1326 "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");
1329 if (kernel == (KernelInfo *) NULL)
1331 kernel->type = type;
1335 { /* Simple Sobel Kernel */
1336 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1337 if (kernel == (KernelInfo *) NULL)
1339 kernel->type = type;
1340 RotateKernelInfo(kernel, args->rho);
1345 kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0");
1346 if (kernel == (KernelInfo *) NULL)
1348 kernel->type = type;
1349 RotateKernelInfo(kernel, args->rho);
1354 kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1");
1355 if (kernel == (KernelInfo *) NULL)
1357 kernel->type = type;
1358 RotateKernelInfo(kernel, args->rho);
1363 kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1");
1364 if (kernel == (KernelInfo *) NULL)
1366 kernel->type = type;
1367 RotateKernelInfo(kernel, args->rho);
1372 kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3");
1373 if (kernel == (KernelInfo *) NULL)
1375 kernel->type = type;
1376 RotateKernelInfo(kernel, args->rho);
1379 case FreiChenKernel:
1380 /* Direction is set to be left to right positive */
1381 /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
1382 /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
1383 { switch ( (int) args->rho ) {
1386 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1387 if (kernel == (KernelInfo *) NULL)
1389 kernel->type = type;
1390 kernel->values[3] = +(MagickRealType) MagickSQ2;
1391 kernel->values[5] = -(MagickRealType) MagickSQ2;
1392 CalcKernelMetaData(kernel); /* recalculate meta-data */
1395 kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1");
1396 if (kernel == (KernelInfo *) NULL)
1398 kernel->type = type;
1399 kernel->values[1] = kernel->values[3]= +(MagickRealType) MagickSQ2;
1400 kernel->values[5] = kernel->values[7]= -(MagickRealType) MagickSQ2;
1401 CalcKernelMetaData(kernel); /* recalculate meta-data */
1402 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1405 kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19");
1406 if (kernel == (KernelInfo *) NULL)
1411 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1412 if (kernel == (KernelInfo *) NULL)
1414 kernel->type = type;
1415 kernel->values[3] = +(MagickRealType) MagickSQ2;
1416 kernel->values[5] = -(MagickRealType) MagickSQ2;
1417 CalcKernelMetaData(kernel); /* recalculate meta-data */
1418 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1421 kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1");
1422 if (kernel == (KernelInfo *) NULL)
1424 kernel->type = type;
1425 kernel->values[1] = +(MagickRealType) MagickSQ2;
1426 kernel->values[7] = +(MagickRealType) MagickSQ2;
1427 CalcKernelMetaData(kernel);
1428 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1431 kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
1432 if (kernel == (KernelInfo *) NULL)
1434 kernel->type = type;
1435 kernel->values[0] = +(MagickRealType) MagickSQ2;
1436 kernel->values[8] = -(MagickRealType) MagickSQ2;
1437 CalcKernelMetaData(kernel);
1438 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1441 kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0");
1442 if (kernel == (KernelInfo *) NULL)
1444 kernel->type = type;
1445 kernel->values[2] = -(MagickRealType) MagickSQ2;
1446 kernel->values[6] = +(MagickRealType) MagickSQ2;
1447 CalcKernelMetaData(kernel);
1448 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1451 kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0");
1452 if (kernel == (KernelInfo *) NULL)
1454 kernel->type = type;
1455 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1458 kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1");
1459 if (kernel == (KernelInfo *) NULL)
1461 kernel->type = type;
1462 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1465 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1");
1466 if (kernel == (KernelInfo *) NULL)
1468 kernel->type = type;
1469 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1472 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1473 if (kernel == (KernelInfo *) NULL)
1475 kernel->type = type;
1476 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1479 kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
1480 if (kernel == (KernelInfo *) NULL)
1482 kernel->type = type;
1483 ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1486 if ( fabs(args->sigma) > MagickEpsilon )
1487 /* Rotate by correctly supplied 'angle' */
1488 RotateKernelInfo(kernel, args->sigma);
1489 else if ( args->rho > 30.0 || args->rho < -30.0 )
1490 /* Rotate by out of bounds 'type' */
1491 RotateKernelInfo(kernel, args->rho);
1496 Boolean or Shaped Kernels
1500 if (args->rho < 1.0)
1501 kernel->width = kernel->height = 3; /* default radius = 1 */
1503 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1504 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1506 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1507 kernel->height*sizeof(*kernel->values));
1508 if (kernel->values == (double *) NULL)
1509 return(DestroyKernelInfo(kernel));
1511 /* set all kernel values within diamond area to scale given */
1512 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1513 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1514 if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
1515 kernel->positive_range += kernel->values[i] = args->sigma;
1517 kernel->values[i] = nan;
1518 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1522 case RectangleKernel:
1525 if ( type == SquareKernel )
1527 if (args->rho < 1.0)
1528 kernel->width = kernel->height = 3; /* default radius = 1 */
1530 kernel->width = kernel->height = (size_t) (2*args->rho+1);
1531 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1532 scale = args->sigma;
1535 /* NOTE: user defaults set in "AcquireKernelInfo()" */
1536 if ( args->rho < 1.0 || args->sigma < 1.0 )
1537 return(DestroyKernelInfo(kernel)); /* invalid args given */
1538 kernel->width = (size_t)args->rho;
1539 kernel->height = (size_t)args->sigma;
1540 if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
1541 args->psi < 0.0 || args->psi > (double)kernel->height )
1542 return(DestroyKernelInfo(kernel)); /* invalid args given */
1543 kernel->x = (ssize_t) args->xi;
1544 kernel->y = (ssize_t) args->psi;
1547 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1548 kernel->height*sizeof(*kernel->values));
1549 if (kernel->values == (double *) NULL)
1550 return(DestroyKernelInfo(kernel));
1552 /* set all kernel values to scale given */
1553 u=(ssize_t) (kernel->width*kernel->height);
1554 for ( i=0; i < u; i++)
1555 kernel->values[i] = scale;
1556 kernel->minimum = kernel->maximum = scale; /* a flat shape */
1557 kernel->positive_range = scale*u;
1562 if (args->rho < 1.0)
1563 kernel->width = kernel->height = 5; /* default radius = 2 */
1565 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1566 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1568 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1569 kernel->height*sizeof(*kernel->values));
1570 if (kernel->values == (double *) NULL)
1571 return(DestroyKernelInfo(kernel));
1573 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1574 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1575 if ( (labs((long) u)+labs((long) v)) <=
1576 ((long)kernel->x + (long)(kernel->x/2)) )
1577 kernel->positive_range += kernel->values[i] = args->sigma;
1579 kernel->values[i] = nan;
1580 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1586 limit = (ssize_t)(args->rho*args->rho);
1588 if (args->rho < 0.4) /* default radius approx 4.3 */
1589 kernel->width = kernel->height = 9L, limit = 18L;
1591 kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1;
1592 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1594 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1595 kernel->height*sizeof(*kernel->values));
1596 if (kernel->values == (double *) NULL)
1597 return(DestroyKernelInfo(kernel));
1599 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1600 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1601 if ((u*u+v*v) <= limit)
1602 kernel->positive_range += kernel->values[i] = args->sigma;
1604 kernel->values[i] = nan;
1605 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1610 if (args->rho < 1.0)
1611 kernel->width = kernel->height = 5; /* default radius 2 */
1613 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1614 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1616 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1617 kernel->height*sizeof(*kernel->values));
1618 if (kernel->values == (double *) NULL)
1619 return(DestroyKernelInfo(kernel));
1621 /* set all kernel values along axises to given scale */
1622 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1623 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1624 kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1625 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1626 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1631 if (args->rho < 1.0)
1632 kernel->width = kernel->height = 5; /* default radius 2 */
1634 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1635 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1637 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1638 kernel->height*sizeof(*kernel->values));
1639 if (kernel->values == (double *) NULL)
1640 return(DestroyKernelInfo(kernel));
1642 /* set all kernel values along axises to given scale */
1643 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1644 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1645 kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1646 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1647 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1661 if (args->rho < args->sigma)
1663 kernel->width = ((size_t)args->sigma)*2+1;
1664 limit1 = (ssize_t)(args->rho*args->rho);
1665 limit2 = (ssize_t)(args->sigma*args->sigma);
1669 kernel->width = ((size_t)args->rho)*2+1;
1670 limit1 = (ssize_t)(args->sigma*args->sigma);
1671 limit2 = (ssize_t)(args->rho*args->rho);
1674 kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1676 kernel->height = kernel->width;
1677 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1678 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1679 kernel->height*sizeof(*kernel->values));
1680 if (kernel->values == (double *) NULL)
1681 return(DestroyKernelInfo(kernel));
1683 /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
1684 scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
1685 for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
1686 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1687 { ssize_t radius=u*u+v*v;
1688 if (limit1 < radius && radius <= limit2)
1689 kernel->positive_range += kernel->values[i] = (double) scale;
1691 kernel->values[i] = nan;
1693 kernel->minimum = kernel->maximum = (double) scale;
1694 if ( type == PeaksKernel ) {
1695 /* set the central point in the middle */
1696 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1697 kernel->positive_range = 1.0;
1698 kernel->maximum = 1.0;
1704 kernel=AcquireKernelInfo("ThinSE:482");
1705 if (kernel == (KernelInfo *) NULL)
1707 kernel->type = type;
1708 ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */
1713 kernel=AcquireKernelInfo("ThinSE:87");
1714 if (kernel == (KernelInfo *) NULL)
1716 kernel->type = type;
1717 ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
1720 case DiagonalsKernel:
1722 switch ( (int) args->rho ) {
1727 kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
1728 if (kernel == (KernelInfo *) NULL)
1730 kernel->type = type;
1731 new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
1732 if (new_kernel == (KernelInfo *) NULL)
1733 return(DestroyKernelInfo(kernel));
1734 new_kernel->type = type;
1735 LastKernelInfo(kernel)->next = new_kernel;
1736 ExpandMirrorKernelInfo(kernel);
1740 kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
1743 kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
1746 if (kernel == (KernelInfo *) NULL)
1748 kernel->type = type;
1749 RotateKernelInfo(kernel, args->sigma);
1752 case LineEndsKernel:
1753 { /* Kernels for finding the end of thin lines */
1754 switch ( (int) args->rho ) {
1757 /* set of kernels to find all end of lines */
1758 return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>"));
1760 /* kernel for 4-connected line ends - no rotation */
1761 kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-");
1764 /* kernel to add for 8-connected lines - no rotation */
1765 kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
1768 /* kernel to add for orthogonal line ends - does not find corners */
1769 kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0");
1772 /* traditional line end - fails on last T end */
1773 kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-");
1776 if (kernel == (KernelInfo *) NULL)
1778 kernel->type = type;
1779 RotateKernelInfo(kernel, args->sigma);
1782 case LineJunctionsKernel:
1783 { /* kernels for finding the junctions of multiple lines */
1784 switch ( (int) args->rho ) {
1787 /* set of kernels to find all line junctions */
1788 return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>"));
1791 kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-");
1794 /* Diagonal T Junctions */
1795 kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
1798 /* Orthogonal T Junctions */
1799 kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-");
1802 /* Diagonal X Junctions */
1803 kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1");
1806 /* Orthogonal X Junctions - minimal diamond kernel */
1807 kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-");
1810 if (kernel == (KernelInfo *) NULL)
1812 kernel->type = type;
1813 RotateKernelInfo(kernel, args->sigma);
1817 { /* Ridges - Ridge finding kernels */
1820 switch ( (int) args->rho ) {
1823 kernel=ParseKernelArray("3x1:0,1,0");
1824 if (kernel == (KernelInfo *) NULL)
1826 kernel->type = type;
1827 ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
1830 kernel=ParseKernelArray("4x1:0,1,1,0");
1831 if (kernel == (KernelInfo *) NULL)
1833 kernel->type = type;
1834 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
1836 /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */
1837 /* Unfortunatally we can not yet rotate a non-square kernel */
1838 /* But then we can't flip a non-symetrical kernel either */
1839 new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1840 if (new_kernel == (KernelInfo *) NULL)
1841 return(DestroyKernelInfo(kernel));
1842 new_kernel->type = type;
1843 LastKernelInfo(kernel)->next = new_kernel;
1844 new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
1845 if (new_kernel == (KernelInfo *) NULL)
1846 return(DestroyKernelInfo(kernel));
1847 new_kernel->type = type;
1848 LastKernelInfo(kernel)->next = new_kernel;
1849 new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
1850 if (new_kernel == (KernelInfo *) NULL)
1851 return(DestroyKernelInfo(kernel));
1852 new_kernel->type = type;
1853 LastKernelInfo(kernel)->next = new_kernel;
1854 new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
1855 if (new_kernel == (KernelInfo *) NULL)
1856 return(DestroyKernelInfo(kernel));
1857 new_kernel->type = type;
1858 LastKernelInfo(kernel)->next = new_kernel;
1859 new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
1860 if (new_kernel == (KernelInfo *) NULL)
1861 return(DestroyKernelInfo(kernel));
1862 new_kernel->type = type;
1863 LastKernelInfo(kernel)->next = new_kernel;
1864 new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
1865 if (new_kernel == (KernelInfo *) NULL)
1866 return(DestroyKernelInfo(kernel));
1867 new_kernel->type = type;
1868 LastKernelInfo(kernel)->next = new_kernel;
1869 new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
1870 if (new_kernel == (KernelInfo *) NULL)
1871 return(DestroyKernelInfo(kernel));
1872 new_kernel->type = type;
1873 LastKernelInfo(kernel)->next = new_kernel;
1874 new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
1875 if (new_kernel == (KernelInfo *) NULL)
1876 return(DestroyKernelInfo(kernel));
1877 new_kernel->type = type;
1878 LastKernelInfo(kernel)->next = new_kernel;
1883 case ConvexHullKernel:
1887 /* first set of 8 kernels */
1888 kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
1889 if (kernel == (KernelInfo *) NULL)
1891 kernel->type = type;
1892 ExpandRotateKernelInfo(kernel, 90.0);
1893 /* append the mirror versions too - no flip function yet */
1894 new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0");
1895 if (new_kernel == (KernelInfo *) NULL)
1896 return(DestroyKernelInfo(kernel));
1897 new_kernel->type = type;
1898 ExpandRotateKernelInfo(new_kernel, 90.0);
1899 LastKernelInfo(kernel)->next = new_kernel;
1902 case SkeletonKernel:
1904 switch ( (int) args->rho ) {
1907 /* Traditional Skeleton...
1908 ** A cyclically rotated single kernel
1910 kernel=AcquireKernelInfo("ThinSE:482");
1911 if (kernel == (KernelInfo *) NULL)
1913 kernel->type = type;
1914 ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */
1917 /* HIPR Variation of the cyclic skeleton
1918 ** Corners of the traditional method made more forgiving,
1919 ** but the retain the same cyclic order.
1921 kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;");
1922 if (kernel == (KernelInfo *) NULL)
1924 if (kernel->next == (KernelInfo *) NULL)
1925 return(DestroyKernelInfo(kernel));
1926 kernel->type = type;
1927 kernel->next->type = type;
1928 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */
1931 /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's
1932 ** "Connectivity-Preserving Morphological Image Thransformations"
1933 ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1934 ** http://www.leptonica.com/papers/conn.pdf
1936 kernel=AcquireKernelInfo(
1937 "ThinSE:41; ThinSE:42; ThinSE:43");
1938 if (kernel == (KernelInfo *) NULL)
1940 kernel->type = type;
1941 kernel->next->type = type;
1942 kernel->next->next->type = type;
1943 ExpandMirrorKernelInfo(kernel); /* 12 kernels total */
1949 { /* Special kernels for general thinning, while preserving connections
1950 ** "Connectivity-Preserving Morphological Image Thransformations"
1951 ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1952 ** http://www.leptonica.com/papers/conn.pdf
1954 ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html
1956 ** Note kernels do not specify the origin pixel, allowing them
1957 ** to be used for both thickening and thinning operations.
1959 switch ( (int) args->rho ) {
1960 /* SE for 4-connected thinning */
1961 case 41: /* SE_4_1 */
1962 kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1");
1964 case 42: /* SE_4_2 */
1965 kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-");
1967 case 43: /* SE_4_3 */
1968 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1");
1970 case 44: /* SE_4_4 */
1971 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-");
1973 case 45: /* SE_4_5 */
1974 kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-");
1976 case 46: /* SE_4_6 */
1977 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1");
1979 case 47: /* SE_4_7 */
1980 kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-");
1982 case 48: /* SE_4_8 */
1983 kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1");
1985 case 49: /* SE_4_9 */
1986 kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1");
1988 /* SE for 8-connected thinning - negatives of the above */
1989 case 81: /* SE_8_0 */
1990 kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-");
1992 case 82: /* SE_8_2 */
1993 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-");
1995 case 83: /* SE_8_3 */
1996 kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-");
1998 case 84: /* SE_8_4 */
1999 kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-");
2001 case 85: /* SE_8_5 */
2002 kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-");
2004 case 86: /* SE_8_6 */
2005 kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1");
2007 case 87: /* SE_8_7 */
2008 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-");
2010 case 88: /* SE_8_8 */
2011 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-");
2013 case 89: /* SE_8_9 */
2014 kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-");
2016 /* Special combined SE kernels */
2017 case 423: /* SE_4_2 , SE_4_3 Combined Kernel */
2018 kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-");
2020 case 823: /* SE_8_2 , SE_8_3 Combined Kernel */
2021 kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-");
2023 case 481: /* SE_48_1 - General Connected Corner Kernel */
2024 kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-");
2027 case 482: /* SE_48_2 - General Edge Kernel */
2028 kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1");
2031 if (kernel == (KernelInfo *) NULL)
2033 kernel->type = type;
2034 RotateKernelInfo(kernel, args->sigma);
2038 Distance Measuring Kernels
2040 case ChebyshevKernel:
2042 if (args->rho < 1.0)
2043 kernel->width = kernel->height = 3; /* default radius = 1 */
2045 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2046 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2048 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2049 kernel->height*sizeof(*kernel->values));
2050 if (kernel->values == (double *) NULL)
2051 return(DestroyKernelInfo(kernel));
2053 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2054 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2055 kernel->positive_range += ( kernel->values[i] =
2056 args->sigma*MagickMax(fabs((double)u),fabs((double)v)) );
2057 kernel->maximum = kernel->values[0];
2060 case ManhattanKernel:
2062 if (args->rho < 1.0)
2063 kernel->width = kernel->height = 3; /* default radius = 1 */
2065 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2066 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2068 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2069 kernel->height*sizeof(*kernel->values));
2070 if (kernel->values == (double *) NULL)
2071 return(DestroyKernelInfo(kernel));
2073 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2074 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2075 kernel->positive_range += ( kernel->values[i] =
2076 args->sigma*(labs((long) u)+labs((long) v)) );
2077 kernel->maximum = kernel->values[0];
2080 case OctagonalKernel:
2082 if (args->rho < 2.0)
2083 kernel->width = kernel->height = 5; /* default/minimum radius = 2 */
2085 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2086 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2088 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2089 kernel->height*sizeof(*kernel->values));
2090 if (kernel->values == (double *) NULL)
2091 return(DestroyKernelInfo(kernel));
2093 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2094 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2097 r1 = MagickMax(fabs((double)u),fabs((double)v)),
2098 r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5);
2099 kernel->positive_range += kernel->values[i] =
2100 args->sigma*MagickMax(r1,r2);
2102 kernel->maximum = kernel->values[0];
2105 case EuclideanKernel:
2107 if (args->rho < 1.0)
2108 kernel->width = kernel->height = 3; /* default radius = 1 */
2110 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2111 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2113 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2114 kernel->height*sizeof(*kernel->values));
2115 if (kernel->values == (double *) NULL)
2116 return(DestroyKernelInfo(kernel));
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*sqrt((double)(u*u+v*v)) );
2122 kernel->maximum = kernel->values[0];
2127 /* No-Op Kernel - Basically just a single pixel on its own */
2128 kernel=ParseKernelArray("1:1");
2129 if (kernel == (KernelInfo *) NULL)
2131 kernel->type = UndefinedKernel;
2140 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2144 % C l o n e K e r n e l I n f o %
2148 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2150 % CloneKernelInfo() creates a new clone of the given Kernel List so that its
2151 % can be modified without effecting the original. The cloned kernel should
2152 % be destroyed using DestoryKernelInfo() when no longer needed.
2154 % The format of the CloneKernelInfo method is:
2156 % KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2158 % A description of each parameter follows:
2160 % o kernel: the Morphology/Convolution kernel to be cloned
2163 MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2171 assert(kernel != (KernelInfo *) NULL);
2172 new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
2173 if (new_kernel == (KernelInfo *) NULL)
2175 *new_kernel=(*kernel); /* copy values in structure */
2177 /* replace the values with a copy of the values */
2178 new_kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2179 kernel->height*sizeof(*kernel->values));
2180 if (new_kernel->values == (double *) NULL)
2181 return(DestroyKernelInfo(new_kernel));
2182 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
2183 new_kernel->values[i]=kernel->values[i];
2185 /* Also clone the next kernel in the kernel list */
2186 if ( kernel->next != (KernelInfo *) NULL ) {
2187 new_kernel->next = CloneKernelInfo(kernel->next);
2188 if ( new_kernel->next == (KernelInfo *) NULL )
2189 return(DestroyKernelInfo(new_kernel));
2196 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2200 % D e s t r o y K e r n e l I n f o %
2204 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2206 % DestroyKernelInfo() frees the memory used by a Convolution/Morphology
2209 % The format of the DestroyKernelInfo method is:
2211 % KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2213 % A description of each parameter follows:
2215 % o kernel: the Morphology/Convolution kernel to be destroyed
2218 MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2220 assert(kernel != (KernelInfo *) NULL);
2221 if ( kernel->next != (KernelInfo *) NULL )
2222 kernel->next=DestroyKernelInfo(kernel->next);
2223 kernel->values=(double *) RelinquishAlignedMemory(kernel->values);
2224 kernel=(KernelInfo *) RelinquishMagickMemory(kernel);
2229 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2233 + E x p a n d M i r r o r K e r n e l I n f o %
2237 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2239 % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
2240 % sequence of 90-degree rotated kernels but providing a reflected 180
2241 % rotatation, before the -/+ 90-degree rotations.
2243 % This special rotation order produces a better, more symetrical thinning of
2246 % The format of the ExpandMirrorKernelInfo method is:
2248 % void ExpandMirrorKernelInfo(KernelInfo *kernel)
2250 % A description of each parameter follows:
2252 % o kernel: the Morphology/Convolution kernel
2254 % This function is only internel to this module, as it is not finalized,
2255 % especially with regard to non-orthogonal angles, and rotation of larger
2260 static void FlopKernelInfo(KernelInfo *kernel)
2261 { /* Do a Flop by reversing each row. */
2269 for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
2270 for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
2271 t=k[x], k[x]=k[r], k[r]=t;
2273 kernel->x = kernel->width - kernel->x - 1;
2274 angle = fmod(angle+180.0, 360.0);
2278 static void ExpandMirrorKernelInfo(KernelInfo *kernel)
2286 clone = CloneKernelInfo(last);
2287 RotateKernelInfo(clone, 180); /* flip */
2288 LastKernelInfo(last)->next = clone;
2291 clone = CloneKernelInfo(last);
2292 RotateKernelInfo(clone, 90); /* transpose */
2293 LastKernelInfo(last)->next = clone;
2296 clone = CloneKernelInfo(last);
2297 RotateKernelInfo(clone, 180); /* flop */
2298 LastKernelInfo(last)->next = clone;
2304 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2308 + E x p a n d R o t a t e K e r n e l I n f o %
2312 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2314 % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
2315 % incrementally by the angle given, until the kernel repeats.
2317 % WARNING: 45 degree rotations only works for 3x3 kernels.
2318 % While 90 degree roatations only works for linear and square kernels
2320 % The format of the ExpandRotateKernelInfo method is:
2322 % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
2324 % A description of each parameter follows:
2326 % o kernel: the Morphology/Convolution kernel
2328 % o angle: angle to rotate in degrees
2330 % This function is only internel to this module, as it is not finalized,
2331 % especially with regard to non-orthogonal angles, and rotation of larger
2335 /* Internal Routine - Return true if two kernels are the same */
2336 static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
2337 const KernelInfo *kernel2)
2342 /* check size and origin location */
2343 if ( kernel1->width != kernel2->width
2344 || kernel1->height != kernel2->height
2345 || kernel1->x != kernel2->x
2346 || kernel1->y != kernel2->y )
2349 /* check actual kernel values */
2350 for (i=0; i < (kernel1->width*kernel1->height); i++) {
2351 /* Test for Nan equivalence */
2352 if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
2354 if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
2356 /* Test actual values are equivalent */
2357 if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
2364 static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
2372 clone = CloneKernelInfo(last);
2373 RotateKernelInfo(clone, angle);
2374 if ( SameKernelInfo(kernel, clone) == MagickTrue )
2376 LastKernelInfo(last)->next = clone;
2379 clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
2384 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2388 + C a l c M e t a K e r n a l I n f o %
2392 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2394 % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2395 % using the kernel values. This should only ne used if it is not possible to
2396 % calculate that meta-data in some easier way.
2398 % It is important that the meta-data is correct before ScaleKernelInfo() is
2399 % used to perform kernel normalization.
2401 % The format of the CalcKernelMetaData method is:
2403 % void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2405 % A description of each parameter follows:
2407 % o kernel: the Morphology/Convolution kernel to modify
2409 % WARNING: Minimum and Maximum values are assumed to include zero, even if
2410 % zero is not part of the kernel (as in Gaussian Derived kernels). This
2411 % however is not true for flat-shaped morphological kernels.
2413 % WARNING: Only the specific kernel pointed to is modified, not a list of
2416 % This is an internal function and not expected to be useful outside this
2417 % module. This could change however.
2419 static void CalcKernelMetaData(KernelInfo *kernel)
2424 kernel->minimum = kernel->maximum = 0.0;
2425 kernel->negative_range = kernel->positive_range = 0.0;
2426 for (i=0; i < (kernel->width*kernel->height); i++)
2428 if ( fabs(kernel->values[i]) < MagickEpsilon )
2429 kernel->values[i] = 0.0;
2430 ( kernel->values[i] < 0)
2431 ? ( kernel->negative_range += kernel->values[i] )
2432 : ( kernel->positive_range += kernel->values[i] );
2433 Minimize(kernel->minimum, kernel->values[i]);
2434 Maximize(kernel->maximum, kernel->values[i]);
2441 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2445 % M o r p h o l o g y A p p l y %
2449 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2451 % MorphologyApply() applies a morphological method, multiple times using
2452 % a list of multiple kernels. This is the method that should be called by
2453 % other 'operators' that internally use morphology operations as part of
2456 % It is basically equivalent to as MorphologyImage() (see below) but
2457 % without any user controls. This allows internel programs to use this
2458 % function, to actually perform a specific task without possible interference
2459 % by any API user supplied settings.
2461 % It is MorphologyImage() task to extract any such user controls, and
2462 % pass them to this function for processing.
2464 % More specifically all given kernels should already be scaled, normalised,
2465 % and blended appropriatally before being parred to this routine. The
2466 % appropriate bias, and compose (typically 'UndefinedComposeOp') given.
2468 % The format of the MorphologyApply method is:
2470 % Image *MorphologyApply(const Image *image,MorphologyMethod method,
2471 % const ssize_t iterations,const KernelInfo *kernel,
2472 % const CompositeMethod compose,const double bias,
2473 % ExceptionInfo *exception)
2475 % A description of each parameter follows:
2477 % o image: the source image
2479 % o method: the morphology method to be applied.
2481 % o iterations: apply the operation this many times (or no change).
2482 % A value of -1 means loop until no change found.
2483 % How this is applied may depend on the morphology method.
2484 % Typically this is a value of 1.
2486 % o channel: the channel type.
2488 % o kernel: An array of double representing the morphology kernel.
2490 % o compose: How to handle or merge multi-kernel results.
2491 % If 'UndefinedCompositeOp' use default for the Morphology method.
2492 % If 'NoCompositeOp' force image to be re-iterated by each kernel.
2493 % Otherwise merge the results using the compose method given.
2495 % o bias: Convolution Output Bias.
2497 % o exception: return any errors or warnings in this structure.
2501 /* Apply a Morphology Primative to an image using the given kernel.
2502 ** Two pre-created images must be provided, and no image is created.
2503 ** It returns the number of pixels that changed between the images
2504 ** for result convergence determination.
2506 static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image,
2507 const MorphologyMethod method,const KernelInfo *kernel,const double bias,
2508 ExceptionInfo *exception)
2510 #define MorphologyTag "Morphology/Image"
2529 assert(image != (Image *) NULL);
2530 assert(image->signature == MagickSignature);
2531 assert(morphology_image != (Image *) NULL);
2532 assert(morphology_image->signature == MagickSignature);
2533 assert(kernel != (KernelInfo *) NULL);
2534 assert(kernel->signature == MagickSignature);
2535 assert(exception != (ExceptionInfo *) NULL);
2536 assert(exception->signature == MagickSignature);
2542 image_view=AcquireVirtualCacheView(image,exception);
2543 morphology_view=AcquireAuthenticCacheView(morphology_image,exception);
2544 virt_width=image->columns+kernel->width-1;
2546 /* Some methods (including convolve) needs use a reflected kernel.
2547 * Adjust 'origin' offsets to loop though kernel as a reflection.
2552 case ConvolveMorphology:
2553 case DilateMorphology:
2554 case DilateIntensityMorphology:
2555 case IterativeDistanceMorphology:
2556 /* kernel needs to used with reflection about origin */
2557 offx = (ssize_t) kernel->width-offx-1;
2558 offy = (ssize_t) kernel->height-offy-1;
2560 case ErodeMorphology:
2561 case ErodeIntensityMorphology:
2562 case HitAndMissMorphology:
2563 case ThinningMorphology:
2564 case ThickenMorphology:
2565 /* kernel is used as is, without reflection */
2568 assert("Not a Primitive Morphology Method" != (char *) NULL);
2572 if ( method == ConvolveMorphology && kernel->width == 1 )
2573 { /* Special handling (for speed) of vertical (blur) kernels.
2574 ** This performs its handling in columns rather than in rows.
2575 ** This is only done for convolve as it is the only method that
2576 ** generates very large 1-D vertical kernels (such as a 'BlurKernel')
2578 ** Timing tests (on single CPU laptop)
2579 ** Using a vertical 1-d Blue with normal row-by-row (below)
2580 ** time convert logo: -morphology Convolve Blur:0x10+90 null:
2582 ** Using this column method
2583 ** time convert logo: -morphology Convolve Blur:0x10+90 null:
2586 ** Anthony Thyssen, 14 June 2010
2591 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2592 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2593 dynamic_number_threads(image->columns,image->rows,1)
2595 for (x=0; x < (ssize_t) image->columns; x++)
2597 register const Quantum
2609 if (status == MagickFalse)
2611 p=GetCacheViewVirtualPixels(image_view,x,-offy,1,image->rows+
2612 kernel->height-1,exception);
2613 q=GetCacheViewAuthenticPixels(morphology_view,x,0,1,
2614 morphology_image->rows,exception);
2615 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2620 /* offset to origin in 'p'. while 'q' points to it directly */
2623 for (y=0; y < (ssize_t) image->rows; y++)
2631 register const double
2634 register const Quantum
2637 /* Copy input image to the output image for unused channels
2638 * This removes need for 'cloning' a new image every iteration
2640 SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2641 GetPixelChannels(image)),q);
2642 SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2643 GetPixelChannels(image)),q);
2644 SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2645 GetPixelChannels(image)),q);
2646 if (image->colorspace == CMYKColorspace)
2647 SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2648 GetPixelChannels(image)),q);
2650 /* Set the bias of the weighted average output */
2655 result.black = bias;
2658 /* Weighted Average of pixels using reflected kernel
2660 ** NOTE for correct working of this operation for asymetrical
2661 ** kernels, the kernel needs to be applied in its reflected form.
2662 ** That is its values needs to be reversed.
2664 k = &kernel->values[ kernel->height-1 ];
2666 if ( (image->channel_mask != DefaultChannels) ||
2667 (image->matte == MagickFalse) )
2668 { /* No 'Sync' involved.
2669 ** Convolution is just a simple greyscale channel operation
2671 for (v=0; v < (ssize_t) kernel->height; v++) {
2672 if ( IsNan(*k) ) continue;
2673 result.red += (*k)*GetPixelRed(image,k_pixels);
2674 result.green += (*k)*GetPixelGreen(image,k_pixels);
2675 result.blue += (*k)*GetPixelBlue(image,k_pixels);
2676 if (image->colorspace == CMYKColorspace)
2677 result.black+=(*k)*GetPixelBlack(image,k_pixels);
2678 result.alpha += (*k)*GetPixelAlpha(image,k_pixels);
2680 k_pixels+=GetPixelChannels(image);
2682 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2683 SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
2684 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2685 SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
2686 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2687 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
2688 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2689 (image->colorspace == CMYKColorspace))
2690 SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
2691 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2692 (image->matte == MagickTrue))
2693 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2696 { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2697 ** Weight the color channels with Alpha Channel so that
2698 ** transparent pixels are not part of the results.
2701 alpha, /* alpha weighting for colors : alpha */
2702 gamma; /* divisor, sum of color alpha weighting */
2704 count; /* alpha valus collected, number kernel values */
2708 for (v=0; v < (ssize_t) kernel->height; v++) {
2709 if ( IsNan(*k) ) continue;
2710 alpha=QuantumScale*GetPixelAlpha(image,k_pixels);
2711 gamma += alpha; /* normalize alpha weights only */
2712 count++; /* number of alpha values collected */
2713 alpha*=(*k); /* include kernel weighting now */
2714 result.red += alpha*GetPixelRed(image,k_pixels);
2715 result.green += alpha*GetPixelGreen(image,k_pixels);
2716 result.blue += alpha*GetPixelBlue(image,k_pixels);
2717 if (image->colorspace == CMYKColorspace)
2718 result.black += alpha*GetPixelBlack(image,k_pixels);
2719 result.alpha += (*k)*GetPixelAlpha(image,k_pixels);
2721 k_pixels+=GetPixelChannels(image);
2723 /* Sync'ed channels, all channels are modified */
2724 gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2725 SetPixelRed(morphology_image,ClampToQuantum(gamma*result.red),q);
2726 SetPixelGreen(morphology_image,ClampToQuantum(gamma*result.green),q);
2727 SetPixelBlue(morphology_image,ClampToQuantum(gamma*result.blue),q);
2728 if (image->colorspace == CMYKColorspace)
2729 SetPixelBlack(morphology_image,ClampToQuantum(gamma*result.black),q);
2730 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2733 /* Count up changed pixels */
2734 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q))
2735 || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q))
2736 || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q))
2737 || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q))
2738 || ((image->colorspace == CMYKColorspace) &&
2739 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
2740 changed++; /* The pixel was changed in some way! */
2741 p+=GetPixelChannels(image);
2742 q+=GetPixelChannels(morphology_image);
2744 if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
2746 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2751 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2752 #pragma omp critical (MagickCore_MorphologyImage)
2754 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
2755 if (proceed == MagickFalse)
2759 morphology_image->type=image->type;
2760 morphology_view=DestroyCacheView(morphology_view);
2761 image_view=DestroyCacheView(image_view);
2762 return(status ? (ssize_t) changed : 0);
2766 ** Normal handling of horizontal or rectangular kernels (row by row)
2768 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2769 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2770 dynamic_number_threads(image->columns,image->rows,1)
2772 for (y=0; y < (ssize_t) image->rows; y++)
2774 register const Quantum
2786 if (status == MagickFalse)
2788 p=GetCacheViewVirtualPixels(image_view, -offx, y-offy, virt_width,
2789 kernel->height, exception);
2790 q=GetCacheViewAuthenticPixels(morphology_view,0,y,
2791 morphology_image->columns,1,exception);
2792 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2797 /* offset to origin in 'p'. while 'q' points to it directly */
2798 r = virt_width*offy + offx;
2800 for (x=0; x < (ssize_t) image->columns; x++)
2808 register const double
2811 register const Quantum
2819 /* Copy input image to the output image for unused channels
2820 * This removes need for 'cloning' a new image every iteration
2822 SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2823 GetPixelChannels(image)),q);
2824 SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2825 GetPixelChannels(image)),q);
2826 SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2827 GetPixelChannels(image)),q);
2828 if (image->colorspace == CMYKColorspace)
2829 SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2830 GetPixelChannels(image)),q);
2837 min.black = (MagickRealType) QuantumRange;
2842 max.black = (MagickRealType) 0;
2843 /* default result is the original pixel value */
2844 result.red = (MagickRealType) GetPixelRed(image,p+r*GetPixelChannels(image));
2845 result.green = (MagickRealType) GetPixelGreen(image,p+r*GetPixelChannels(image));
2846 result.blue = (MagickRealType) GetPixelBlue(image,p+r*GetPixelChannels(image));
2848 if (image->colorspace == CMYKColorspace)
2849 result.black = (MagickRealType) GetPixelBlack(image,p+r*GetPixelChannels(image));
2850 result.alpha=(MagickRealType) GetPixelAlpha(image,p+r*GetPixelChannels(image));
2853 case ConvolveMorphology:
2854 /* Set the bias of the weighted average output */
2859 result.black = bias;
2861 case DilateIntensityMorphology:
2862 case ErodeIntensityMorphology:
2863 /* use a boolean flag indicating when first match found */
2864 result.red = 0.0; /* result is not used otherwise */
2871 case ConvolveMorphology:
2872 /* Weighted Average of pixels using reflected kernel
2874 ** NOTE for correct working of this operation for asymetrical
2875 ** kernels, the kernel needs to be applied in its reflected form.
2876 ** That is its values needs to be reversed.
2878 ** Correlation is actually the same as this but without reflecting
2879 ** the kernel, and thus 'lower-level' that Convolution. However
2880 ** as Convolution is the more common method used, and it does not
2881 ** really cost us much in terms of processing to use a reflected
2882 ** kernel, so it is Convolution that is implemented.
2884 ** Correlation will have its kernel reflected before calling
2885 ** this function to do a Convolve.
2887 ** For more details of Correlation vs Convolution see
2888 ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
2890 k = &kernel->values[ kernel->width*kernel->height-1 ];
2892 if ( (image->channel_mask != DefaultChannels) ||
2893 (image->matte == MagickFalse) )
2894 { /* No 'Sync' involved.
2895 ** Convolution is simple greyscale channel operation
2897 for (v=0; v < (ssize_t) kernel->height; v++) {
2898 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2899 if ( IsNan(*k) ) continue;
2901 GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2902 result.green += (*k)*
2903 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2904 result.blue += (*k)*
2905 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2906 if (image->colorspace == CMYKColorspace)
2907 result.black += (*k)*
2908 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2909 result.alpha += (*k)*
2910 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2912 k_pixels += virt_width*GetPixelChannels(image);
2914 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2915 SetPixelRed(morphology_image,ClampToQuantum(result.red),
2917 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2918 SetPixelGreen(morphology_image,ClampToQuantum(result.green),
2920 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2921 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),
2923 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2924 (image->colorspace == CMYKColorspace))
2925 SetPixelBlack(morphology_image,ClampToQuantum(result.black),
2927 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2928 (image->matte == MagickTrue))
2929 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),
2933 { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2934 ** Weight the color channels with Alpha Channel so that
2935 ** transparent pixels are not part of the results.
2938 alpha, /* alpha weighting for colors : alpha */
2939 gamma; /* divisor, sum of color alpha weighting */
2941 count; /* alpha valus collected, number kernel values */
2945 for (v=0; v < (ssize_t) kernel->height; v++) {
2946 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2947 if ( IsNan(*k) ) continue;
2948 alpha=QuantumScale*GetPixelAlpha(image,
2949 k_pixels+u*GetPixelChannels(image));
2950 gamma += alpha; /* normalize alpha weights only */
2951 count++; /* number of alpha values collected */
2952 alpha=alpha*(*k); /* include kernel weighting now */
2953 result.red += alpha*
2954 GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2955 result.green += alpha*
2956 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2957 result.blue += alpha*
2958 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2959 if (image->colorspace == CMYKColorspace)
2960 result.black += alpha*
2961 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2962 result.alpha += (*k)*
2963 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2965 k_pixels += virt_width*GetPixelChannels(image);
2967 /* Sync'ed channels, all channels are modified */
2968 gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2969 SetPixelRed(morphology_image,
2970 ClampToQuantum(gamma*result.red),q);
2971 SetPixelGreen(morphology_image,
2972 ClampToQuantum(gamma*result.green),q);
2973 SetPixelBlue(morphology_image,
2974 ClampToQuantum(gamma*result.blue),q);
2975 if (image->colorspace == CMYKColorspace)
2976 SetPixelBlack(morphology_image,
2977 ClampToQuantum(gamma*result.black),q);
2978 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2982 case ErodeMorphology:
2983 /* Minimum Value within kernel neighbourhood
2985 ** NOTE that the kernel is not reflected for this operation!
2987 ** NOTE: in normal Greyscale Morphology, the kernel value should
2988 ** be added to the real value, this is currently not done, due to
2989 ** the nature of the boolean kernels being used.
2993 for (v=0; v < (ssize_t) kernel->height; v++) {
2994 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
2995 if ( IsNan(*k) || (*k) < 0.5 ) continue;
2996 Minimize(min.red, (double)
2997 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
2998 Minimize(min.green, (double)
2999 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3000 Minimize(min.blue, (double)
3001 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3002 Minimize(min.alpha, (double)
3003 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3004 if (image->colorspace == CMYKColorspace)
3005 Minimize(min.black, (double)
3006 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3008 k_pixels += virt_width*GetPixelChannels(image);
3012 case DilateMorphology:
3013 /* Maximum Value within kernel neighbourhood
3015 ** NOTE for correct working of this operation for asymetrical
3016 ** kernels, the kernel needs to be applied in its reflected form.
3017 ** That is its values needs to be reversed.
3019 ** NOTE: in normal Greyscale Morphology, the kernel value should
3020 ** be added to the real value, this is currently not done, due to
3021 ** the nature of the boolean kernels being used.
3024 k = &kernel->values[ kernel->width*kernel->height-1 ];
3026 for (v=0; v < (ssize_t) kernel->height; v++) {
3027 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3028 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3029 Maximize(max.red, (double)
3030 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3031 Maximize(max.green, (double)
3032 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3033 Maximize(max.blue, (double)
3034 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3035 Maximize(max.alpha, (double)
3036 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3037 if (image->colorspace == CMYKColorspace)
3038 Maximize(max.black, (double)
3039 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3041 k_pixels += virt_width*GetPixelChannels(image);
3045 case HitAndMissMorphology:
3046 case ThinningMorphology:
3047 case ThickenMorphology:
3048 /* Minimum of Foreground Pixel minus Maxumum of Background Pixels
3050 ** NOTE that the kernel is not reflected for this operation,
3051 ** and consists of both foreground and background pixel
3052 ** neighbourhoods, 0.0 for background, and 1.0 for foreground
3053 ** with either Nan or 0.5 values for don't care.
3055 ** Note that this will never produce a meaningless negative
3056 ** result. Such results can cause Thinning/Thicken to not work
3057 ** correctly when used against a greyscale image.
3061 for (v=0; v < (ssize_t) kernel->height; v++) {
3062 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3063 if ( IsNan(*k) ) continue;
3065 { /* minimim of foreground pixels */
3066 Minimize(min.red, (double)
3067 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3068 Minimize(min.green, (double)
3069 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3070 Minimize(min.blue, (double)
3071 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3072 Minimize(min.alpha,(double)
3073 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3074 if ( image->colorspace == CMYKColorspace)
3075 Minimize(min.black,(double)
3076 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3078 else if ( (*k) < 0.3 )
3079 { /* maximum of background pixels */
3080 Maximize(max.red, (double)
3081 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3082 Maximize(max.green, (double)
3083 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3084 Maximize(max.blue, (double)
3085 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3086 Maximize(max.alpha,(double)
3087 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3088 if (image->colorspace == CMYKColorspace)
3089 Maximize(max.black, (double)
3090 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3093 k_pixels += virt_width*GetPixelChannels(image);
3095 /* Pattern Match if difference is positive */
3096 min.red -= max.red; Maximize( min.red, 0.0 );
3097 min.green -= max.green; Maximize( min.green, 0.0 );
3098 min.blue -= max.blue; Maximize( min.blue, 0.0 );
3099 min.black -= max.black; Maximize( min.black, 0.0 );
3100 min.alpha -= max.alpha; Maximize( min.alpha, 0.0 );
3103 case ErodeIntensityMorphology:
3104 /* Select Pixel with Minimum Intensity within kernel neighbourhood
3106 ** WARNING: the intensity test fails for CMYK and does not
3107 ** take into account the moderating effect of the alpha channel
3108 ** on the intensity.
3110 ** NOTE that the kernel is not reflected for this operation!
3114 for (v=0; v < (ssize_t) kernel->height; v++) {
3115 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3116 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3117 if ( result.red == 0.0 ||
3118 GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) < GetPixelIntensity(morphology_image,q) ) {
3119 /* copy the whole pixel - no channel selection */
3120 SetPixelRed(morphology_image,GetPixelRed(image,
3121 k_pixels+u*GetPixelChannels(image)),q);
3122 SetPixelGreen(morphology_image,GetPixelGreen(image,
3123 k_pixels+u*GetPixelChannels(image)),q);
3124 SetPixelBlue(morphology_image,GetPixelBlue(image,
3125 k_pixels+u*GetPixelChannels(image)),q);
3126 SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3127 k_pixels+u*GetPixelChannels(image)),q);
3128 if ( result.red > 0.0 ) changed++;
3132 k_pixels += virt_width*GetPixelChannels(image);
3136 case DilateIntensityMorphology:
3137 /* Select Pixel with Maximum Intensity within kernel neighbourhood
3139 ** WARNING: the intensity test fails for CMYK and does not
3140 ** take into account the moderating effect of the alpha channel
3141 ** on the intensity (yet).
3143 ** NOTE for correct working of this operation for asymetrical
3144 ** kernels, the kernel needs to be applied in its reflected form.
3145 ** That is its values needs to be reversed.
3147 k = &kernel->values[ kernel->width*kernel->height-1 ];
3149 for (v=0; v < (ssize_t) kernel->height; v++) {
3150 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3151 if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */
3152 if ( result.red == 0.0 ||
3153 GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) > GetPixelIntensity(morphology_image,q) ) {
3154 /* copy the whole pixel - no channel selection */
3155 SetPixelRed(morphology_image,GetPixelRed(image,
3156 k_pixels+u*GetPixelChannels(image)),q);
3157 SetPixelGreen(morphology_image,GetPixelGreen(image,
3158 k_pixels+u*GetPixelChannels(image)),q);
3159 SetPixelBlue(morphology_image,GetPixelBlue(image,
3160 k_pixels+u*GetPixelChannels(image)),q);
3161 SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3162 k_pixels+u*GetPixelChannels(image)),q);
3163 if ( result.red > 0.0 ) changed++;
3167 k_pixels += virt_width*GetPixelChannels(image);
3171 case IterativeDistanceMorphology:
3172 /* Work out an iterative distance from black edge of a white image
3173 ** shape. Essentually white values are decreased to the smallest
3174 ** 'distance from edge' it can find.
3176 ** It works by adding kernel values to the neighbourhood, and and
3177 ** select the minimum value found. The kernel is rotated before
3178 ** use, so kernel distances match resulting distances, when a user
3179 ** provided asymmetric kernel is applied.
3182 ** This code is almost identical to True GrayScale Morphology But
3185 ** GreyDilate Kernel values added, maximum value found Kernel is
3186 ** rotated before use.
3188 ** GrayErode: Kernel values subtracted and minimum value found No
3189 ** kernel rotation used.
3191 ** Note the the Iterative Distance method is essentially a
3192 ** GrayErode, but with negative kernel values, and kernel
3193 ** rotation applied.
3195 k = &kernel->values[ kernel->width*kernel->height-1 ];
3197 for (v=0; v < (ssize_t) kernel->height; v++) {
3198 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3199 if ( IsNan(*k) ) continue;
3200 Minimize(result.red, (*k)+(double)
3201 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3202 Minimize(result.green, (*k)+(double)
3203 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3204 Minimize(result.blue, (*k)+(double)
3205 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3206 Minimize(result.alpha, (*k)+(double)
3207 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3208 if ( image->colorspace == CMYKColorspace)
3209 Maximize(result.black, (*k)+(double)
3210 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3212 k_pixels += virt_width*GetPixelChannels(image);
3216 case UndefinedMorphology:
3218 break; /* Do nothing */
3220 /* Final mathematics of results (combine with original image?)
3222 ** NOTE: Difference Morphology operators Edge* and *Hat could also
3223 ** be done here but works better with iteration as a image difference
3224 ** in the controling function (below). Thicken and Thinning however
3225 ** should be done here so thay can be iterated correctly.
3228 case HitAndMissMorphology:
3229 case ErodeMorphology:
3230 result = min; /* minimum of neighbourhood */
3232 case DilateMorphology:
3233 result = max; /* maximum of neighbourhood */
3235 case ThinningMorphology:
3236 /* subtract pattern match from original */
3237 result.red -= min.red;
3238 result.green -= min.green;
3239 result.blue -= min.blue;
3240 result.black -= min.black;
3241 result.alpha -= min.alpha;
3243 case ThickenMorphology:
3244 /* Add the pattern matchs to the original */
3245 result.red += min.red;
3246 result.green += min.green;
3247 result.blue += min.blue;
3248 result.black += min.black;
3249 result.alpha += min.alpha;
3252 /* result directly calculated or assigned */
3255 /* Assign the resulting pixel values - Clamping Result */
3257 case UndefinedMorphology:
3258 case ConvolveMorphology:
3259 case DilateIntensityMorphology:
3260 case ErodeIntensityMorphology:
3261 break; /* full pixel was directly assigned - not a channel method */
3263 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3264 SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
3265 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3266 SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
3267 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3268 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
3269 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3270 (image->colorspace == CMYKColorspace))
3271 SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
3272 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
3273 (image->matte == MagickTrue))
3274 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
3277 /* Count up changed pixels */
3278 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q)) ||
3279 (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q)) ||
3280 (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q)) ||
3281 (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q)) ||
3282 ((image->colorspace == CMYKColorspace) &&
3283 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
3284 changed++; /* The pixel was changed in some way! */
3285 p+=GetPixelChannels(image);
3286 q+=GetPixelChannels(morphology_image);
3288 if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
3290 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3295 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3296 #pragma omp critical (MagickCore_MorphologyImage)
3298 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
3299 if (proceed == MagickFalse)
3303 morphology_view=DestroyCacheView(morphology_view);
3304 image_view=DestroyCacheView(image_view);
3305 return(status ? (ssize_t)changed : -1);
3308 /* This is almost identical to the MorphologyPrimative() function above,
3309 ** but will apply the primitive directly to the actual image using two
3310 ** passes, once in each direction, with the results of the previous (and
3311 ** current) row being re-used.
3313 ** That is after each row is 'Sync'ed' into the image, the next row will
3314 ** make use of those values as part of the calculation of the next row.
3315 ** It then repeats, but going in the oppisite (bottom-up) direction.
3317 ** Because of this 're-use of results' this function can not make use
3318 ** of multi-threaded, parellel processing.
3320 static ssize_t MorphologyPrimitiveDirect(Image *image,
3321 const MorphologyMethod method,const KernelInfo *kernel,
3322 ExceptionInfo *exception)
3345 assert(image != (Image *) NULL);
3346 assert(image->signature == MagickSignature);
3347 assert(kernel != (KernelInfo *) NULL);
3348 assert(kernel->signature == MagickSignature);
3349 assert(exception != (ExceptionInfo *) NULL);
3350 assert(exception->signature == MagickSignature);
3352 /* Some methods (including convolve) needs use a reflected kernel.
3353 * Adjust 'origin' offsets to loop though kernel as a reflection.
3358 case DistanceMorphology:
3359 case VoronoiMorphology:
3360 /* kernel needs to used with reflection about origin */
3361 offx = (ssize_t) kernel->width-offx-1;
3362 offy = (ssize_t) kernel->height-offy-1;
3365 case ?????Morphology:
3366 /* kernel is used as is, without reflection */
3370 assert("Not a PrimativeDirect Morphology Method" != (char *) NULL);
3374 /* DO NOT THREAD THIS CODE! */
3375 /* two views into same image (virtual, and actual) */
3376 virt_view=AcquireVirtualCacheView(image,exception);
3377 auth_view=AcquireAuthenticCacheView(image,exception);
3378 virt_width=image->columns+kernel->width-1;
3380 for (y=0; y < (ssize_t) image->rows; y++)
3382 register const Quantum
3394 /* NOTE read virtual pixels, and authentic pixels, from the same image!
3395 ** we read using virtual to get virtual pixel handling, but write back
3396 ** into the same image.
3398 ** Only top half of kernel is processed as we do a single pass downward
3399 ** through the image iterating the distance function as we go.
3401 if (status == MagickFalse)
3403 p=GetCacheViewVirtualPixels(virt_view,-offx,y-offy,virt_width,(size_t)
3405 q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3407 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3409 if (status == MagickFalse)
3412 /* offset to origin in 'p'. while 'q' points to it directly */
3413 r = (ssize_t) virt_width*offy + offx;
3415 for (x=0; x < (ssize_t) image->columns; x++)
3423 register const double
3426 register const Quantum
3432 /* Starting Defaults */
3433 GetPixelInfo(image,&result);
3434 GetPixelInfoPixel(image,q,&result);
3435 if ( method != VoronoiMorphology )
3436 result.alpha = QuantumRange - result.alpha;
3439 case DistanceMorphology:
3440 /* Add kernel Value and select the minimum value found. */
3441 k = &kernel->values[ kernel->width*kernel->height-1 ];
3443 for (v=0; v <= (ssize_t) offy; v++) {
3444 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3445 if ( IsNan(*k) ) continue;
3446 Minimize(result.red, (*k)+
3447 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3448 Minimize(result.green, (*k)+
3449 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3450 Minimize(result.blue, (*k)+
3451 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3452 if (image->colorspace == CMYKColorspace)
3453 Minimize(result.black,(*k)+
3454 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3455 Minimize(result.alpha, (*k)+
3456 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3458 k_pixels += virt_width*GetPixelChannels(image);
3460 /* repeat with the just processed pixels of this row */
3461 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3462 k_pixels = q-offx*GetPixelChannels(image);
3463 for (u=0; u < (ssize_t) offx; u++, k--) {
3464 if ( x+u-offx < 0 ) continue; /* off the edge! */
3465 if ( IsNan(*k) ) continue;
3466 Minimize(result.red, (*k)+
3467 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3468 Minimize(result.green, (*k)+
3469 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3470 Minimize(result.blue, (*k)+
3471 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3472 if (image->colorspace == CMYKColorspace)
3473 Minimize(result.black,(*k)+
3474 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3475 Minimize(result.alpha,(*k)+
3476 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3479 case VoronoiMorphology:
3480 /* Apply Distance to 'Matte' channel, while coping the color
3481 ** values of the closest pixel.
3483 ** This is experimental, and realy the 'alpha' component should
3484 ** be completely separate 'masking' channel so that alpha can
3485 ** also be used as part of the results.
3487 k = &kernel->values[ kernel->width*kernel->height-1 ];
3489 for (v=0; v <= (ssize_t) offy; v++) {
3490 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3491 if ( IsNan(*k) ) continue;
3492 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3494 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3499 k_pixels += virt_width*GetPixelChannels(image);
3501 /* repeat with the just processed pixels of this row */
3502 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3503 k_pixels = q-offx*GetPixelChannels(image);
3504 for (u=0; u < (ssize_t) offx; u++, k--) {
3505 if ( x+u-offx < 0 ) continue; /* off the edge! */
3506 if ( IsNan(*k) ) continue;
3507 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3509 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3516 /* result directly calculated or assigned */
3519 /* Assign the resulting pixel values - Clamping Result */
3521 case VoronoiMorphology:
3522 SetPixelInfoPixel(image,&result,q);
3525 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3526 SetPixelRed(image,ClampToQuantum(result.red),q);
3527 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3528 SetPixelGreen(image,ClampToQuantum(result.green),q);
3529 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3530 SetPixelBlue(image,ClampToQuantum(result.blue),q);
3531 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3532 (image->colorspace == CMYKColorspace))
3533 SetPixelBlack(image,ClampToQuantum(result.black),q);
3534 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3535 (image->matte == MagickTrue))
3536 SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3539 /* Count up changed pixels */
3540 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q)) ||
3541 (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q)) ||
3542 (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q)) ||
3543 (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q)) ||
3544 ((image->colorspace == CMYKColorspace) &&
3545 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3546 changed++; /* The pixel was changed in some way! */
3548 p+=GetPixelChannels(image); /* increment pixel buffers */
3549 q+=GetPixelChannels(image);
3552 if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3554 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3555 if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3561 /* Do the reversed pass through the image */
3562 for (y=(ssize_t)image->rows-1; y >= 0; y--)
3564 register const Quantum
3576 if (status == MagickFalse)
3578 /* NOTE read virtual pixels, and authentic pixels, from the same image!
3579 ** we read using virtual to get virtual pixel handling, but write back
3580 ** into the same image.
3582 ** Only the bottom half of the kernel will be processes as we
3585 p=GetCacheViewVirtualPixels(virt_view,-offx,y,virt_width,(size_t)
3586 kernel->y+1,exception);
3587 q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3589 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3591 if (status == MagickFalse)
3594 /* adjust positions to end of row */
3595 p += (image->columns-1)*GetPixelChannels(image);
3596 q += (image->columns-1)*GetPixelChannels(image);
3598 /* offset to origin in 'p'. while 'q' points to it directly */
3601 for (x=(ssize_t)image->columns-1; x >= 0; x--)
3609 register const double
3612 register const Quantum
3618 /* Default - previously modified pixel */
3619 GetPixelInfo(image,&result);
3620 GetPixelInfoPixel(image,q,&result);
3621 if ( method != VoronoiMorphology )
3622 result.alpha = QuantumRange - result.alpha;
3625 case DistanceMorphology:
3626 /* Add kernel Value and select the minimum value found. */
3627 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3629 for (v=offy; v < (ssize_t) kernel->height; v++) {
3630 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3631 if ( IsNan(*k) ) continue;
3632 Minimize(result.red, (*k)+
3633 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3634 Minimize(result.green, (*k)+
3635 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3636 Minimize(result.blue, (*k)+
3637 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3638 if ( image->colorspace == CMYKColorspace)
3639 Minimize(result.black,(*k)+
3640 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3641 Minimize(result.alpha, (*k)+
3642 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3644 k_pixels += virt_width*GetPixelChannels(image);
3646 /* repeat with the just processed pixels of this row */
3647 k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3648 k_pixels = q-offx*GetPixelChannels(image);
3649 for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3650 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3651 if ( IsNan(*k) ) continue;
3652 Minimize(result.red, (*k)+
3653 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3654 Minimize(result.green, (*k)+
3655 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3656 Minimize(result.blue, (*k)+
3657 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3658 if ( image->colorspace == CMYKColorspace)
3659 Minimize(result.black, (*k)+
3660 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3661 Minimize(result.alpha, (*k)+
3662 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3665 case VoronoiMorphology:
3666 /* Apply Distance to 'Matte' channel, coping the closest color.
3668 ** This is experimental, and realy the 'alpha' component should
3669 ** be completely separate 'masking' channel.
3671 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3673 for (v=offy; v < (ssize_t) kernel->height; v++) {
3674 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3675 if ( IsNan(*k) ) continue;
3676 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3678 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3683 k_pixels += virt_width*GetPixelChannels(image);
3685 /* repeat with the just processed pixels of this row */
3686 k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3687 k_pixels = q-offx*GetPixelChannels(image);
3688 for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3689 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3690 if ( IsNan(*k) ) continue;
3691 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3693 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3700 /* result directly calculated or assigned */
3703 /* Assign the resulting pixel values - Clamping Result */
3705 case VoronoiMorphology:
3706 SetPixelInfoPixel(image,&result,q);
3709 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3710 SetPixelRed(image,ClampToQuantum(result.red),q);
3711 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3712 SetPixelGreen(image,ClampToQuantum(result.green),q);
3713 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3714 SetPixelBlue(image,ClampToQuantum(result.blue),q);
3715 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3716 (image->colorspace == CMYKColorspace))
3717 SetPixelBlack(image,ClampToQuantum(result.black),q);
3718 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3719 (image->matte == MagickTrue))
3720 SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3723 /* Count up changed pixels */
3724 if ( (GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q))
3725 || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q))
3726 || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q))
3727 || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q))
3728 || ((image->colorspace == CMYKColorspace) &&
3729 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3730 changed++; /* The pixel was changed in some way! */
3732 p-=GetPixelChannels(image); /* go backward through pixel buffers */
3733 q-=GetPixelChannels(image);
3735 if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3737 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3738 if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3744 auth_view=DestroyCacheView(auth_view);
3745 virt_view=DestroyCacheView(virt_view);
3746 return(status ? (ssize_t) changed : -1);
3749 /* Apply a Morphology by calling one of the above low level primitive
3750 ** application functions. This function handles any iteration loops,
3751 ** composition or re-iteration of results, and compound morphology methods
3752 ** that is based on multiple low-level (staged) morphology methods.
3754 ** Basically this provides the complex glue between the requested morphology
3755 ** method and raw low-level implementation (above).
3757 MagickPrivate Image *MorphologyApply(const Image *image,
3758 const MorphologyMethod method, const ssize_t iterations,
3759 const KernelInfo *kernel, const CompositeOperator compose,const double bias,
3760 ExceptionInfo *exception)
3766 *curr_image, /* Image we are working with or iterating */
3767 *work_image, /* secondary image for primitive iteration */
3768 *save_image, /* saved image - for 'edge' method only */
3769 *rslt_image; /* resultant image - after multi-kernel handling */
3772 *reflected_kernel, /* A reflected copy of the kernel (if needed) */
3773 *norm_kernel, /* the current normal un-reflected kernel */
3774 *rflt_kernel, /* the current reflected kernel (if needed) */
3775 *this_kernel; /* the kernel being applied */
3778 primitive; /* the current morphology primitive being applied */
3781 rslt_compose; /* multi-kernel compose method for results to use */
3784 special, /* do we use a direct modify function? */
3785 verbose; /* verbose output of results */
3788 method_loop, /* Loop 1: number of compound method iterations (norm 1) */
3789 method_limit, /* maximum number of compound method iterations */
3790 kernel_number, /* Loop 2: the kernel number being applied */
3791 stage_loop, /* Loop 3: primitive loop for compound morphology */
3792 stage_limit, /* how many primitives are in this compound */
3793 kernel_loop, /* Loop 4: iterate the kernel over image */
3794 kernel_limit, /* number of times to iterate kernel */
3795 count, /* total count of primitive steps applied */
3796 kernel_changed, /* total count of changed using iterated kernel */
3797 method_changed; /* total count of changed over method iteration */
3800 changed; /* number pixels changed by last primitive operation */
3805 assert(image != (Image *) NULL);
3806 assert(image->signature == MagickSignature);
3807 assert(kernel != (KernelInfo *) NULL);
3808 assert(kernel->signature == MagickSignature);
3809 assert(exception != (ExceptionInfo *) NULL);
3810 assert(exception->signature == MagickSignature);
3812 count = 0; /* number of low-level morphology primitives performed */
3813 if ( iterations == 0 )
3814 return((Image *)NULL); /* null operation - nothing to do! */
3816 kernel_limit = (size_t) iterations;
3817 if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
3818 kernel_limit = image->columns>image->rows ? image->columns : image->rows;
3820 verbose = IsStringTrue(GetImageArtifact(image,"verbose"));
3822 /* initialise for cleanup */
3823 curr_image = (Image *) image;
3824 curr_compose = image->compose;
3825 (void) curr_compose;
3826 work_image = save_image = rslt_image = (Image *) NULL;
3827 reflected_kernel = (KernelInfo *) NULL;
3829 /* Initialize specific methods
3830 * + which loop should use the given iteratations
3831 * + how many primitives make up the compound morphology
3832 * + multi-kernel compose method to use (by default)
3834 method_limit = 1; /* just do method once, unless otherwise set */
3835 stage_limit = 1; /* assume method is not a compound */
3836 special = MagickFalse; /* assume it is NOT a direct modify primitive */
3837 rslt_compose = compose; /* and we are composing multi-kernels as given */
3839 case SmoothMorphology: /* 4 primitive compound morphology */
3842 case OpenMorphology: /* 2 primitive compound morphology */
3843 case OpenIntensityMorphology:
3844 case TopHatMorphology:
3845 case CloseMorphology:
3846 case CloseIntensityMorphology:
3847 case BottomHatMorphology:
3848 case EdgeMorphology:
3851 case HitAndMissMorphology:
3852 rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
3854 case ThinningMorphology:
3855 case ThickenMorphology:
3856 method_limit = kernel_limit; /* iterate the whole method */
3857 kernel_limit = 1; /* do not do kernel iteration */
3859 case DistanceMorphology:
3860 case VoronoiMorphology:
3861 special = MagickTrue; /* use special direct primative */
3867 /* Apply special methods with special requirments
3868 ** For example, single run only, or post-processing requirements
3870 if ( special == MagickTrue )
3872 rslt_image=CloneImage(image,0,0,MagickTrue,exception);
3873 if (rslt_image == (Image *) NULL)
3875 if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse)
3878 changed = MorphologyPrimitiveDirect(rslt_image, method,
3881 if ( IfMagickTrue(verbose) )
3882 (void) (void) FormatLocaleFile(stderr,
3883 "%s:%.20g.%.20g #%.20g => Changed %.20g\n",
3884 CommandOptionToMnemonic(MagickMorphologyOptions, method),
3885 1.0,0.0,1.0, (double) changed);
3890 if ( method == VoronoiMorphology ) {
3891 /* Preserve the alpha channel of input image - but turned off */
3892 (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3894 (void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp,
3895 MagickTrue,0,0,exception);
3896 (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3902 /* Handle user (caller) specified multi-kernel composition method */
3903 if ( compose != UndefinedCompositeOp )
3904 rslt_compose = compose; /* override default composition for method */
3905 if ( rslt_compose == UndefinedCompositeOp )
3906 rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
3908 /* Some methods require a reflected kernel to use with primitives.
3909 * Create the reflected kernel for those methods. */
3911 case CorrelateMorphology:
3912 case CloseMorphology:
3913 case CloseIntensityMorphology:
3914 case BottomHatMorphology:
3915 case SmoothMorphology:
3916 reflected_kernel = CloneKernelInfo(kernel);
3917 if (reflected_kernel == (KernelInfo *) NULL)
3919 RotateKernelInfo(reflected_kernel,180);
3925 /* Loops around more primitive morpholgy methods
3926 ** erose, dilate, open, close, smooth, edge, etc...
3928 /* Loop 1: iterate the compound method */
3931 while ( method_loop < method_limit && method_changed > 0 ) {
3935 /* Loop 2: iterate over each kernel in a multi-kernel list */
3936 norm_kernel = (KernelInfo *) kernel;
3937 this_kernel = (KernelInfo *) kernel;
3938 rflt_kernel = reflected_kernel;
3941 while ( norm_kernel != NULL ) {
3943 /* Loop 3: Compound Morphology Staging - Select Primative to apply */
3944 stage_loop = 0; /* the compound morphology stage number */
3945 while ( stage_loop < stage_limit ) {
3946 stage_loop++; /* The stage of the compound morphology */
3948 /* Select primitive morphology for this stage of compound method */
3949 this_kernel = norm_kernel; /* default use unreflected kernel */
3950 primitive = method; /* Assume method is a primitive */
3952 case ErodeMorphology: /* just erode */
3953 case EdgeInMorphology: /* erode and image difference */
3954 primitive = ErodeMorphology;
3956 case DilateMorphology: /* just dilate */
3957 case EdgeOutMorphology: /* dilate and image difference */
3958 primitive = DilateMorphology;
3960 case OpenMorphology: /* erode then dialate */
3961 case TopHatMorphology: /* open and image difference */
3962 primitive = ErodeMorphology;
3963 if ( stage_loop == 2 )
3964 primitive = DilateMorphology;
3966 case OpenIntensityMorphology:
3967 primitive = ErodeIntensityMorphology;
3968 if ( stage_loop == 2 )
3969 primitive = DilateIntensityMorphology;
3971 case CloseMorphology: /* dilate, then erode */
3972 case BottomHatMorphology: /* close and image difference */
3973 this_kernel = rflt_kernel; /* use the reflected kernel */
3974 primitive = DilateMorphology;
3975 if ( stage_loop == 2 )
3976 primitive = ErodeMorphology;
3978 case CloseIntensityMorphology:
3979 this_kernel = rflt_kernel; /* use the reflected kernel */
3980 primitive = DilateIntensityMorphology;
3981 if ( stage_loop == 2 )
3982 primitive = ErodeIntensityMorphology;
3984 case SmoothMorphology: /* open, close */
3985 switch ( stage_loop ) {
3986 case 1: /* start an open method, which starts with Erode */
3987 primitive = ErodeMorphology;
3989 case 2: /* now Dilate the Erode */
3990 primitive = DilateMorphology;
3992 case 3: /* Reflect kernel a close */
3993 this_kernel = rflt_kernel; /* use the reflected kernel */
3994 primitive = DilateMorphology;
3996 case 4: /* Finish the Close */
3997 this_kernel = rflt_kernel; /* use the reflected kernel */
3998 primitive = ErodeMorphology;
4002 case EdgeMorphology: /* dilate and erode difference */
4003 primitive = DilateMorphology;
4004 if ( stage_loop == 2 ) {
4005 save_image = curr_image; /* save the image difference */
4006 curr_image = (Image *) image;
4007 primitive = ErodeMorphology;
4010 case CorrelateMorphology:
4011 /* A Correlation is a Convolution with a reflected kernel.
4012 ** However a Convolution is a weighted sum using a reflected
4013 ** kernel. It may seem stange to convert a Correlation into a
4014 ** Convolution as the Correlation is the simplier method, but
4015 ** Convolution is much more commonly used, and it makes sense to
4016 ** implement it directly so as to avoid the need to duplicate the
4017 ** kernel when it is not required (which is typically the
4020 this_kernel = rflt_kernel; /* use the reflected kernel */
4021 primitive = ConvolveMorphology;
4026 assert( this_kernel != (KernelInfo *) NULL );
4028 /* Extra information for debugging compound operations */
4029 if ( IfMagickTrue(verbose) ) {
4030 if ( stage_limit > 1 )
4031 (void) FormatLocaleString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ",
4032 CommandOptionToMnemonic(MagickMorphologyOptions,method),(double)
4033 method_loop,(double) stage_loop);
4034 else if ( primitive != method )
4035 (void) FormatLocaleString(v_info, MaxTextExtent, "%s:%.20g -> ",
4036 CommandOptionToMnemonic(MagickMorphologyOptions, method),(double)
4042 /* Loop 4: Iterate the kernel with primitive */
4046 while ( kernel_loop < kernel_limit && changed > 0 ) {
4047 kernel_loop++; /* the iteration of this kernel */
4049 /* Create a clone as the destination image, if not yet defined */
4050 if ( work_image == (Image *) NULL )
4052 work_image=CloneImage(image,0,0,MagickTrue,exception);
4053 if (work_image == (Image *) NULL)
4055 if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse)
4057 /* work_image->type=image->type; ??? */
4060 /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
4062 changed = MorphologyPrimitive(curr_image, work_image, primitive,
4063 this_kernel, bias, exception);
4065 if ( IfMagickTrue(verbose) ) {
4066 if ( kernel_loop > 1 )
4067 (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */
4068 (void) (void) FormatLocaleFile(stderr,
4069 "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
4070 v_info,CommandOptionToMnemonic(MagickMorphologyOptions,
4071 primitive),(this_kernel == rflt_kernel ) ? "*" : "",
4072 (double) (method_loop+kernel_loop-1),(double) kernel_number,
4073 (double) count,(double) changed);
4077 kernel_changed += changed;
4078 method_changed += changed;
4080 /* prepare next loop */
4081 { Image *tmp = work_image; /* swap images for iteration */
4082 work_image = curr_image;
4085 if ( work_image == image )
4086 work_image = (Image *) NULL; /* replace input 'image' */
4088 } /* End Loop 4: Iterate the kernel with primitive */
4090 if ( IfMagickTrue(verbose) && kernel_changed != (size_t)changed )
4091 (void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed);
4092 if ( IfMagickTrue(verbose) && stage_loop < stage_limit )
4093 (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */
4096 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
4097 (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
4098 (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image);
4099 (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image);
4100 (void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
4103 } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
4105 /* Final Post-processing for some Compound Methods
4107 ** The removal of any 'Sync' channel flag in the Image Compositon
4108 ** below ensures the methematical compose method is applied in a
4109 ** purely mathematical way, and only to the selected channels.
4110 ** Turn off SVG composition 'alpha blending'.
4113 case EdgeOutMorphology:
4114 case EdgeInMorphology:
4115 case TopHatMorphology:
4116 case BottomHatMorphology:
4117 if ( IfMagickTrue(verbose) )
4118 (void) FormatLocaleFile(stderr,
4119 "\n%s: Difference with original image",CommandOptionToMnemonic(
4120 MagickMorphologyOptions, method) );
4121 (void) CompositeImage(curr_image,image,DifferenceCompositeOp,
4122 MagickTrue,0,0,exception);
4124 case EdgeMorphology:
4125 if ( IfMagickTrue(verbose) )
4126 (void) FormatLocaleFile(stderr,
4127 "\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic(
4128 MagickMorphologyOptions, method) );
4129 (void) CompositeImage(curr_image,save_image,DifferenceCompositeOp,
4130 MagickTrue,0,0,exception);
4131 save_image = DestroyImage(save_image); /* finished with save image */
4137 /* multi-kernel handling: re-iterate, or compose results */
4138 if ( kernel->next == (KernelInfo *) NULL )
4139 rslt_image = curr_image; /* just return the resulting image */
4140 else if ( rslt_compose == NoCompositeOp )
4141 { if ( IfMagickTrue(verbose) ) {
4142 if ( this_kernel->next != (KernelInfo *) NULL )
4143 (void) FormatLocaleFile(stderr, " (re-iterate)");
4145 (void) FormatLocaleFile(stderr, " (done)");
4147 rslt_image = curr_image; /* return result, and re-iterate */
4149 else if ( rslt_image == (Image *) NULL)
4150 { if ( IfMagickTrue(verbose) )
4151 (void) FormatLocaleFile(stderr, " (save for compose)");
4152 rslt_image = curr_image;
4153 curr_image = (Image *) image; /* continue with original image */
4156 { /* Add the new 'current' result to the composition
4158 ** The removal of any 'Sync' channel flag in the Image Compositon
4159 ** below ensures the methematical compose method is applied in a
4160 ** purely mathematical way, and only to the selected channels.
4161 ** IE: Turn off SVG composition 'alpha blending'.
4163 if ( IfMagickTrue(verbose) )
4164 (void) FormatLocaleFile(stderr, " (compose \"%s\")",
4165 CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) );
4166 (void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue,
4168 curr_image = DestroyImage(curr_image);
4169 curr_image = (Image *) image; /* continue with original image */
4171 if ( IfMagickTrue(verbose) )
4172 (void) FormatLocaleFile(stderr, "\n");
4174 /* loop to the next kernel in a multi-kernel list */
4175 norm_kernel = norm_kernel->next;
4176 if ( rflt_kernel != (KernelInfo *) NULL )
4177 rflt_kernel = rflt_kernel->next;
4179 } /* End Loop 2: Loop over each kernel */
4181 } /* End Loop 1: compound method interation */
4185 /* Yes goto's are bad, but it makes cleanup lot more efficient */
4187 if ( curr_image == rslt_image )
4188 curr_image = (Image *) NULL;
4189 if ( rslt_image != (Image *) NULL )
4190 rslt_image = DestroyImage(rslt_image);
4192 if ( curr_image == rslt_image || curr_image == image )
4193 curr_image = (Image *) NULL;
4194 if ( curr_image != (Image *) NULL )
4195 curr_image = DestroyImage(curr_image);
4196 if ( work_image != (Image *) NULL )
4197 work_image = DestroyImage(work_image);
4198 if ( save_image != (Image *) NULL )
4199 save_image = DestroyImage(save_image);
4200 if ( reflected_kernel != (KernelInfo *) NULL )
4201 reflected_kernel = DestroyKernelInfo(reflected_kernel);
4207 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4211 % M o r p h o l o g y I m a g e %
4215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4217 % MorphologyImage() applies a user supplied kernel to the image
4218 % according to the given mophology method.
4220 % This function applies any and all user defined settings before calling
4221 % the above internal function MorphologyApply().
4223 % User defined settings include...
4224 % * Output Bias for Convolution and correlation ("-define convolve:bias=??")
4225 % * Kernel Scale/normalize settings ("-define convolve:scale=??")
4226 % This can also includes the addition of a scaled unity kernel.
4227 % * Show Kernel being applied ("-define showkernel=1")
4229 % Other operators that do not want user supplied options interfering,
4230 % especially "convolve:bias" and "showkernel" should use MorphologyApply()
4233 % The format of the MorphologyImage method is:
4235 % Image *MorphologyImage(const Image *image,MorphologyMethod method,
4236 % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
4238 % A description of each parameter follows:
4240 % o image: the image.
4242 % o method: the morphology method to be applied.
4244 % o iterations: apply the operation this many times (or no change).
4245 % A value of -1 means loop until no change found.
4246 % How this is applied may depend on the morphology method.
4247 % Typically this is a value of 1.
4249 % o kernel: An array of double representing the morphology kernel.
4250 % Warning: kernel may be normalized for the Convolve method.
4252 % o exception: return any errors or warnings in this structure.
4255 MagickExport Image *MorphologyImage(const Image *image,
4256 const MorphologyMethod method,const ssize_t iterations,
4257 const KernelInfo *kernel,ExceptionInfo *exception)
4271 curr_kernel = (KernelInfo *) kernel;
4273 compose = (ssize_t)UndefinedCompositeOp; /* use default for method */
4275 /* Apply Convolve/Correlate Normalization and Scaling Factors.
4276 * This is done BEFORE the ShowKernelInfo() function is called so that
4277 * users can see the results of the 'option:convolve:scale' option.
4279 if ( method == ConvolveMorphology || method == CorrelateMorphology ) {
4283 /* Get the bias value as it will be needed */
4284 artifact = GetImageArtifact(image,"convolve:bias");
4285 if ( artifact != (const char *) NULL) {
4286 if (IfMagickFalse(IsGeometry(artifact)))
4287 (void) ThrowMagickException(exception,GetMagickModule(),
4288 OptionWarning,"InvalidSetting","'%s' '%s'",
4289 "convolve:bias",artifact);
4291 bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0);
4294 /* Scale kernel according to user wishes */
4295 artifact = GetImageArtifact(image,"convolve:scale");
4296 if ( artifact != (const char *)NULL ) {
4297 if (IfMagickFalse(IsGeometry(artifact)))
4298 (void) ThrowMagickException(exception,GetMagickModule(),
4299 OptionWarning,"InvalidSetting","'%s' '%s'",
4300 "convolve:scale",artifact);
4302 if ( curr_kernel == kernel )
4303 curr_kernel = CloneKernelInfo(kernel);
4304 if (curr_kernel == (KernelInfo *) NULL)
4305 return((Image *) NULL);
4306 ScaleGeometryKernelInfo(curr_kernel, artifact);
4311 /* display the (normalized) kernel via stderr */
4312 if ( IfStringTrue(GetImageArtifact(image,"showkernel"))
4313 || IfStringTrue(GetImageArtifact(image,"convolve:showkernel"))
4314 || IfStringTrue(GetImageArtifact(image,"morphology:showkernel")) )
4315 ShowKernelInfo(curr_kernel);
4317 /* Override the default handling of multi-kernel morphology results
4318 * If 'Undefined' use the default method
4319 * If 'None' (default for 'Convolve') re-iterate previous result
4320 * Otherwise merge resulting images using compose method given.
4321 * Default for 'HitAndMiss' is 'Lighten'.
4328 artifact = GetImageArtifact(image,"morphology:compose");
4329 if ( artifact != (const char *) NULL) {
4330 parse=ParseCommandOption(MagickComposeOptions,
4331 MagickFalse,artifact);
4333 (void) ThrowMagickException(exception,GetMagickModule(),
4334 OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'",
4335 "morphology:compose",artifact);
4337 compose=(CompositeOperator)parse;
4340 /* Apply the Morphology */
4341 morphology_image = MorphologyApply(image,method,iterations,
4342 curr_kernel,compose,bias,exception);
4344 /* Cleanup and Exit */
4345 if ( curr_kernel != kernel )
4346 curr_kernel=DestroyKernelInfo(curr_kernel);
4347 return(morphology_image);
4351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4355 + R o t a t e K e r n e l I n f o %
4359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4361 % RotateKernelInfo() rotates the kernel by the angle given.
4363 % Currently it is restricted to 90 degree angles, of either 1D kernels
4364 % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
4365 % It will ignore usless rotations for specific 'named' built-in kernels.
4367 % The format of the RotateKernelInfo method is:
4369 % void RotateKernelInfo(KernelInfo *kernel, double angle)
4371 % A description of each parameter follows:
4373 % o kernel: the Morphology/Convolution kernel
4375 % o angle: angle to rotate in degrees
4377 % This function is currently internal to this module only, but can be exported
4378 % to other modules if needed.
4380 static void RotateKernelInfo(KernelInfo *kernel, double angle)
4382 /* angle the lower kernels first */
4383 if ( kernel->next != (KernelInfo *) NULL)
4384 RotateKernelInfo(kernel->next, angle);
4386 /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
4388 ** TODO: expand beyond simple 90 degree rotates, flips and flops
4391 /* Modulus the angle */
4392 angle = fmod(angle, 360.0);
4396 if ( 337.5 < angle || angle <= 22.5 )
4397 return; /* Near zero angle - no change! - At least not at this time */
4399 /* Handle special cases */
4400 switch (kernel->type) {
4401 /* These built-in kernels are cylindrical kernels, rotating is useless */
4402 case GaussianKernel:
4407 case LaplacianKernel:
4408 case ChebyshevKernel:
4409 case ManhattanKernel:
4410 case EuclideanKernel:
4413 /* These may be rotatable at non-90 angles in the future */
4414 /* but simply rotating them in multiples of 90 degrees is useless */
4421 /* These only allows a +/-90 degree rotation (by transpose) */
4422 /* A 180 degree rotation is useless */
4424 if ( 135.0 < angle && angle <= 225.0 )
4426 if ( 225.0 < angle && angle <= 315.0 )
4433 /* Attempt rotations by 45 degrees -- 3x3 kernels only */
4434 if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
4436 if ( kernel->width == 3 && kernel->height == 3 )
4437 { /* Rotate a 3x3 square by 45 degree angle */
4438 MagickRealType t = kernel->values[0];
4439 kernel->values[0] = kernel->values[3];
4440 kernel->values[3] = kernel->values[6];
4441 kernel->values[6] = kernel->values[7];
4442 kernel->values[7] = kernel->values[8];
4443 kernel->values[8] = kernel->values[5];
4444 kernel->values[5] = kernel->values[2];
4445 kernel->values[2] = kernel->values[1];
4446 kernel->values[1] = t;
4447 /* rotate non-centered origin */
4448 if ( kernel->x != 1 || kernel->y != 1 ) {
4450 x = (ssize_t) kernel->x-1;
4451 y = (ssize_t) kernel->y-1;
4452 if ( x == y ) x = 0;
4453 else if ( x == 0 ) x = -y;
4454 else if ( x == -y ) y = 0;
4455 else if ( y == 0 ) y = x;
4456 kernel->x = (ssize_t) x+1;
4457 kernel->y = (ssize_t) y+1;
4459 angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */
4460 kernel->angle = fmod(kernel->angle+45.0, 360.0);
4463 perror("Unable to rotate non-3x3 kernel by 45 degrees");
4465 if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 )
4467 if ( kernel->width == 1 || kernel->height == 1 )
4468 { /* Do a transpose of a 1 dimensional kernel,
4469 ** which results in a fast 90 degree rotation of some type.
4473 t = (ssize_t) kernel->width;
4474 kernel->width = kernel->height;
4475 kernel->height = (size_t) t;
4477 kernel->x = kernel->y;
4479 if ( kernel->width == 1 ) {
4480 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
4481 kernel->angle = fmod(kernel->angle+90.0, 360.0);
4483 angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */
4484 kernel->angle = fmod(kernel->angle+270.0, 360.0);
4487 else if ( kernel->width == kernel->height )
4488 { /* Rotate a square array of values by 90 degrees */
4494 for( i=0, x=kernel->width-1; i<=x; i++, x--)
4495 for( j=0, y=kernel->height-1; j<y; j++, y--)
4496 { t = k[i+j*kernel->width];
4497 k[i+j*kernel->width] = k[j+x*kernel->width];
4498 k[j+x*kernel->width] = k[x+y*kernel->width];
4499 k[x+y*kernel->width] = k[y+i*kernel->width];
4500 k[y+i*kernel->width] = t;
4503 /* rotate the origin - relative to center of array */
4504 { register ssize_t x,y;
4505 x = (ssize_t) (kernel->x*2-kernel->width+1);
4506 y = (ssize_t) (kernel->y*2-kernel->height+1);
4507 kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2;
4508 kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2;
4510 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
4511 kernel->angle = fmod(kernel->angle+90.0, 360.0);
4514 perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
4516 if ( 135.0 < angle && angle <= 225.0 )
4518 /* For a 180 degree rotation - also know as a reflection
4519 * This is actually a very very common operation!
4520 * Basically all that is needed is a reversal of the kernel data!
4521 * And a reflection of the origon
4534 j=(ssize_t) (kernel->width*kernel->height-1);
4535 for (i=0; i < j; i++, j--)
4536 t=k[i], k[i]=k[j], k[j]=t;
4538 kernel->x = (ssize_t) kernel->width - kernel->x - 1;
4539 kernel->y = (ssize_t) kernel->height - kernel->y - 1;
4540 angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */
4541 kernel->angle = fmod(kernel->angle+180.0, 360.0);
4543 /* At this point angle should at least between -45 (315) and +45 degrees
4544 * In the future some form of non-orthogonal angled rotates could be
4545 * performed here, posibily with a linear kernel restriction.
4552 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4556 % S c a l e G e o m e t r y K e r n e l I n f o %
4560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4562 % ScaleGeometryKernelInfo() takes a geometry argument string, typically
4563 % provided as a "-set option:convolve:scale {geometry}" user setting,
4564 % and modifies the kernel according to the parsed arguments of that setting.
4566 % The first argument (and any normalization flags) are passed to
4567 % ScaleKernelInfo() to scale/normalize the kernel. The second argument
4568 % is then passed to UnityAddKernelInfo() to add a scled unity kernel
4569 % into the scaled/normalized kernel.
4571 % The format of the ScaleGeometryKernelInfo method is:
4573 % void ScaleGeometryKernelInfo(KernelInfo *kernel,
4574 % const double scaling_factor,const MagickStatusType normalize_flags)
4576 % A description of each parameter follows:
4578 % o kernel: the Morphology/Convolution kernel to modify
4581 % The geometry string to parse, typically from the user provided
4582 % "-set option:convolve:scale {geometry}" setting.
4585 MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
4586 const char *geometry)
4595 SetGeometryInfo(&args);
4596 flags = ParseGeometry(geometry, &args);
4599 /* For Debugging Geometry Input */
4600 (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
4601 flags, args.rho, args.sigma, args.xi, args.psi );
4604 if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/
4605 args.rho *= 0.01, args.sigma *= 0.01;
4607 if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */
4609 if ( (flags & SigmaValue) == 0 )
4612 /* Scale/Normalize the input kernel */
4613 ScaleKernelInfo(kernel, args.rho, flags);
4615 /* Add Unity Kernel, for blending with original */
4616 if ( (flags & SigmaValue) != 0 )
4617 UnityAddKernelInfo(kernel, args.sigma);
4622 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4626 % S c a l e K e r n e l I n f o %
4630 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4632 % ScaleKernelInfo() scales the given kernel list by the given amount, with or
4633 % without normalization of the sum of the kernel values (as per given flags).
4635 % By default (no flags given) the values within the kernel is scaled
4636 % directly using given scaling factor without change.
4638 % If either of the two 'normalize_flags' are given the kernel will first be
4639 % normalized and then further scaled by the scaling factor value given.
4641 % Kernel normalization ('normalize_flags' given) is designed to ensure that
4642 % any use of the kernel scaling factor with 'Convolve' or 'Correlate'
4643 % morphology methods will fall into -1.0 to +1.0 range. Note that for
4644 % non-HDRI versions of IM this may cause images to have any negative results
4645 % clipped, unless some 'bias' is used.
4647 % More specifically. Kernels which only contain positive values (such as a
4648 % 'Gaussian' kernel) will be scaled so that those values sum to +1.0,
4649 % ensuring a 0.0 to +1.0 output range for non-HDRI images.
4651 % For Kernels that contain some negative values, (such as 'Sharpen' kernels)
4652 % the kernel will be scaled by the absolute of the sum of kernel values, so
4653 % that it will generally fall within the +/- 1.0 range.
4655 % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
4656 % will be scaled by just the sum of the postive values, so that its output
4657 % range will again fall into the +/- 1.0 range.
4659 % For special kernels designed for locating shapes using 'Correlate', (often
4660 % only containing +1 and -1 values, representing foreground/brackground
4661 % matching) a special normalization method is provided to scale the positive
4662 % values separately to those of the negative values, so the kernel will be
4663 % forced to become a zero-sum kernel better suited to such searches.
4665 % WARNING: Correct normalization of the kernel assumes that the '*_range'
4666 % attributes within the kernel structure have been correctly set during the
4669 % NOTE: The values used for 'normalize_flags' have been selected specifically
4670 % to match the use of geometry options, so that '!' means NormalizeValue, '^'
4671 % means CorrelateNormalizeValue. All other GeometryFlags values are ignored.
4673 % The format of the ScaleKernelInfo method is:
4675 % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
4676 % const MagickStatusType normalize_flags )
4678 % A description of each parameter follows:
4680 % o kernel: the Morphology/Convolution kernel
4683 % multiply all values (after normalization) by this factor if not
4684 % zero. If the kernel is normalized regardless of any flags.
4686 % o normalize_flags:
4687 % GeometryFlags defining normalization method to use.
4688 % specifically: NormalizeValue, CorrelateNormalizeValue,
4689 % and/or PercentValue
4692 MagickExport void ScaleKernelInfo(KernelInfo *kernel,
4693 const double scaling_factor,const GeometryFlags normalize_flags)
4702 /* do the other kernels in a multi-kernel list first */
4703 if ( kernel->next != (KernelInfo *) NULL)
4704 ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
4706 /* Normalization of Kernel */
4708 if ( (normalize_flags&NormalizeValue) != 0 ) {
4709 if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon )
4710 /* non-zero-summing kernel (generally positive) */
4711 pos_scale = fabs(kernel->positive_range + kernel->negative_range);
4713 /* zero-summing kernel */
4714 pos_scale = kernel->positive_range;
4716 /* Force kernel into a normalized zero-summing kernel */
4717 if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
4718 pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon )
4719 ? kernel->positive_range : 1.0;
4720 neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon )
4721 ? -kernel->negative_range : 1.0;
4724 neg_scale = pos_scale;
4726 /* finialize scaling_factor for positive and negative components */
4727 pos_scale = scaling_factor/pos_scale;
4728 neg_scale = scaling_factor/neg_scale;
4730 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
4731 if ( ! IsNan(kernel->values[i]) )
4732 kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
4734 /* convolution output range */
4735 kernel->positive_range *= pos_scale;
4736 kernel->negative_range *= neg_scale;
4737 /* maximum and minimum values in kernel */
4738 kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
4739 kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
4741 /* swap kernel settings if user's scaling factor is negative */
4742 if ( scaling_factor < MagickEpsilon ) {
4744 t = kernel->positive_range;
4745 kernel->positive_range = kernel->negative_range;
4746 kernel->negative_range = t;
4747 t = kernel->maximum;
4748 kernel->maximum = kernel->minimum;
4749 kernel->minimum = 1;
4756 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4760 % S h o w K e r n e l I n f o %
4764 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4766 % ShowKernelInfo() outputs the details of the given kernel defination to
4767 % standard error, generally due to a users 'showkernel' option request.
4769 % The format of the ShowKernel method is:
4771 % void ShowKernelInfo(const KernelInfo *kernel)
4773 % A description of each parameter follows:
4775 % o kernel: the Morphology/Convolution kernel
4778 MagickPrivate void ShowKernelInfo(const KernelInfo *kernel)
4786 for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) {
4788 (void) FormatLocaleFile(stderr, "Kernel");
4789 if ( kernel->next != (KernelInfo *) NULL )
4790 (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c );
4791 (void) FormatLocaleFile(stderr, " \"%s",
4792 CommandOptionToMnemonic(MagickKernelOptions, k->type) );
4793 if ( fabs(k->angle) > MagickEpsilon )
4794 (void) FormatLocaleFile(stderr, "@%lg", k->angle);
4795 (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long)
4796 k->width,(unsigned long) k->height,(long) k->x,(long) k->y);
4797 (void) FormatLocaleFile(stderr,
4798 " with values from %.*lg to %.*lg\n",
4799 GetMagickPrecision(), k->minimum,
4800 GetMagickPrecision(), k->maximum);
4801 (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg",
4802 GetMagickPrecision(), k->negative_range,
4803 GetMagickPrecision(), k->positive_range);
4804 if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
4805 (void) FormatLocaleFile(stderr, " (Zero-Summing)\n");
4806 else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
4807 (void) FormatLocaleFile(stderr, " (Normalized)\n");
4809 (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n",
4810 GetMagickPrecision(), k->positive_range+k->negative_range);
4811 for (i=v=0; v < k->height; v++) {
4812 (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v );
4813 for (u=0; u < k->width; u++, i++)
4814 if ( IsNan(k->values[i]) )
4815 (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan");
4817 (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3,
4818 GetMagickPrecision(), k->values[i]);
4819 (void) FormatLocaleFile(stderr,"\n");
4825 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4829 % U n i t y A d d K e r n a l I n f o %
4833 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4835 % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
4836 % to the given pre-scaled and normalized Kernel. This in effect adds that
4837 % amount of the original image into the resulting convolution kernel. This
4838 % value is usually provided by the user as a percentage value in the
4839 % 'convolve:scale' setting.
4841 % The resulting effect is to convert the defined kernels into blended
4842 % soft-blurs, unsharp kernels or into sharpening kernels.
4844 % The format of the UnityAdditionKernelInfo method is:
4846 % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
4848 % A description of each parameter follows:
4850 % o kernel: the Morphology/Convolution kernel
4853 % scaling factor for the unity kernel to be added to
4857 MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
4860 /* do the other kernels in a multi-kernel list first */
4861 if ( kernel->next != (KernelInfo *) NULL)
4862 UnityAddKernelInfo(kernel->next, scale);
4864 /* Add the scaled unity kernel to the existing kernel */
4865 kernel->values[kernel->x+kernel->y*kernel->width] += scale;
4866 CalcKernelMetaData(kernel); /* recalculate the meta-data */
4872 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4876 % Z e r o K e r n e l N a n s %
4880 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4882 % ZeroKernelNans() replaces any special 'nan' value that may be present in
4883 % the kernel with a zero value. This is typically done when the kernel will
4884 % be used in special hardware (GPU) convolution processors, to simply
4887 % The format of the ZeroKernelNans method is:
4889 % void ZeroKernelNans (KernelInfo *kernel)
4891 % A description of each parameter follows:
4893 % o kernel: the Morphology/Convolution kernel
4896 MagickPrivate void ZeroKernelNans(KernelInfo *kernel)
4901 /* do the other kernels in a multi-kernel list first */
4902 if ( kernel->next != (KernelInfo *) NULL)
4903 ZeroKernelNans(kernel->next);
4905 for (i=0; i < (kernel->width*kernel->height); i++)
4906 if ( IsNan(kernel->values[i]) )
4907 kernel->values[i] = 0.0;