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 */
1189 /* Calculate a Positive Gaussian */
1190 if ( sigma > MagickEpsilon )
1191 { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1192 beta = 1.0/(MagickSQ2PI*sigma);
1193 for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1194 kernel->values[i] = exp(-((double)(u*u))*alpha)*beta;
1196 else /* special case - generate a unity kernel */
1197 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1198 kernel->width*kernel->height*sizeof(double));
1199 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1202 /* Note the above kernel may have been 'clipped' by a user defined
1203 ** radius, producing a smaller (darker) kernel. Also for very small
1204 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1205 ** producing a very bright kernel.
1207 ** Normalization will still be needed.
1210 /* Normalize the 1D Gaussian Kernel
1212 ** NB: a CorrelateNormalize performs a normal Normalize if
1213 ** there are no negative values.
1215 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1216 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1218 /* rotate the 1D kernel by given angle */
1219 RotateKernelInfo(kernel, args->xi );
1224 sigma = fabs(args->sigma),
1227 if ( args->rho < 1.0 )
1228 kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
1230 kernel->width = (size_t)args->rho;
1231 kernel->x = kernel->y = 0;
1233 kernel->negative_range = kernel->positive_range = 0.0;
1234 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1235 kernel->height*sizeof(*kernel->values));
1236 if (kernel->values == (double *) NULL)
1237 return(DestroyKernelInfo(kernel));
1239 /* A comet blur is half a 1D gaussian curve, so that the object is
1240 ** blurred in one direction only. This may not be quite the right
1241 ** curve to use so may change in the future. The function must be
1242 ** normalised after generation, which also resolves any clipping.
1244 ** As we are normalizing and not subtracting gaussians,
1245 ** there is no need for a divisor in the gaussian formula
1247 ** It is less comples
1249 if ( sigma > MagickEpsilon )
1252 #define KernelRank 3
1253 v = (ssize_t) kernel->width*KernelRank; /* start/end points */
1254 (void) ResetMagickMemory(kernel->values,0, (size_t)
1255 kernel->width*sizeof(double));
1256 sigma *= KernelRank; /* simplify the loop expression */
1257 A = 1.0/(2.0*sigma*sigma);
1258 /* B = 1.0/(MagickSQ2PI*sigma); */
1259 for ( u=0; u < v; u++) {
1260 kernel->values[u/KernelRank] +=
1261 exp(-((double)(u*u))*A);
1262 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1264 for (i=0; i < (ssize_t) kernel->width; i++)
1265 kernel->positive_range += kernel->values[i];
1267 A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
1268 /* B = 1.0/(MagickSQ2PI*sigma); */
1269 for ( i=0; i < (ssize_t) kernel->width; i++)
1270 kernel->positive_range +=
1272 exp(-((double)(i*i))*A);
1273 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1276 else /* special case - generate a unity kernel */
1277 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1278 kernel->width*kernel->height*sizeof(double));
1279 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1280 kernel->positive_range = 1.0;
1283 kernel->minimum = 0.0;
1284 kernel->maximum = kernel->values[0];
1285 kernel->negative_range = 0.0;
1287 ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1288 RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
1293 Convolution Kernels - Well Known Named Constant Kernels
1295 case LaplacianKernel:
1296 { switch ( (int) args->rho ) {
1298 default: /* laplacian square filter -- default */
1299 kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
1301 case 1: /* laplacian diamond filter */
1302 kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
1305 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1308 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
1310 case 5: /* a 5x5 laplacian */
1311 kernel=ParseKernelArray(
1312 "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");
1314 case 7: /* a 7x7 laplacian */
1315 kernel=ParseKernelArray(
1316 "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" );
1318 case 15: /* a 5x5 LoG (sigma approx 1.4) */
1319 kernel=ParseKernelArray(
1320 "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");
1322 case 19: /* a 9x9 LoG (sigma approx 1.4) */
1323 /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1324 kernel=ParseKernelArray(
1325 "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");
1328 if (kernel == (KernelInfo *) NULL)
1330 kernel->type = type;
1334 { /* Simple Sobel Kernel */
1335 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1336 if (kernel == (KernelInfo *) NULL)
1338 kernel->type = type;
1339 RotateKernelInfo(kernel, args->rho);
1344 kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0");
1345 if (kernel == (KernelInfo *) NULL)
1347 kernel->type = type;
1348 RotateKernelInfo(kernel, args->rho);
1353 kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1");
1354 if (kernel == (KernelInfo *) NULL)
1356 kernel->type = type;
1357 RotateKernelInfo(kernel, args->rho);
1362 kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1");
1363 if (kernel == (KernelInfo *) NULL)
1365 kernel->type = type;
1366 RotateKernelInfo(kernel, args->rho);
1371 kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3");
1372 if (kernel == (KernelInfo *) NULL)
1374 kernel->type = type;
1375 RotateKernelInfo(kernel, args->rho);
1378 case FreiChenKernel:
1379 /* Direction is set to be left to right positive */
1380 /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
1381 /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
1382 { switch ( (int) args->rho ) {
1385 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1386 if (kernel == (KernelInfo *) NULL)
1388 kernel->type = type;
1389 kernel->values[3]+=(MagickRealType) MagickSQ2;
1390 kernel->values[5]-=(MagickRealType) MagickSQ2;
1391 CalcKernelMetaData(kernel); /* recalculate meta-data */
1394 kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1");
1395 if (kernel == (KernelInfo *) NULL)
1397 kernel->type = type;
1398 kernel->values[1] = kernel->values[3]+=(MagickRealType) MagickSQ2;
1399 kernel->values[5] = kernel->values[7]-=(MagickRealType) MagickSQ2;
1400 CalcKernelMetaData(kernel); /* recalculate meta-data */
1401 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1404 kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19");
1405 if (kernel == (KernelInfo *) NULL)
1410 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1411 if (kernel == (KernelInfo *) NULL)
1413 kernel->type = type;
1414 kernel->values[3]+=(MagickRealType) MagickSQ2;
1415 kernel->values[5]-=(MagickRealType) MagickSQ2;
1416 CalcKernelMetaData(kernel); /* recalculate meta-data */
1417 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1420 kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1");
1421 if (kernel == (KernelInfo *) NULL)
1423 kernel->type = type;
1424 kernel->values[1]+=(MagickRealType) MagickSQ2;
1425 kernel->values[7]+=(MagickRealType) MagickSQ2;
1426 CalcKernelMetaData(kernel);
1427 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1430 kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
1431 if (kernel == (KernelInfo *) NULL)
1433 kernel->type = type;
1434 kernel->values[0]+=(MagickRealType) MagickSQ2;
1435 kernel->values[8]-=(MagickRealType) MagickSQ2;
1436 CalcKernelMetaData(kernel);
1437 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1440 kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0");
1441 if (kernel == (KernelInfo *) NULL)
1443 kernel->type = type;
1444 kernel->values[2]-=(MagickRealType) MagickSQ2;
1445 kernel->values[6]+=(MagickRealType) MagickSQ2;
1446 CalcKernelMetaData(kernel);
1447 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1450 kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0");
1451 if (kernel == (KernelInfo *) NULL)
1453 kernel->type = type;
1454 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1457 kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1");
1458 if (kernel == (KernelInfo *) NULL)
1460 kernel->type = type;
1461 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1464 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1");
1465 if (kernel == (KernelInfo *) NULL)
1467 kernel->type = type;
1468 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1471 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1472 if (kernel == (KernelInfo *) NULL)
1474 kernel->type = type;
1475 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1478 kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
1479 if (kernel == (KernelInfo *) NULL)
1481 kernel->type = type;
1482 ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1485 if ( fabs(args->sigma) > MagickEpsilon )
1486 /* Rotate by correctly supplied 'angle' */
1487 RotateKernelInfo(kernel, args->sigma);
1488 else if ( args->rho > 30.0 || args->rho < -30.0 )
1489 /* Rotate by out of bounds 'type' */
1490 RotateKernelInfo(kernel, args->rho);
1495 Boolean or Shaped Kernels
1499 if (args->rho < 1.0)
1500 kernel->width = kernel->height = 3; /* default radius = 1 */
1502 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1503 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1505 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1506 kernel->height*sizeof(*kernel->values));
1507 if (kernel->values == (double *) NULL)
1508 return(DestroyKernelInfo(kernel));
1510 /* set all kernel values within diamond area to scale given */
1511 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1512 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1513 if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
1514 kernel->positive_range += kernel->values[i] = args->sigma;
1516 kernel->values[i] = nan;
1517 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1521 case RectangleKernel:
1524 if ( type == SquareKernel )
1526 if (args->rho < 1.0)
1527 kernel->width = kernel->height = 3; /* default radius = 1 */
1529 kernel->width = kernel->height = (size_t) (2*args->rho+1);
1530 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1531 scale = args->sigma;
1534 /* NOTE: user defaults set in "AcquireKernelInfo()" */
1535 if ( args->rho < 1.0 || args->sigma < 1.0 )
1536 return(DestroyKernelInfo(kernel)); /* invalid args given */
1537 kernel->width = (size_t)args->rho;
1538 kernel->height = (size_t)args->sigma;
1539 if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
1540 args->psi < 0.0 || args->psi > (double)kernel->height )
1541 return(DestroyKernelInfo(kernel)); /* invalid args given */
1542 kernel->x = (ssize_t) args->xi;
1543 kernel->y = (ssize_t) args->psi;
1546 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1547 kernel->height*sizeof(*kernel->values));
1548 if (kernel->values == (double *) NULL)
1549 return(DestroyKernelInfo(kernel));
1551 /* set all kernel values to scale given */
1552 u=(ssize_t) (kernel->width*kernel->height);
1553 for ( i=0; i < u; i++)
1554 kernel->values[i] = scale;
1555 kernel->minimum = kernel->maximum = scale; /* a flat shape */
1556 kernel->positive_range = scale*u;
1561 if (args->rho < 1.0)
1562 kernel->width = kernel->height = 5; /* default radius = 2 */
1564 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1565 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1567 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1568 kernel->height*sizeof(*kernel->values));
1569 if (kernel->values == (double *) NULL)
1570 return(DestroyKernelInfo(kernel));
1572 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1573 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1574 if ( (labs((long) u)+labs((long) v)) <=
1575 ((long)kernel->x + (long)(kernel->x/2)) )
1576 kernel->positive_range += kernel->values[i] = args->sigma;
1578 kernel->values[i] = nan;
1579 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1585 limit = (ssize_t)(args->rho*args->rho);
1587 if (args->rho < 0.4) /* default radius approx 4.3 */
1588 kernel->width = kernel->height = 9L, limit = 18L;
1590 kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1;
1591 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1593 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1594 kernel->height*sizeof(*kernel->values));
1595 if (kernel->values == (double *) NULL)
1596 return(DestroyKernelInfo(kernel));
1598 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1599 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1600 if ((u*u+v*v) <= limit)
1601 kernel->positive_range += kernel->values[i] = args->sigma;
1603 kernel->values[i] = nan;
1604 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1609 if (args->rho < 1.0)
1610 kernel->width = kernel->height = 5; /* default radius 2 */
1612 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1613 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1615 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1616 kernel->height*sizeof(*kernel->values));
1617 if (kernel->values == (double *) NULL)
1618 return(DestroyKernelInfo(kernel));
1620 /* set all kernel values along axises to given scale */
1621 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1622 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1623 kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1624 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1625 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1630 if (args->rho < 1.0)
1631 kernel->width = kernel->height = 5; /* default radius 2 */
1633 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1634 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1636 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1637 kernel->height*sizeof(*kernel->values));
1638 if (kernel->values == (double *) NULL)
1639 return(DestroyKernelInfo(kernel));
1641 /* set all kernel values along axises to given scale */
1642 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1643 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1644 kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1645 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1646 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1660 if (args->rho < args->sigma)
1662 kernel->width = ((size_t)args->sigma)*2+1;
1663 limit1 = (ssize_t)(args->rho*args->rho);
1664 limit2 = (ssize_t)(args->sigma*args->sigma);
1668 kernel->width = ((size_t)args->rho)*2+1;
1669 limit1 = (ssize_t)(args->sigma*args->sigma);
1670 limit2 = (ssize_t)(args->rho*args->rho);
1673 kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1675 kernel->height = kernel->width;
1676 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1677 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
1678 kernel->height*sizeof(*kernel->values));
1679 if (kernel->values == (double *) NULL)
1680 return(DestroyKernelInfo(kernel));
1682 /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
1683 scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
1684 for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
1685 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1686 { ssize_t radius=u*u+v*v;
1687 if (limit1 < radius && radius <= limit2)
1688 kernel->positive_range += kernel->values[i] = (double) scale;
1690 kernel->values[i] = nan;
1692 kernel->minimum = kernel->maximum = (double) scale;
1693 if ( type == PeaksKernel ) {
1694 /* set the central point in the middle */
1695 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1696 kernel->positive_range = 1.0;
1697 kernel->maximum = 1.0;
1703 kernel=AcquireKernelInfo("ThinSE:482");
1704 if (kernel == (KernelInfo *) NULL)
1706 kernel->type = type;
1707 ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */
1712 kernel=AcquireKernelInfo("ThinSE:87");
1713 if (kernel == (KernelInfo *) NULL)
1715 kernel->type = type;
1716 ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
1719 case DiagonalsKernel:
1721 switch ( (int) args->rho ) {
1726 kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
1727 if (kernel == (KernelInfo *) NULL)
1729 kernel->type = type;
1730 new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
1731 if (new_kernel == (KernelInfo *) NULL)
1732 return(DestroyKernelInfo(kernel));
1733 new_kernel->type = type;
1734 LastKernelInfo(kernel)->next = new_kernel;
1735 ExpandMirrorKernelInfo(kernel);
1739 kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
1742 kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
1745 if (kernel == (KernelInfo *) NULL)
1747 kernel->type = type;
1748 RotateKernelInfo(kernel, args->sigma);
1751 case LineEndsKernel:
1752 { /* Kernels for finding the end of thin lines */
1753 switch ( (int) args->rho ) {
1756 /* set of kernels to find all end of lines */
1757 return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>"));
1759 /* kernel for 4-connected line ends - no rotation */
1760 kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-");
1763 /* kernel to add for 8-connected lines - no rotation */
1764 kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
1767 /* kernel to add for orthogonal line ends - does not find corners */
1768 kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0");
1771 /* traditional line end - fails on last T end */
1772 kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-");
1775 if (kernel == (KernelInfo *) NULL)
1777 kernel->type = type;
1778 RotateKernelInfo(kernel, args->sigma);
1781 case LineJunctionsKernel:
1782 { /* kernels for finding the junctions of multiple lines */
1783 switch ( (int) args->rho ) {
1786 /* set of kernels to find all line junctions */
1787 return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>"));
1790 kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-");
1793 /* Diagonal T Junctions */
1794 kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
1797 /* Orthogonal T Junctions */
1798 kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-");
1801 /* Diagonal X Junctions */
1802 kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1");
1805 /* Orthogonal X Junctions - minimal diamond kernel */
1806 kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-");
1809 if (kernel == (KernelInfo *) NULL)
1811 kernel->type = type;
1812 RotateKernelInfo(kernel, args->sigma);
1816 { /* Ridges - Ridge finding kernels */
1819 switch ( (int) args->rho ) {
1822 kernel=ParseKernelArray("3x1:0,1,0");
1823 if (kernel == (KernelInfo *) NULL)
1825 kernel->type = type;
1826 ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
1829 kernel=ParseKernelArray("4x1:0,1,1,0");
1830 if (kernel == (KernelInfo *) NULL)
1832 kernel->type = type;
1833 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
1835 /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */
1836 /* Unfortunatally we can not yet rotate a non-square kernel */
1837 /* But then we can't flip a non-symetrical kernel either */
1838 new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1839 if (new_kernel == (KernelInfo *) NULL)
1840 return(DestroyKernelInfo(kernel));
1841 new_kernel->type = type;
1842 LastKernelInfo(kernel)->next = new_kernel;
1843 new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
1844 if (new_kernel == (KernelInfo *) NULL)
1845 return(DestroyKernelInfo(kernel));
1846 new_kernel->type = type;
1847 LastKernelInfo(kernel)->next = new_kernel;
1848 new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
1849 if (new_kernel == (KernelInfo *) NULL)
1850 return(DestroyKernelInfo(kernel));
1851 new_kernel->type = type;
1852 LastKernelInfo(kernel)->next = new_kernel;
1853 new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
1854 if (new_kernel == (KernelInfo *) NULL)
1855 return(DestroyKernelInfo(kernel));
1856 new_kernel->type = type;
1857 LastKernelInfo(kernel)->next = new_kernel;
1858 new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
1859 if (new_kernel == (KernelInfo *) NULL)
1860 return(DestroyKernelInfo(kernel));
1861 new_kernel->type = type;
1862 LastKernelInfo(kernel)->next = new_kernel;
1863 new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
1864 if (new_kernel == (KernelInfo *) NULL)
1865 return(DestroyKernelInfo(kernel));
1866 new_kernel->type = type;
1867 LastKernelInfo(kernel)->next = new_kernel;
1868 new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
1869 if (new_kernel == (KernelInfo *) NULL)
1870 return(DestroyKernelInfo(kernel));
1871 new_kernel->type = type;
1872 LastKernelInfo(kernel)->next = new_kernel;
1873 new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
1874 if (new_kernel == (KernelInfo *) NULL)
1875 return(DestroyKernelInfo(kernel));
1876 new_kernel->type = type;
1877 LastKernelInfo(kernel)->next = new_kernel;
1882 case ConvexHullKernel:
1886 /* first set of 8 kernels */
1887 kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
1888 if (kernel == (KernelInfo *) NULL)
1890 kernel->type = type;
1891 ExpandRotateKernelInfo(kernel, 90.0);
1892 /* append the mirror versions too - no flip function yet */
1893 new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0");
1894 if (new_kernel == (KernelInfo *) NULL)
1895 return(DestroyKernelInfo(kernel));
1896 new_kernel->type = type;
1897 ExpandRotateKernelInfo(new_kernel, 90.0);
1898 LastKernelInfo(kernel)->next = new_kernel;
1901 case SkeletonKernel:
1903 switch ( (int) args->rho ) {
1906 /* Traditional Skeleton...
1907 ** A cyclically rotated single kernel
1909 kernel=AcquireKernelInfo("ThinSE:482");
1910 if (kernel == (KernelInfo *) NULL)
1912 kernel->type = type;
1913 ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */
1916 /* HIPR Variation of the cyclic skeleton
1917 ** Corners of the traditional method made more forgiving,
1918 ** but the retain the same cyclic order.
1920 kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;");
1921 if (kernel == (KernelInfo *) NULL)
1923 if (kernel->next == (KernelInfo *) NULL)
1924 return(DestroyKernelInfo(kernel));
1925 kernel->type = type;
1926 kernel->next->type = type;
1927 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */
1930 /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's
1931 ** "Connectivity-Preserving Morphological Image Thransformations"
1932 ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1933 ** http://www.leptonica.com/papers/conn.pdf
1935 kernel=AcquireKernelInfo(
1936 "ThinSE:41; ThinSE:42; ThinSE:43");
1937 if (kernel == (KernelInfo *) NULL)
1939 kernel->type = type;
1940 kernel->next->type = type;
1941 kernel->next->next->type = type;
1942 ExpandMirrorKernelInfo(kernel); /* 12 kernels total */
1948 { /* Special kernels for general thinning, while preserving connections
1949 ** "Connectivity-Preserving Morphological Image Thransformations"
1950 ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1951 ** http://www.leptonica.com/papers/conn.pdf
1953 ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html
1955 ** Note kernels do not specify the origin pixel, allowing them
1956 ** to be used for both thickening and thinning operations.
1958 switch ( (int) args->rho ) {
1959 /* SE for 4-connected thinning */
1960 case 41: /* SE_4_1 */
1961 kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1");
1963 case 42: /* SE_4_2 */
1964 kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-");
1966 case 43: /* SE_4_3 */
1967 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1");
1969 case 44: /* SE_4_4 */
1970 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-");
1972 case 45: /* SE_4_5 */
1973 kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-");
1975 case 46: /* SE_4_6 */
1976 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1");
1978 case 47: /* SE_4_7 */
1979 kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-");
1981 case 48: /* SE_4_8 */
1982 kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1");
1984 case 49: /* SE_4_9 */
1985 kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1");
1987 /* SE for 8-connected thinning - negatives of the above */
1988 case 81: /* SE_8_0 */
1989 kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-");
1991 case 82: /* SE_8_2 */
1992 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-");
1994 case 83: /* SE_8_3 */
1995 kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-");
1997 case 84: /* SE_8_4 */
1998 kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-");
2000 case 85: /* SE_8_5 */
2001 kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-");
2003 case 86: /* SE_8_6 */
2004 kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1");
2006 case 87: /* SE_8_7 */
2007 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-");
2009 case 88: /* SE_8_8 */
2010 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-");
2012 case 89: /* SE_8_9 */
2013 kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-");
2015 /* Special combined SE kernels */
2016 case 423: /* SE_4_2 , SE_4_3 Combined Kernel */
2017 kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-");
2019 case 823: /* SE_8_2 , SE_8_3 Combined Kernel */
2020 kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-");
2022 case 481: /* SE_48_1 - General Connected Corner Kernel */
2023 kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-");
2026 case 482: /* SE_48_2 - General Edge Kernel */
2027 kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1");
2030 if (kernel == (KernelInfo *) NULL)
2032 kernel->type = type;
2033 RotateKernelInfo(kernel, args->sigma);
2037 Distance Measuring Kernels
2039 case ChebyshevKernel:
2041 if (args->rho < 1.0)
2042 kernel->width = kernel->height = 3; /* default radius = 1 */
2044 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2045 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2047 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2048 kernel->height*sizeof(*kernel->values));
2049 if (kernel->values == (double *) NULL)
2050 return(DestroyKernelInfo(kernel));
2052 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2053 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2054 kernel->positive_range += ( kernel->values[i] =
2055 args->sigma*MagickMax(fabs((double)u),fabs((double)v)) );
2056 kernel->maximum = kernel->values[0];
2059 case ManhattanKernel:
2061 if (args->rho < 1.0)
2062 kernel->width = kernel->height = 3; /* default radius = 1 */
2064 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2065 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2067 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2068 kernel->height*sizeof(*kernel->values));
2069 if (kernel->values == (double *) NULL)
2070 return(DestroyKernelInfo(kernel));
2072 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2073 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2074 kernel->positive_range += ( kernel->values[i] =
2075 args->sigma*(labs((long) u)+labs((long) v)) );
2076 kernel->maximum = kernel->values[0];
2079 case OctagonalKernel:
2081 if (args->rho < 2.0)
2082 kernel->width = kernel->height = 5; /* default/minimum radius = 2 */
2084 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2085 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2087 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2088 kernel->height*sizeof(*kernel->values));
2089 if (kernel->values == (double *) NULL)
2090 return(DestroyKernelInfo(kernel));
2092 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2093 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2096 r1 = MagickMax(fabs((double)u),fabs((double)v)),
2097 r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5);
2098 kernel->positive_range += kernel->values[i] =
2099 args->sigma*MagickMax(r1,r2);
2101 kernel->maximum = kernel->values[0];
2104 case EuclideanKernel:
2106 if (args->rho < 1.0)
2107 kernel->width = kernel->height = 3; /* default radius = 1 */
2109 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2110 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2112 kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2113 kernel->height*sizeof(*kernel->values));
2114 if (kernel->values == (double *) NULL)
2115 return(DestroyKernelInfo(kernel));
2117 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2118 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2119 kernel->positive_range += ( kernel->values[i] =
2120 args->sigma*sqrt((double)(u*u+v*v)) );
2121 kernel->maximum = kernel->values[0];
2126 /* No-Op Kernel - Basically just a single pixel on its own */
2127 kernel=ParseKernelArray("1:1");
2128 if (kernel == (KernelInfo *) NULL)
2130 kernel->type = UndefinedKernel;
2139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2143 % C l o n e K e r n e l I n f o %
2147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2149 % CloneKernelInfo() creates a new clone of the given Kernel List so that its
2150 % can be modified without effecting the original. The cloned kernel should
2151 % be destroyed using DestoryKernelInfo() when no longer needed.
2153 % The format of the CloneKernelInfo method is:
2155 % KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2157 % A description of each parameter follows:
2159 % o kernel: the Morphology/Convolution kernel to be cloned
2162 MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2170 assert(kernel != (KernelInfo *) NULL);
2171 new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
2172 if (new_kernel == (KernelInfo *) NULL)
2174 *new_kernel=(*kernel); /* copy values in structure */
2176 /* replace the values with a copy of the values */
2177 new_kernel->values=(double *) AcquireAlignedMemory(kernel->width,
2178 kernel->height*sizeof(*kernel->values));
2179 if (new_kernel->values == (double *) NULL)
2180 return(DestroyKernelInfo(new_kernel));
2181 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
2182 new_kernel->values[i]=kernel->values[i];
2184 /* Also clone the next kernel in the kernel list */
2185 if ( kernel->next != (KernelInfo *) NULL ) {
2186 new_kernel->next = CloneKernelInfo(kernel->next);
2187 if ( new_kernel->next == (KernelInfo *) NULL )
2188 return(DestroyKernelInfo(new_kernel));
2195 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2199 % D e s t r o y K e r n e l I n f o %
2203 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2205 % DestroyKernelInfo() frees the memory used by a Convolution/Morphology
2208 % The format of the DestroyKernelInfo method is:
2210 % KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2212 % A description of each parameter follows:
2214 % o kernel: the Morphology/Convolution kernel to be destroyed
2217 MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2219 assert(kernel != (KernelInfo *) NULL);
2220 if ( kernel->next != (KernelInfo *) NULL )
2221 kernel->next=DestroyKernelInfo(kernel->next);
2222 kernel->values=(double *) RelinquishAlignedMemory(kernel->values);
2223 kernel=(KernelInfo *) RelinquishMagickMemory(kernel);
2228 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2232 + E x p a n d M i r r o r K e r n e l I n f o %
2236 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2238 % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
2239 % sequence of 90-degree rotated kernels but providing a reflected 180
2240 % rotatation, before the -/+ 90-degree rotations.
2242 % This special rotation order produces a better, more symetrical thinning of
2245 % The format of the ExpandMirrorKernelInfo method is:
2247 % void ExpandMirrorKernelInfo(KernelInfo *kernel)
2249 % A description of each parameter follows:
2251 % o kernel: the Morphology/Convolution kernel
2253 % This function is only internel to this module, as it is not finalized,
2254 % especially with regard to non-orthogonal angles, and rotation of larger
2259 static void FlopKernelInfo(KernelInfo *kernel)
2260 { /* Do a Flop by reversing each row. */
2268 for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
2269 for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
2270 t=k[x], k[x]=k[r], k[r]=t;
2272 kernel->x = kernel->width - kernel->x - 1;
2273 angle = fmod(angle+180.0, 360.0);
2277 static void ExpandMirrorKernelInfo(KernelInfo *kernel)
2285 clone = CloneKernelInfo(last);
2286 RotateKernelInfo(clone, 180); /* flip */
2287 LastKernelInfo(last)->next = clone;
2290 clone = CloneKernelInfo(last);
2291 RotateKernelInfo(clone, 90); /* transpose */
2292 LastKernelInfo(last)->next = clone;
2295 clone = CloneKernelInfo(last);
2296 RotateKernelInfo(clone, 180); /* flop */
2297 LastKernelInfo(last)->next = clone;
2303 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2307 + E x p a n d R o t a t e K e r n e l I n f o %
2311 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2313 % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
2314 % incrementally by the angle given, until the kernel repeats.
2316 % WARNING: 45 degree rotations only works for 3x3 kernels.
2317 % While 90 degree roatations only works for linear and square kernels
2319 % The format of the ExpandRotateKernelInfo method is:
2321 % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
2323 % A description of each parameter follows:
2325 % o kernel: the Morphology/Convolution kernel
2327 % o angle: angle to rotate in degrees
2329 % This function is only internel to this module, as it is not finalized,
2330 % especially with regard to non-orthogonal angles, and rotation of larger
2334 /* Internal Routine - Return true if two kernels are the same */
2335 static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
2336 const KernelInfo *kernel2)
2341 /* check size and origin location */
2342 if ( kernel1->width != kernel2->width
2343 || kernel1->height != kernel2->height
2344 || kernel1->x != kernel2->x
2345 || kernel1->y != kernel2->y )
2348 /* check actual kernel values */
2349 for (i=0; i < (kernel1->width*kernel1->height); i++) {
2350 /* Test for Nan equivalence */
2351 if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
2353 if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
2355 /* Test actual values are equivalent */
2356 if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
2363 static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
2371 clone = CloneKernelInfo(last);
2372 RotateKernelInfo(clone, angle);
2373 if ( SameKernelInfo(kernel, clone) == MagickTrue )
2375 LastKernelInfo(last)->next = clone;
2378 clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
2383 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2387 + C a l c M e t a K e r n a l I n f o %
2391 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2393 % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2394 % using the kernel values. This should only ne used if it is not possible to
2395 % calculate that meta-data in some easier way.
2397 % It is important that the meta-data is correct before ScaleKernelInfo() is
2398 % used to perform kernel normalization.
2400 % The format of the CalcKernelMetaData method is:
2402 % void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2404 % A description of each parameter follows:
2406 % o kernel: the Morphology/Convolution kernel to modify
2408 % WARNING: Minimum and Maximum values are assumed to include zero, even if
2409 % zero is not part of the kernel (as in Gaussian Derived kernels). This
2410 % however is not true for flat-shaped morphological kernels.
2412 % WARNING: Only the specific kernel pointed to is modified, not a list of
2415 % This is an internal function and not expected to be useful outside this
2416 % module. This could change however.
2418 static void CalcKernelMetaData(KernelInfo *kernel)
2423 kernel->minimum = kernel->maximum = 0.0;
2424 kernel->negative_range = kernel->positive_range = 0.0;
2425 for (i=0; i < (kernel->width*kernel->height); i++)
2427 if ( fabs(kernel->values[i]) < MagickEpsilon )
2428 kernel->values[i] = 0.0;
2429 ( kernel->values[i] < 0)
2430 ? ( kernel->negative_range += kernel->values[i] )
2431 : ( kernel->positive_range += kernel->values[i] );
2432 Minimize(kernel->minimum, kernel->values[i]);
2433 Maximize(kernel->maximum, kernel->values[i]);
2440 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2444 % M o r p h o l o g y A p p l y %
2448 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2450 % MorphologyApply() applies a morphological method, multiple times using
2451 % a list of multiple kernels. This is the method that should be called by
2452 % other 'operators' that internally use morphology operations as part of
2455 % It is basically equivalent to as MorphologyImage() (see below) but
2456 % without any user controls. This allows internel programs to use this
2457 % function, to actually perform a specific task without possible interference
2458 % by any API user supplied settings.
2460 % It is MorphologyImage() task to extract any such user controls, and
2461 % pass them to this function for processing.
2463 % More specifically all given kernels should already be scaled, normalised,
2464 % and blended appropriatally before being parred to this routine. The
2465 % appropriate bias, and compose (typically 'UndefinedComposeOp') given.
2467 % The format of the MorphologyApply method is:
2469 % Image *MorphologyApply(const Image *image,MorphologyMethod method,
2470 % const ssize_t iterations,const KernelInfo *kernel,
2471 % const CompositeMethod compose,const double bias,
2472 % ExceptionInfo *exception)
2474 % A description of each parameter follows:
2476 % o image: the source image
2478 % o method: the morphology method to be applied.
2480 % o iterations: apply the operation this many times (or no change).
2481 % A value of -1 means loop until no change found.
2482 % How this is applied may depend on the morphology method.
2483 % Typically this is a value of 1.
2485 % o channel: the channel type.
2487 % o kernel: An array of double representing the morphology kernel.
2489 % o compose: How to handle or merge multi-kernel results.
2490 % If 'UndefinedCompositeOp' use default for the Morphology method.
2491 % If 'NoCompositeOp' force image to be re-iterated by each kernel.
2492 % Otherwise merge the results using the compose method given.
2494 % o bias: Convolution Output Bias.
2496 % o exception: return any errors or warnings in this structure.
2500 /* Apply a Morphology Primative to an image using the given kernel.
2501 ** Two pre-created images must be provided, and no image is created.
2502 ** It returns the number of pixels that changed between the images
2503 ** for result convergence determination.
2505 static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image,
2506 const MorphologyMethod method,const KernelInfo *kernel,const double bias,
2507 ExceptionInfo *exception)
2509 #define MorphologyTag "Morphology/Image"
2528 assert(image != (Image *) NULL);
2529 assert(image->signature == MagickSignature);
2530 assert(morphology_image != (Image *) NULL);
2531 assert(morphology_image->signature == MagickSignature);
2532 assert(kernel != (KernelInfo *) NULL);
2533 assert(kernel->signature == MagickSignature);
2534 assert(exception != (ExceptionInfo *) NULL);
2535 assert(exception->signature == MagickSignature);
2541 image_view=AcquireVirtualCacheView(image,exception);
2542 morphology_view=AcquireAuthenticCacheView(morphology_image,exception);
2543 virt_width=image->columns+kernel->width-1;
2545 /* Some methods (including convolve) needs use a reflected kernel.
2546 * Adjust 'origin' offsets to loop though kernel as a reflection.
2551 case ConvolveMorphology:
2552 case DilateMorphology:
2553 case DilateIntensityMorphology:
2554 case IterativeDistanceMorphology:
2555 /* kernel needs to used with reflection about origin */
2556 offx = (ssize_t) kernel->width-offx-1;
2557 offy = (ssize_t) kernel->height-offy-1;
2559 case ErodeMorphology:
2560 case ErodeIntensityMorphology:
2561 case HitAndMissMorphology:
2562 case ThinningMorphology:
2563 case ThickenMorphology:
2564 /* kernel is used as is, without reflection */
2567 assert("Not a Primitive Morphology Method" != (char *) NULL);
2571 if ( method == ConvolveMorphology && kernel->width == 1 )
2572 { /* Special handling (for speed) of vertical (blur) kernels.
2573 ** This performs its handling in columns rather than in rows.
2574 ** This is only done for convolve as it is the only method that
2575 ** generates very large 1-D vertical kernels (such as a 'BlurKernel')
2577 ** Timing tests (on single CPU laptop)
2578 ** Using a vertical 1-d Blue with normal row-by-row (below)
2579 ** time convert logo: -morphology Convolve Blur:0x10+90 null:
2581 ** Using this column method
2582 ** time convert logo: -morphology Convolve Blur:0x10+90 null:
2585 ** Anthony Thyssen, 14 June 2010
2590 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2591 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2592 dynamic_num_threads_dos(image->columns,image->rows)
2594 for (x=0; x < (ssize_t) image->columns; x++)
2596 register const Quantum
2608 if (status == MagickFalse)
2610 p=GetCacheViewVirtualPixels(image_view,x,-offy,1,image->rows+
2611 kernel->height-1,exception);
2612 q=GetCacheViewAuthenticPixels(morphology_view,x,0,1,
2613 morphology_image->rows,exception);
2614 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2619 /* offset to origin in 'p'. while 'q' points to it directly */
2622 for (y=0; y < (ssize_t) image->rows; y++)
2630 register const double
2633 register const Quantum
2636 /* Copy input image to the output image for unused channels
2637 * This removes need for 'cloning' a new image every iteration
2639 SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2640 GetPixelChannels(image)),q);
2641 SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2642 GetPixelChannels(image)),q);
2643 SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2644 GetPixelChannels(image)),q);
2645 if (image->colorspace == CMYKColorspace)
2646 SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2647 GetPixelChannels(image)),q);
2649 /* Set the bias of the weighted average output */
2654 result.black = bias;
2657 /* Weighted Average of pixels using reflected kernel
2659 ** NOTE for correct working of this operation for asymetrical
2660 ** kernels, the kernel needs to be applied in its reflected form.
2661 ** That is its values needs to be reversed.
2663 k = &kernel->values[ kernel->height-1 ];
2665 if ( (image->channel_mask != DefaultChannels) ||
2666 (image->matte == MagickFalse) )
2667 { /* No 'Sync' involved.
2668 ** Convolution is just a simple greyscale channel operation
2670 for (v=0; v < (ssize_t) kernel->height; v++) {
2671 if ( IsNan(*k) ) continue;
2672 result.red += (*k)*GetPixelRed(image,k_pixels);
2673 result.green += (*k)*GetPixelGreen(image,k_pixels);
2674 result.blue += (*k)*GetPixelBlue(image,k_pixels);
2675 if (image->colorspace == CMYKColorspace)
2676 result.black+=(*k)*GetPixelBlack(image,k_pixels);
2677 result.alpha += (*k)*GetPixelAlpha(image,k_pixels);
2679 k_pixels+=GetPixelChannels(image);
2681 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2682 SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
2683 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2684 SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
2685 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2686 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
2687 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2688 (image->colorspace == CMYKColorspace))
2689 SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
2690 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2691 (image->matte == MagickTrue))
2692 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2695 { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2696 ** Weight the color channels with Alpha Channel so that
2697 ** transparent pixels are not part of the results.
2700 alpha, /* alpha weighting for colors : alpha */
2701 gamma; /* divisor, sum of color alpha weighting */
2703 count; /* alpha valus collected, number kernel values */
2707 for (v=0; v < (ssize_t) kernel->height; v++) {
2708 if ( IsNan(*k) ) continue;
2709 alpha=QuantumScale*GetPixelAlpha(image,k_pixels);
2710 gamma += alpha; /* normalize alpha weights only */
2711 count++; /* number of alpha values collected */
2712 alpha*=(*k); /* include kernel weighting now */
2713 result.red += alpha*GetPixelRed(image,k_pixels);
2714 result.green += alpha*GetPixelGreen(image,k_pixels);
2715 result.blue += alpha*GetPixelBlue(image,k_pixels);
2716 if (image->colorspace == CMYKColorspace)
2717 result.black += alpha*GetPixelBlack(image,k_pixels);
2718 result.alpha += (*k)*GetPixelAlpha(image,k_pixels);
2720 k_pixels+=GetPixelChannels(image);
2722 /* Sync'ed channels, all channels are modified */
2723 gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2724 SetPixelRed(morphology_image,ClampToQuantum(gamma*result.red),q);
2725 SetPixelGreen(morphology_image,ClampToQuantum(gamma*result.green),q);
2726 SetPixelBlue(morphology_image,ClampToQuantum(gamma*result.blue),q);
2727 if (image->colorspace == CMYKColorspace)
2728 SetPixelBlack(morphology_image,ClampToQuantum(gamma*result.black),q);
2729 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2732 /* Count up changed pixels */
2733 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q))
2734 || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q))
2735 || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q))
2736 || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q))
2737 || ((image->colorspace == CMYKColorspace) &&
2738 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
2739 changed++; /* The pixel was changed in some way! */
2740 p+=GetPixelChannels(image);
2741 q+=GetPixelChannels(morphology_image);
2743 if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
2745 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2750 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2751 #pragma omp critical (MagickCore_MorphologyImage)
2753 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
2754 if (proceed == MagickFalse)
2758 morphology_image->type=image->type;
2759 morphology_view=DestroyCacheView(morphology_view);
2760 image_view=DestroyCacheView(image_view);
2761 return(status ? (ssize_t) changed : 0);
2765 ** Normal handling of horizontal or rectangular kernels (row by row)
2767 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2768 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2769 dynamic_num_threads_dos(image->columns,image->rows)
2771 for (y=0; y < (ssize_t) image->rows; y++)
2773 register const Quantum
2785 if (status == MagickFalse)
2787 p=GetCacheViewVirtualPixels(image_view, -offx, y-offy, virt_width,
2788 kernel->height, exception);
2789 q=GetCacheViewAuthenticPixels(morphology_view,0,y,
2790 morphology_image->columns,1,exception);
2791 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2796 /* offset to origin in 'p'. while 'q' points to it directly */
2797 r = virt_width*offy + offx;
2799 for (x=0; x < (ssize_t) image->columns; x++)
2807 register const double
2810 register const Quantum
2818 /* Copy input image to the output image for unused channels
2819 * This removes need for 'cloning' a new image every iteration
2821 SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2822 GetPixelChannels(image)),q);
2823 SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2824 GetPixelChannels(image)),q);
2825 SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2826 GetPixelChannels(image)),q);
2827 if (image->colorspace == CMYKColorspace)
2828 SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2829 GetPixelChannels(image)),q);
2836 min.black = (MagickRealType) QuantumRange;
2841 max.black = (MagickRealType) 0;
2842 /* default result is the original pixel value */
2843 result.red = (MagickRealType) GetPixelRed(image,p+r*GetPixelChannels(image));
2844 result.green = (MagickRealType) GetPixelGreen(image,p+r*GetPixelChannels(image));
2845 result.blue = (MagickRealType) GetPixelBlue(image,p+r*GetPixelChannels(image));
2847 if (image->colorspace == CMYKColorspace)
2848 result.black = (MagickRealType) GetPixelBlack(image,p+r*GetPixelChannels(image));
2849 result.alpha=(MagickRealType) GetPixelAlpha(image,p+r*GetPixelChannels(image));
2852 case ConvolveMorphology:
2853 /* Set the bias of the weighted average output */
2858 result.black = bias;
2860 case DilateIntensityMorphology:
2861 case ErodeIntensityMorphology:
2862 /* use a boolean flag indicating when first match found */
2863 result.red = 0.0; /* result is not used otherwise */
2870 case ConvolveMorphology:
2871 /* Weighted Average of pixels using reflected kernel
2873 ** NOTE for correct working of this operation for asymetrical
2874 ** kernels, the kernel needs to be applied in its reflected form.
2875 ** That is its values needs to be reversed.
2877 ** Correlation is actually the same as this but without reflecting
2878 ** the kernel, and thus 'lower-level' that Convolution. However
2879 ** as Convolution is the more common method used, and it does not
2880 ** really cost us much in terms of processing to use a reflected
2881 ** kernel, so it is Convolution that is implemented.
2883 ** Correlation will have its kernel reflected before calling
2884 ** this function to do a Convolve.
2886 ** For more details of Correlation vs Convolution see
2887 ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
2889 k = &kernel->values[ kernel->width*kernel->height-1 ];
2891 if ( (image->channel_mask != DefaultChannels) ||
2892 (image->matte == MagickFalse) )
2893 { /* No 'Sync' involved.
2894 ** Convolution is simple greyscale channel operation
2896 for (v=0; v < (ssize_t) kernel->height; v++) {
2897 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2898 if ( IsNan(*k) ) continue;
2900 GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2901 result.green += (*k)*
2902 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2903 result.blue += (*k)*
2904 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2905 if (image->colorspace == CMYKColorspace)
2906 result.black += (*k)*
2907 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2908 result.alpha += (*k)*
2909 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2911 k_pixels += virt_width*GetPixelChannels(image);
2913 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2914 SetPixelRed(morphology_image,ClampToQuantum(result.red),
2916 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2917 SetPixelGreen(morphology_image,ClampToQuantum(result.green),
2919 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2920 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),
2922 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2923 (image->colorspace == CMYKColorspace))
2924 SetPixelBlack(morphology_image,ClampToQuantum(result.black),
2926 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2927 (image->matte == MagickTrue))
2928 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),
2932 { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2933 ** Weight the color channels with Alpha Channel so that
2934 ** transparent pixels are not part of the results.
2937 alpha, /* alpha weighting for colors : alpha */
2938 gamma; /* divisor, sum of color alpha weighting */
2940 count; /* alpha valus collected, number kernel values */
2944 for (v=0; v < (ssize_t) kernel->height; v++) {
2945 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2946 if ( IsNan(*k) ) continue;
2947 alpha=QuantumScale*GetPixelAlpha(image,
2948 k_pixels+u*GetPixelChannels(image));
2949 gamma += alpha; /* normalize alpha weights only */
2950 count++; /* number of alpha values collected */
2951 alpha=alpha*(*k); /* include kernel weighting now */
2952 result.red += alpha*
2953 GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2954 result.green += alpha*
2955 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2956 result.blue += alpha*
2957 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2958 if (image->colorspace == CMYKColorspace)
2959 result.black += alpha*
2960 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2961 result.alpha += (*k)*
2962 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2964 k_pixels += virt_width*GetPixelChannels(image);
2966 /* Sync'ed channels, all channels are modified */
2967 gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2968 SetPixelRed(morphology_image,
2969 ClampToQuantum(gamma*result.red),q);
2970 SetPixelGreen(morphology_image,
2971 ClampToQuantum(gamma*result.green),q);
2972 SetPixelBlue(morphology_image,
2973 ClampToQuantum(gamma*result.blue),q);
2974 if (image->colorspace == CMYKColorspace)
2975 SetPixelBlack(morphology_image,
2976 ClampToQuantum(gamma*result.black),q);
2977 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2981 case ErodeMorphology:
2982 /* Minimum Value within kernel neighbourhood
2984 ** NOTE that the kernel is not reflected for this operation!
2986 ** NOTE: in normal Greyscale Morphology, the kernel value should
2987 ** be added to the real value, this is currently not done, due to
2988 ** the nature of the boolean kernels being used.
2992 for (v=0; v < (ssize_t) kernel->height; v++) {
2993 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
2994 if ( IsNan(*k) || (*k) < 0.5 ) continue;
2995 Minimize(min.red, (double)
2996 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
2997 Minimize(min.green, (double)
2998 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
2999 Minimize(min.blue, (double)
3000 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3001 Minimize(min.alpha, (double)
3002 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3003 if (image->colorspace == CMYKColorspace)
3004 Minimize(min.black, (double)
3005 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3007 k_pixels += virt_width*GetPixelChannels(image);
3011 case DilateMorphology:
3012 /* Maximum Value within kernel neighbourhood
3014 ** NOTE for correct working of this operation for asymetrical
3015 ** kernels, the kernel needs to be applied in its reflected form.
3016 ** That is its values needs to be reversed.
3018 ** NOTE: in normal Greyscale Morphology, the kernel value should
3019 ** be added to the real value, this is currently not done, due to
3020 ** the nature of the boolean kernels being used.
3023 k = &kernel->values[ kernel->width*kernel->height-1 ];
3025 for (v=0; v < (ssize_t) kernel->height; v++) {
3026 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3027 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3028 Maximize(max.red, (double)
3029 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3030 Maximize(max.green, (double)
3031 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3032 Maximize(max.blue, (double)
3033 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3034 Maximize(max.alpha, (double)
3035 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3036 if (image->colorspace == CMYKColorspace)
3037 Maximize(max.black, (double)
3038 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3040 k_pixels += virt_width*GetPixelChannels(image);
3044 case HitAndMissMorphology:
3045 case ThinningMorphology:
3046 case ThickenMorphology:
3047 /* Minimum of Foreground Pixel minus Maxumum of Background Pixels
3049 ** NOTE that the kernel is not reflected for this operation,
3050 ** and consists of both foreground and background pixel
3051 ** neighbourhoods, 0.0 for background, and 1.0 for foreground
3052 ** with either Nan or 0.5 values for don't care.
3054 ** Note that this will never produce a meaningless negative
3055 ** result. Such results can cause Thinning/Thicken to not work
3056 ** correctly when used against a greyscale image.
3060 for (v=0; v < (ssize_t) kernel->height; v++) {
3061 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3062 if ( IsNan(*k) ) continue;
3064 { /* minimim of foreground pixels */
3065 Minimize(min.red, (double)
3066 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3067 Minimize(min.green, (double)
3068 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3069 Minimize(min.blue, (double)
3070 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3071 Minimize(min.alpha,(double)
3072 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3073 if ( image->colorspace == CMYKColorspace)
3074 Minimize(min.black,(double)
3075 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3077 else if ( (*k) < 0.3 )
3078 { /* maximum of background pixels */
3079 Maximize(max.red, (double)
3080 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3081 Maximize(max.green, (double)
3082 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3083 Maximize(max.blue, (double)
3084 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3085 Maximize(max.alpha,(double)
3086 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3087 if (image->colorspace == CMYKColorspace)
3088 Maximize(max.black, (double)
3089 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3092 k_pixels += virt_width*GetPixelChannels(image);
3094 /* Pattern Match if difference is positive */
3095 min.red -= max.red; Maximize( min.red, 0.0 );
3096 min.green -= max.green; Maximize( min.green, 0.0 );
3097 min.blue -= max.blue; Maximize( min.blue, 0.0 );
3098 min.black -= max.black; Maximize( min.black, 0.0 );
3099 min.alpha -= max.alpha; Maximize( min.alpha, 0.0 );
3102 case ErodeIntensityMorphology:
3103 /* Select Pixel with Minimum Intensity within kernel neighbourhood
3105 ** WARNING: the intensity test fails for CMYK and does not
3106 ** take into account the moderating effect of the alpha channel
3107 ** on the intensity.
3109 ** NOTE that the kernel is not reflected for this operation!
3113 for (v=0; v < (ssize_t) kernel->height; v++) {
3114 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3115 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3116 if ( result.red == 0.0 ||
3117 GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) < GetPixelIntensity(morphology_image,q) ) {
3118 /* copy the whole pixel - no channel selection */
3119 SetPixelRed(morphology_image,GetPixelRed(image,
3120 k_pixels+u*GetPixelChannels(image)),q);
3121 SetPixelGreen(morphology_image,GetPixelGreen(image,
3122 k_pixels+u*GetPixelChannels(image)),q);
3123 SetPixelBlue(morphology_image,GetPixelBlue(image,
3124 k_pixels+u*GetPixelChannels(image)),q);
3125 SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3126 k_pixels+u*GetPixelChannels(image)),q);
3127 if ( result.red > 0.0 ) changed++;
3131 k_pixels += virt_width*GetPixelChannels(image);
3135 case DilateIntensityMorphology:
3136 /* Select Pixel with Maximum Intensity within kernel neighbourhood
3138 ** WARNING: the intensity test fails for CMYK and does not
3139 ** take into account the moderating effect of the alpha channel
3140 ** on the intensity (yet).
3142 ** NOTE for correct working of this operation for asymetrical
3143 ** kernels, the kernel needs to be applied in its reflected form.
3144 ** That is its values needs to be reversed.
3146 k = &kernel->values[ kernel->width*kernel->height-1 ];
3148 for (v=0; v < (ssize_t) kernel->height; v++) {
3149 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3150 if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */
3151 if ( result.red == 0.0 ||
3152 GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) > GetPixelIntensity(morphology_image,q) ) {
3153 /* copy the whole pixel - no channel selection */
3154 SetPixelRed(morphology_image,GetPixelRed(image,
3155 k_pixels+u*GetPixelChannels(image)),q);
3156 SetPixelGreen(morphology_image,GetPixelGreen(image,
3157 k_pixels+u*GetPixelChannels(image)),q);
3158 SetPixelBlue(morphology_image,GetPixelBlue(image,
3159 k_pixels+u*GetPixelChannels(image)),q);
3160 SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3161 k_pixels+u*GetPixelChannels(image)),q);
3162 if ( result.red > 0.0 ) changed++;
3166 k_pixels += virt_width*GetPixelChannels(image);
3170 case IterativeDistanceMorphology:
3171 /* Work out an iterative distance from black edge of a white image
3172 ** shape. Essentually white values are decreased to the smallest
3173 ** 'distance from edge' it can find.
3175 ** It works by adding kernel values to the neighbourhood, and and
3176 ** select the minimum value found. The kernel is rotated before
3177 ** use, so kernel distances match resulting distances, when a user
3178 ** provided asymmetric kernel is applied.
3181 ** This code is almost identical to True GrayScale Morphology But
3184 ** GreyDilate Kernel values added, maximum value found Kernel is
3185 ** rotated before use.
3187 ** GrayErode: Kernel values subtracted and minimum value found No
3188 ** kernel rotation used.
3190 ** Note the the Iterative Distance method is essentially a
3191 ** GrayErode, but with negative kernel values, and kernel
3192 ** rotation applied.
3194 k = &kernel->values[ kernel->width*kernel->height-1 ];
3196 for (v=0; v < (ssize_t) kernel->height; v++) {
3197 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3198 if ( IsNan(*k) ) continue;
3199 Minimize(result.red, (*k)+(double)
3200 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3201 Minimize(result.green, (*k)+(double)
3202 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3203 Minimize(result.blue, (*k)+(double)
3204 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3205 Minimize(result.alpha, (*k)+(double)
3206 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3207 if ( image->colorspace == CMYKColorspace)
3208 Maximize(result.black, (*k)+(double)
3209 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3211 k_pixels += virt_width*GetPixelChannels(image);
3215 case UndefinedMorphology:
3217 break; /* Do nothing */
3219 /* Final mathematics of results (combine with original image?)
3221 ** NOTE: Difference Morphology operators Edge* and *Hat could also
3222 ** be done here but works better with iteration as a image difference
3223 ** in the controling function (below). Thicken and Thinning however
3224 ** should be done here so thay can be iterated correctly.
3227 case HitAndMissMorphology:
3228 case ErodeMorphology:
3229 result = min; /* minimum of neighbourhood */
3231 case DilateMorphology:
3232 result = max; /* maximum of neighbourhood */
3234 case ThinningMorphology:
3235 /* subtract pattern match from original */
3236 result.red -= min.red;
3237 result.green -= min.green;
3238 result.blue -= min.blue;
3239 result.black -= min.black;
3240 result.alpha -= min.alpha;
3242 case ThickenMorphology:
3243 /* Add the pattern matchs to the original */
3244 result.red += min.red;
3245 result.green += min.green;
3246 result.blue += min.blue;
3247 result.black += min.black;
3248 result.alpha += min.alpha;
3251 /* result directly calculated or assigned */
3254 /* Assign the resulting pixel values - Clamping Result */
3256 case UndefinedMorphology:
3257 case ConvolveMorphology:
3258 case DilateIntensityMorphology:
3259 case ErodeIntensityMorphology:
3260 break; /* full pixel was directly assigned - not a channel method */
3262 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3263 SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
3264 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3265 SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
3266 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3267 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
3268 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3269 (image->colorspace == CMYKColorspace))
3270 SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
3271 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
3272 (image->matte == MagickTrue))
3273 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
3276 /* Count up changed pixels */
3277 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q)) ||
3278 (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q)) ||
3279 (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q)) ||
3280 (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q)) ||
3281 ((image->colorspace == CMYKColorspace) &&
3282 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
3283 changed++; /* The pixel was changed in some way! */
3284 p+=GetPixelChannels(image);
3285 q+=GetPixelChannels(morphology_image);
3287 if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
3289 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3294 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3295 #pragma omp critical (MagickCore_MorphologyImage)
3297 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
3298 if (proceed == MagickFalse)
3302 morphology_view=DestroyCacheView(morphology_view);
3303 image_view=DestroyCacheView(image_view);
3304 return(status ? (ssize_t)changed : -1);
3307 /* This is almost identical to the MorphologyPrimative() function above,
3308 ** but will apply the primitive directly to the actual image using two
3309 ** passes, once in each direction, with the results of the previous (and
3310 ** current) row being re-used.
3312 ** That is after each row is 'Sync'ed' into the image, the next row will
3313 ** make use of those values as part of the calculation of the next row.
3314 ** It then repeats, but going in the oppisite (bottom-up) direction.
3316 ** Because of this 're-use of results' this function can not make use
3317 ** of multi-threaded, parellel processing.
3319 static ssize_t MorphologyPrimitiveDirect(Image *image,
3320 const MorphologyMethod method,const KernelInfo *kernel,
3321 ExceptionInfo *exception)
3344 assert(image != (Image *) NULL);
3345 assert(image->signature == MagickSignature);
3346 assert(kernel != (KernelInfo *) NULL);
3347 assert(kernel->signature == MagickSignature);
3348 assert(exception != (ExceptionInfo *) NULL);
3349 assert(exception->signature == MagickSignature);
3351 /* Some methods (including convolve) needs use a reflected kernel.
3352 * Adjust 'origin' offsets to loop though kernel as a reflection.
3357 case DistanceMorphology:
3358 case VoronoiMorphology:
3359 /* kernel needs to used with reflection about origin */
3360 offx = (ssize_t) kernel->width-offx-1;
3361 offy = (ssize_t) kernel->height-offy-1;
3364 case ?????Morphology:
3365 /* kernel is used as is, without reflection */
3369 assert("Not a PrimativeDirect Morphology Method" != (char *) NULL);
3373 /* DO NOT THREAD THIS CODE! */
3374 /* two views into same image (virtual, and actual) */
3375 virt_view=AcquireVirtualCacheView(image,exception);
3376 auth_view=AcquireAuthenticCacheView(image,exception);
3377 virt_width=image->columns+kernel->width-1;
3379 for (y=0; y < (ssize_t) image->rows; y++)
3381 register const Quantum
3393 /* NOTE read virtual pixels, and authentic pixels, from the same image!
3394 ** we read using virtual to get virtual pixel handling, but write back
3395 ** into the same image.
3397 ** Only top half of kernel is processed as we do a single pass downward
3398 ** through the image iterating the distance function as we go.
3400 if (status == MagickFalse)
3402 p=GetCacheViewVirtualPixels(virt_view,-offx,y-offy,virt_width,(size_t)
3404 q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3406 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3408 if (status == MagickFalse)
3411 /* offset to origin in 'p'. while 'q' points to it directly */
3412 r = (ssize_t) virt_width*offy + offx;
3414 for (x=0; x < (ssize_t) image->columns; x++)
3422 register const double
3425 register const Quantum
3431 /* Starting Defaults */
3432 GetPixelInfo(image,&result);
3433 GetPixelInfoPixel(image,q,&result);
3434 if ( method != VoronoiMorphology )
3435 result.alpha = QuantumRange - result.alpha;
3438 case DistanceMorphology:
3439 /* Add kernel Value and select the minimum value found. */
3440 k = &kernel->values[ kernel->width*kernel->height-1 ];
3442 for (v=0; v <= (ssize_t) offy; v++) {
3443 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3444 if ( IsNan(*k) ) continue;
3445 Minimize(result.red, (*k)+
3446 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3447 Minimize(result.green, (*k)+
3448 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3449 Minimize(result.blue, (*k)+
3450 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3451 if (image->colorspace == CMYKColorspace)
3452 Minimize(result.black,(*k)+
3453 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3454 Minimize(result.alpha, (*k)+
3455 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3457 k_pixels += virt_width*GetPixelChannels(image);
3459 /* repeat with the just processed pixels of this row */
3460 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3461 k_pixels = q-offx*GetPixelChannels(image);
3462 for (u=0; u < (ssize_t) offx; u++, k--) {
3463 if ( x+u-offx < 0 ) continue; /* off the edge! */
3464 if ( IsNan(*k) ) continue;
3465 Minimize(result.red, (*k)+
3466 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3467 Minimize(result.green, (*k)+
3468 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3469 Minimize(result.blue, (*k)+
3470 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3471 if (image->colorspace == CMYKColorspace)
3472 Minimize(result.black,(*k)+
3473 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3474 Minimize(result.alpha,(*k)+
3475 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3478 case VoronoiMorphology:
3479 /* Apply Distance to 'Matte' channel, while coping the color
3480 ** values of the closest pixel.
3482 ** This is experimental, and realy the 'alpha' component should
3483 ** be completely separate 'masking' channel so that alpha can
3484 ** also be used as part of the results.
3486 k = &kernel->values[ kernel->width*kernel->height-1 ];
3488 for (v=0; v <= (ssize_t) offy; v++) {
3489 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3490 if ( IsNan(*k) ) continue;
3491 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3493 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3498 k_pixels += virt_width*GetPixelChannels(image);
3500 /* repeat with the just processed pixels of this row */
3501 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3502 k_pixels = q-offx*GetPixelChannels(image);
3503 for (u=0; u < (ssize_t) offx; u++, k--) {
3504 if ( x+u-offx < 0 ) continue; /* off the edge! */
3505 if ( IsNan(*k) ) continue;
3506 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3508 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3515 /* result directly calculated or assigned */
3518 /* Assign the resulting pixel values - Clamping Result */
3520 case VoronoiMorphology:
3521 SetPixelInfoPixel(image,&result,q);
3524 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3525 SetPixelRed(image,ClampToQuantum(result.red),q);
3526 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3527 SetPixelGreen(image,ClampToQuantum(result.green),q);
3528 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3529 SetPixelBlue(image,ClampToQuantum(result.blue),q);
3530 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3531 (image->colorspace == CMYKColorspace))
3532 SetPixelBlack(image,ClampToQuantum(result.black),q);
3533 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3534 (image->matte == MagickTrue))
3535 SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3538 /* Count up changed pixels */
3539 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q)) ||
3540 (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q)) ||
3541 (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q)) ||
3542 (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q)) ||
3543 ((image->colorspace == CMYKColorspace) &&
3544 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3545 changed++; /* The pixel was changed in some way! */
3547 p+=GetPixelChannels(image); /* increment pixel buffers */
3548 q+=GetPixelChannels(image);
3551 if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3553 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3554 if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3560 /* Do the reversed pass through the image */
3561 for (y=(ssize_t)image->rows-1; y >= 0; y--)
3563 register const Quantum
3575 if (status == MagickFalse)
3577 /* NOTE read virtual pixels, and authentic pixels, from the same image!
3578 ** we read using virtual to get virtual pixel handling, but write back
3579 ** into the same image.
3581 ** Only the bottom half of the kernel will be processes as we
3584 p=GetCacheViewVirtualPixels(virt_view,-offx,y,virt_width,(size_t)
3585 kernel->y+1,exception);
3586 q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3588 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3590 if (status == MagickFalse)
3593 /* adjust positions to end of row */
3594 p += (image->columns-1)*GetPixelChannels(image);
3595 q += (image->columns-1)*GetPixelChannels(image);
3597 /* offset to origin in 'p'. while 'q' points to it directly */
3600 for (x=(ssize_t)image->columns-1; x >= 0; x--)
3608 register const double
3611 register const Quantum
3617 /* Default - previously modified pixel */
3618 GetPixelInfo(image,&result);
3619 GetPixelInfoPixel(image,q,&result);
3620 if ( method != VoronoiMorphology )
3621 result.alpha = QuantumRange - result.alpha;
3624 case DistanceMorphology:
3625 /* Add kernel Value and select the minimum value found. */
3626 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3628 for (v=offy; v < (ssize_t) kernel->height; v++) {
3629 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3630 if ( IsNan(*k) ) continue;
3631 Minimize(result.red, (*k)+
3632 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3633 Minimize(result.green, (*k)+
3634 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3635 Minimize(result.blue, (*k)+
3636 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3637 if ( image->colorspace == CMYKColorspace)
3638 Minimize(result.black,(*k)+
3639 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3640 Minimize(result.alpha, (*k)+
3641 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3643 k_pixels += virt_width*GetPixelChannels(image);
3645 /* repeat with the just processed pixels of this row */
3646 k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3647 k_pixels = q-offx*GetPixelChannels(image);
3648 for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3649 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3650 if ( IsNan(*k) ) continue;
3651 Minimize(result.red, (*k)+
3652 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3653 Minimize(result.green, (*k)+
3654 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3655 Minimize(result.blue, (*k)+
3656 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3657 if ( image->colorspace == CMYKColorspace)
3658 Minimize(result.black, (*k)+
3659 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3660 Minimize(result.alpha, (*k)+
3661 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3664 case VoronoiMorphology:
3665 /* Apply Distance to 'Matte' channel, coping the closest color.
3667 ** This is experimental, and realy the 'alpha' component should
3668 ** be completely separate 'masking' channel.
3670 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3672 for (v=offy; v < (ssize_t) kernel->height; v++) {
3673 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3674 if ( IsNan(*k) ) continue;
3675 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3677 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3682 k_pixels += virt_width*GetPixelChannels(image);
3684 /* repeat with the just processed pixels of this row */
3685 k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3686 k_pixels = q-offx*GetPixelChannels(image);
3687 for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3688 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3689 if ( IsNan(*k) ) continue;
3690 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3692 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3699 /* result directly calculated or assigned */
3702 /* Assign the resulting pixel values - Clamping Result */
3704 case VoronoiMorphology:
3705 SetPixelInfoPixel(image,&result,q);
3708 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3709 SetPixelRed(image,ClampToQuantum(result.red),q);
3710 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3711 SetPixelGreen(image,ClampToQuantum(result.green),q);
3712 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3713 SetPixelBlue(image,ClampToQuantum(result.blue),q);
3714 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3715 (image->colorspace == CMYKColorspace))
3716 SetPixelBlack(image,ClampToQuantum(result.black),q);
3717 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3718 (image->matte == MagickTrue))
3719 SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3722 /* Count up changed pixels */
3723 if ( (GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q))
3724 || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q))
3725 || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q))
3726 || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q))
3727 || ((image->colorspace == CMYKColorspace) &&
3728 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3729 changed++; /* The pixel was changed in some way! */
3731 p-=GetPixelChannels(image); /* go backward through pixel buffers */
3732 q-=GetPixelChannels(image);
3734 if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3736 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3737 if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3743 auth_view=DestroyCacheView(auth_view);
3744 virt_view=DestroyCacheView(virt_view);
3745 return(status ? (ssize_t) changed : -1);
3748 /* Apply a Morphology by calling one of the above low level primitive
3749 ** application functions. This function handles any iteration loops,
3750 ** composition or re-iteration of results, and compound morphology methods
3751 ** that is based on multiple low-level (staged) morphology methods.
3753 ** Basically this provides the complex glue between the requested morphology
3754 ** method and raw low-level implementation (above).
3756 MagickPrivate Image *MorphologyApply(const Image *image,
3757 const MorphologyMethod method, const ssize_t iterations,
3758 const KernelInfo *kernel, const CompositeOperator compose,const double bias,
3759 ExceptionInfo *exception)
3765 *curr_image, /* Image we are working with or iterating */
3766 *work_image, /* secondary image for primitive iteration */
3767 *save_image, /* saved image - for 'edge' method only */
3768 *rslt_image; /* resultant image - after multi-kernel handling */
3771 *reflected_kernel, /* A reflected copy of the kernel (if needed) */
3772 *norm_kernel, /* the current normal un-reflected kernel */
3773 *rflt_kernel, /* the current reflected kernel (if needed) */
3774 *this_kernel; /* the kernel being applied */
3777 primitive; /* the current morphology primitive being applied */
3780 rslt_compose; /* multi-kernel compose method for results to use */
3783 special, /* do we use a direct modify function? */
3784 verbose; /* verbose output of results */
3787 method_loop, /* Loop 1: number of compound method iterations (norm 1) */
3788 method_limit, /* maximum number of compound method iterations */
3789 kernel_number, /* Loop 2: the kernel number being applied */
3790 stage_loop, /* Loop 3: primitive loop for compound morphology */
3791 stage_limit, /* how many primitives are in this compound */
3792 kernel_loop, /* Loop 4: iterate the kernel over image */
3793 kernel_limit, /* number of times to iterate kernel */
3794 count, /* total count of primitive steps applied */
3795 kernel_changed, /* total count of changed using iterated kernel */
3796 method_changed; /* total count of changed over method iteration */
3799 changed; /* number pixels changed by last primitive operation */
3804 assert(image != (Image *) NULL);
3805 assert(image->signature == MagickSignature);
3806 assert(kernel != (KernelInfo *) NULL);
3807 assert(kernel->signature == MagickSignature);
3808 assert(exception != (ExceptionInfo *) NULL);
3809 assert(exception->signature == MagickSignature);
3811 count = 0; /* number of low-level morphology primitives performed */
3812 if ( iterations == 0 )
3813 return((Image *)NULL); /* null operation - nothing to do! */
3815 kernel_limit = (size_t) iterations;
3816 if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
3817 kernel_limit = image->columns>image->rows ? image->columns : image->rows;
3819 verbose = IsStringTrue(GetImageArtifact(image,"verbose"));
3821 /* initialise for cleanup */
3822 curr_image = (Image *) image;
3823 curr_compose = image->compose;
3824 (void) curr_compose;
3825 work_image = save_image = rslt_image = (Image *) NULL;
3826 reflected_kernel = (KernelInfo *) NULL;
3828 /* Initialize specific methods
3829 * + which loop should use the given iteratations
3830 * + how many primitives make up the compound morphology
3831 * + multi-kernel compose method to use (by default)
3833 method_limit = 1; /* just do method once, unless otherwise set */
3834 stage_limit = 1; /* assume method is not a compound */
3835 special = MagickFalse; /* assume it is NOT a direct modify primitive */
3836 rslt_compose = compose; /* and we are composing multi-kernels as given */
3838 case SmoothMorphology: /* 4 primitive compound morphology */
3841 case OpenMorphology: /* 2 primitive compound morphology */
3842 case OpenIntensityMorphology:
3843 case TopHatMorphology:
3844 case CloseMorphology:
3845 case CloseIntensityMorphology:
3846 case BottomHatMorphology:
3847 case EdgeMorphology:
3850 case HitAndMissMorphology:
3851 rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
3853 case ThinningMorphology:
3854 case ThickenMorphology:
3855 method_limit = kernel_limit; /* iterate the whole method */
3856 kernel_limit = 1; /* do not do kernel iteration */
3858 case DistanceMorphology:
3859 case VoronoiMorphology:
3860 special = MagickTrue; /* use special direct primative */
3866 /* Apply special methods with special requirments
3867 ** For example, single run only, or post-processing requirements
3869 if ( special == MagickTrue )
3871 rslt_image=CloneImage(image,0,0,MagickTrue,exception);
3872 if (rslt_image == (Image *) NULL)
3874 if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse)
3877 changed = MorphologyPrimitiveDirect(rslt_image, method,
3880 if ( IfMagickTrue(verbose) )
3881 (void) (void) FormatLocaleFile(stderr,
3882 "%s:%.20g.%.20g #%.20g => Changed %.20g\n",
3883 CommandOptionToMnemonic(MagickMorphologyOptions, method),
3884 1.0,0.0,1.0, (double) changed);
3889 if ( method == VoronoiMorphology ) {
3890 /* Preserve the alpha channel of input image - but turned off */
3891 (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3893 (void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp,
3894 MagickTrue,0,0,exception);
3895 (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3901 /* Handle user (caller) specified multi-kernel composition method */
3902 if ( compose != UndefinedCompositeOp )
3903 rslt_compose = compose; /* override default composition for method */
3904 if ( rslt_compose == UndefinedCompositeOp )
3905 rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
3907 /* Some methods require a reflected kernel to use with primitives.
3908 * Create the reflected kernel for those methods. */
3910 case CorrelateMorphology:
3911 case CloseMorphology:
3912 case CloseIntensityMorphology:
3913 case BottomHatMorphology:
3914 case SmoothMorphology:
3915 reflected_kernel = CloneKernelInfo(kernel);
3916 if (reflected_kernel == (KernelInfo *) NULL)
3918 RotateKernelInfo(reflected_kernel,180);
3924 /* Loops around more primitive morpholgy methods
3925 ** erose, dilate, open, close, smooth, edge, etc...
3927 /* Loop 1: iterate the compound method */
3930 while ( method_loop < method_limit && method_changed > 0 ) {
3934 /* Loop 2: iterate over each kernel in a multi-kernel list */
3935 norm_kernel = (KernelInfo *) kernel;
3936 this_kernel = (KernelInfo *) kernel;
3937 rflt_kernel = reflected_kernel;
3940 while ( norm_kernel != NULL ) {
3942 /* Loop 3: Compound Morphology Staging - Select Primative to apply */
3943 stage_loop = 0; /* the compound morphology stage number */
3944 while ( stage_loop < stage_limit ) {
3945 stage_loop++; /* The stage of the compound morphology */
3947 /* Select primitive morphology for this stage of compound method */
3948 this_kernel = norm_kernel; /* default use unreflected kernel */
3949 primitive = method; /* Assume method is a primitive */
3951 case ErodeMorphology: /* just erode */
3952 case EdgeInMorphology: /* erode and image difference */
3953 primitive = ErodeMorphology;
3955 case DilateMorphology: /* just dilate */
3956 case EdgeOutMorphology: /* dilate and image difference */
3957 primitive = DilateMorphology;
3959 case OpenMorphology: /* erode then dialate */
3960 case TopHatMorphology: /* open and image difference */
3961 primitive = ErodeMorphology;
3962 if ( stage_loop == 2 )
3963 primitive = DilateMorphology;
3965 case OpenIntensityMorphology:
3966 primitive = ErodeIntensityMorphology;
3967 if ( stage_loop == 2 )
3968 primitive = DilateIntensityMorphology;
3970 case CloseMorphology: /* dilate, then erode */
3971 case BottomHatMorphology: /* close and image difference */
3972 this_kernel = rflt_kernel; /* use the reflected kernel */
3973 primitive = DilateMorphology;
3974 if ( stage_loop == 2 )
3975 primitive = ErodeMorphology;
3977 case CloseIntensityMorphology:
3978 this_kernel = rflt_kernel; /* use the reflected kernel */
3979 primitive = DilateIntensityMorphology;
3980 if ( stage_loop == 2 )
3981 primitive = ErodeIntensityMorphology;
3983 case SmoothMorphology: /* open, close */
3984 switch ( stage_loop ) {
3985 case 1: /* start an open method, which starts with Erode */
3986 primitive = ErodeMorphology;
3988 case 2: /* now Dilate the Erode */
3989 primitive = DilateMorphology;
3991 case 3: /* Reflect kernel a close */
3992 this_kernel = rflt_kernel; /* use the reflected kernel */
3993 primitive = DilateMorphology;
3995 case 4: /* Finish the Close */
3996 this_kernel = rflt_kernel; /* use the reflected kernel */
3997 primitive = ErodeMorphology;
4001 case EdgeMorphology: /* dilate and erode difference */
4002 primitive = DilateMorphology;
4003 if ( stage_loop == 2 ) {
4004 save_image = curr_image; /* save the image difference */
4005 curr_image = (Image *) image;
4006 primitive = ErodeMorphology;
4009 case CorrelateMorphology:
4010 /* A Correlation is a Convolution with a reflected kernel.
4011 ** However a Convolution is a weighted sum using a reflected
4012 ** kernel. It may seem stange to convert a Correlation into a
4013 ** Convolution as the Correlation is the simplier method, but
4014 ** Convolution is much more commonly used, and it makes sense to
4015 ** implement it directly so as to avoid the need to duplicate the
4016 ** kernel when it is not required (which is typically the
4019 this_kernel = rflt_kernel; /* use the reflected kernel */
4020 primitive = ConvolveMorphology;
4025 assert( this_kernel != (KernelInfo *) NULL );
4027 /* Extra information for debugging compound operations */
4028 if ( IfMagickTrue(verbose) ) {
4029 if ( stage_limit > 1 )
4030 (void) FormatLocaleString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ",
4031 CommandOptionToMnemonic(MagickMorphologyOptions,method),(double)
4032 method_loop,(double) stage_loop);
4033 else if ( primitive != method )
4034 (void) FormatLocaleString(v_info, MaxTextExtent, "%s:%.20g -> ",
4035 CommandOptionToMnemonic(MagickMorphologyOptions, method),(double)
4041 /* Loop 4: Iterate the kernel with primitive */
4045 while ( kernel_loop < kernel_limit && changed > 0 ) {
4046 kernel_loop++; /* the iteration of this kernel */
4048 /* Create a clone as the destination image, if not yet defined */
4049 if ( work_image == (Image *) NULL )
4051 work_image=CloneImage(image,0,0,MagickTrue,exception);
4052 if (work_image == (Image *) NULL)
4054 if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse)
4056 /* work_image->type=image->type; ??? */
4059 /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
4061 changed = MorphologyPrimitive(curr_image, work_image, primitive,
4062 this_kernel, bias, exception);
4064 if ( IfMagickTrue(verbose) ) {
4065 if ( kernel_loop > 1 )
4066 (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */
4067 (void) (void) FormatLocaleFile(stderr,
4068 "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
4069 v_info,CommandOptionToMnemonic(MagickMorphologyOptions,
4070 primitive),(this_kernel == rflt_kernel ) ? "*" : "",
4071 (double) (method_loop+kernel_loop-1),(double) kernel_number,
4072 (double) count,(double) changed);
4076 kernel_changed += changed;
4077 method_changed += changed;
4079 /* prepare next loop */
4080 { Image *tmp = work_image; /* swap images for iteration */
4081 work_image = curr_image;
4084 if ( work_image == image )
4085 work_image = (Image *) NULL; /* replace input 'image' */
4087 } /* End Loop 4: Iterate the kernel with primitive */
4089 if ( IfMagickTrue(verbose) && kernel_changed != (size_t)changed )
4090 (void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed);
4091 if ( IfMagickTrue(verbose) && stage_loop < stage_limit )
4092 (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */
4095 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
4096 (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
4097 (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image);
4098 (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image);
4099 (void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
4102 } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
4104 /* Final Post-processing for some Compound Methods
4106 ** The removal of any 'Sync' channel flag in the Image Compositon
4107 ** below ensures the methematical compose method is applied in a
4108 ** purely mathematical way, and only to the selected channels.
4109 ** Turn off SVG composition 'alpha blending'.
4112 case EdgeOutMorphology:
4113 case EdgeInMorphology:
4114 case TopHatMorphology:
4115 case BottomHatMorphology:
4116 if ( IfMagickTrue(verbose) )
4117 (void) FormatLocaleFile(stderr,
4118 "\n%s: Difference with original image",CommandOptionToMnemonic(
4119 MagickMorphologyOptions, method) );
4120 (void) CompositeImage(curr_image,image,DifferenceCompositeOp,
4121 MagickTrue,0,0,exception);
4123 case EdgeMorphology:
4124 if ( IfMagickTrue(verbose) )
4125 (void) FormatLocaleFile(stderr,
4126 "\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic(
4127 MagickMorphologyOptions, method) );
4128 (void) CompositeImage(curr_image,save_image,DifferenceCompositeOp,
4129 MagickTrue,0,0,exception);
4130 save_image = DestroyImage(save_image); /* finished with save image */
4136 /* multi-kernel handling: re-iterate, or compose results */
4137 if ( kernel->next == (KernelInfo *) NULL )
4138 rslt_image = curr_image; /* just return the resulting image */
4139 else if ( rslt_compose == NoCompositeOp )
4140 { if ( IfMagickTrue(verbose) ) {
4141 if ( this_kernel->next != (KernelInfo *) NULL )
4142 (void) FormatLocaleFile(stderr, " (re-iterate)");
4144 (void) FormatLocaleFile(stderr, " (done)");
4146 rslt_image = curr_image; /* return result, and re-iterate */
4148 else if ( rslt_image == (Image *) NULL)
4149 { if ( IfMagickTrue(verbose) )
4150 (void) FormatLocaleFile(stderr, " (save for compose)");
4151 rslt_image = curr_image;
4152 curr_image = (Image *) image; /* continue with original image */
4155 { /* Add the new 'current' result to the composition
4157 ** The removal of any 'Sync' channel flag in the Image Compositon
4158 ** below ensures the methematical compose method is applied in a
4159 ** purely mathematical way, and only to the selected channels.
4160 ** IE: Turn off SVG composition 'alpha blending'.
4162 if ( IfMagickTrue(verbose) )
4163 (void) FormatLocaleFile(stderr, " (compose \"%s\")",
4164 CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) );
4165 (void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue,
4167 curr_image = DestroyImage(curr_image);
4168 curr_image = (Image *) image; /* continue with original image */
4170 if ( IfMagickTrue(verbose) )
4171 (void) FormatLocaleFile(stderr, "\n");
4173 /* loop to the next kernel in a multi-kernel list */
4174 norm_kernel = norm_kernel->next;
4175 if ( rflt_kernel != (KernelInfo *) NULL )
4176 rflt_kernel = rflt_kernel->next;
4178 } /* End Loop 2: Loop over each kernel */
4180 } /* End Loop 1: compound method interation */
4184 /* Yes goto's are bad, but it makes cleanup lot more efficient */
4186 if ( curr_image == rslt_image )
4187 curr_image = (Image *) NULL;
4188 if ( rslt_image != (Image *) NULL )
4189 rslt_image = DestroyImage(rslt_image);
4191 if ( curr_image == rslt_image || curr_image == image )
4192 curr_image = (Image *) NULL;
4193 if ( curr_image != (Image *) NULL )
4194 curr_image = DestroyImage(curr_image);
4195 if ( work_image != (Image *) NULL )
4196 work_image = DestroyImage(work_image);
4197 if ( save_image != (Image *) NULL )
4198 save_image = DestroyImage(save_image);
4199 if ( reflected_kernel != (KernelInfo *) NULL )
4200 reflected_kernel = DestroyKernelInfo(reflected_kernel);
4206 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4210 % M o r p h o l o g y I m a g e %
4214 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4216 % MorphologyImage() applies a user supplied kernel to the image
4217 % according to the given mophology method.
4219 % This function applies any and all user defined settings before calling
4220 % the above internal function MorphologyApply().
4222 % User defined settings include...
4223 % * Output Bias for Convolution and correlation ("-define convolve:bias=??")
4224 % * Kernel Scale/normalize settings ("-define convolve:scale=??")
4225 % This can also includes the addition of a scaled unity kernel.
4226 % * Show Kernel being applied ("-define showkernel=1")
4228 % Other operators that do not want user supplied options interfering,
4229 % especially "convolve:bias" and "showkernel" should use MorphologyApply()
4232 % The format of the MorphologyImage method is:
4234 % Image *MorphologyImage(const Image *image,MorphologyMethod method,
4235 % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
4237 % A description of each parameter follows:
4239 % o image: the image.
4241 % o method: the morphology method to be applied.
4243 % o iterations: apply the operation this many times (or no change).
4244 % A value of -1 means loop until no change found.
4245 % How this is applied may depend on the morphology method.
4246 % Typically this is a value of 1.
4248 % o kernel: An array of double representing the morphology kernel.
4249 % Warning: kernel may be normalized for the Convolve method.
4251 % o exception: return any errors or warnings in this structure.
4254 MagickExport Image *MorphologyImage(const Image *image,
4255 const MorphologyMethod method,const ssize_t iterations,
4256 const KernelInfo *kernel,ExceptionInfo *exception)
4270 curr_kernel = (KernelInfo *) kernel;
4272 compose = (ssize_t)UndefinedCompositeOp; /* use default for method */
4274 /* Apply Convolve/Correlate Normalization and Scaling Factors.
4275 * This is done BEFORE the ShowKernelInfo() function is called so that
4276 * users can see the results of the 'option:convolve:scale' option.
4278 if ( method == ConvolveMorphology || method == CorrelateMorphology ) {
4282 /* Get the bias value as it will be needed */
4283 artifact = GetImageArtifact(image,"convolve:bias");
4284 if ( artifact != (const char *) NULL) {
4285 if (IfMagickFalse(IsGeometry(artifact)))
4286 (void) ThrowMagickException(exception,GetMagickModule(),
4287 OptionWarning,"InvalidSetting","'%s' '%s'",
4288 "convolve:bias",artifact);
4290 bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0);
4293 /* Scale kernel according to user wishes */
4294 artifact = GetImageArtifact(image,"convolve:scale");
4295 if ( artifact != (const char *)NULL ) {
4296 if (IfMagickFalse(IsGeometry(artifact)))
4297 (void) ThrowMagickException(exception,GetMagickModule(),
4298 OptionWarning,"InvalidSetting","'%s' '%s'",
4299 "convolve:scale",artifact);
4301 if ( curr_kernel == kernel )
4302 curr_kernel = CloneKernelInfo(kernel);
4303 if (curr_kernel == (KernelInfo *) NULL)
4304 return((Image *) NULL);
4305 ScaleGeometryKernelInfo(curr_kernel, artifact);
4310 /* display the (normalized) kernel via stderr */
4311 if ( IfStringTrue(GetImageArtifact(image,"showkernel"))
4312 || IfStringTrue(GetImageArtifact(image,"convolve:showkernel"))
4313 || IfStringTrue(GetImageArtifact(image,"morphology:showkernel")) )
4314 ShowKernelInfo(curr_kernel);
4316 /* Override the default handling of multi-kernel morphology results
4317 * If 'Undefined' use the default method
4318 * If 'None' (default for 'Convolve') re-iterate previous result
4319 * Otherwise merge resulting images using compose method given.
4320 * Default for 'HitAndMiss' is 'Lighten'.
4327 artifact = GetImageArtifact(image,"morphology:compose");
4328 if ( artifact != (const char *) NULL) {
4329 parse=ParseCommandOption(MagickComposeOptions,
4330 MagickFalse,artifact);
4332 (void) ThrowMagickException(exception,GetMagickModule(),
4333 OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'",
4334 "morphology:compose",artifact);
4336 compose=(CompositeOperator)parse;
4339 /* Apply the Morphology */
4340 morphology_image = MorphologyApply(image,method,iterations,
4341 curr_kernel,compose,bias,exception);
4343 /* Cleanup and Exit */
4344 if ( curr_kernel != kernel )
4345 curr_kernel=DestroyKernelInfo(curr_kernel);
4346 return(morphology_image);
4350 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4354 + R o t a t e K e r n e l I n f o %
4358 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4360 % RotateKernelInfo() rotates the kernel by the angle given.
4362 % Currently it is restricted to 90 degree angles, of either 1D kernels
4363 % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
4364 % It will ignore usless rotations for specific 'named' built-in kernels.
4366 % The format of the RotateKernelInfo method is:
4368 % void RotateKernelInfo(KernelInfo *kernel, double angle)
4370 % A description of each parameter follows:
4372 % o kernel: the Morphology/Convolution kernel
4374 % o angle: angle to rotate in degrees
4376 % This function is currently internal to this module only, but can be exported
4377 % to other modules if needed.
4379 static void RotateKernelInfo(KernelInfo *kernel, double angle)
4381 /* angle the lower kernels first */
4382 if ( kernel->next != (KernelInfo *) NULL)
4383 RotateKernelInfo(kernel->next, angle);
4385 /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
4387 ** TODO: expand beyond simple 90 degree rotates, flips and flops
4390 /* Modulus the angle */
4391 angle = fmod(angle, 360.0);
4395 if ( 337.5 < angle || angle <= 22.5 )
4396 return; /* Near zero angle - no change! - At least not at this time */
4398 /* Handle special cases */
4399 switch (kernel->type) {
4400 /* These built-in kernels are cylindrical kernels, rotating is useless */
4401 case GaussianKernel:
4406 case LaplacianKernel:
4407 case ChebyshevKernel:
4408 case ManhattanKernel:
4409 case EuclideanKernel:
4412 /* These may be rotatable at non-90 angles in the future */
4413 /* but simply rotating them in multiples of 90 degrees is useless */
4420 /* These only allows a +/-90 degree rotation (by transpose) */
4421 /* A 180 degree rotation is useless */
4423 if ( 135.0 < angle && angle <= 225.0 )
4425 if ( 225.0 < angle && angle <= 315.0 )
4432 /* Attempt rotations by 45 degrees -- 3x3 kernels only */
4433 if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
4435 if ( kernel->width == 3 && kernel->height == 3 )
4436 { /* Rotate a 3x3 square by 45 degree angle */
4437 MagickRealType t = kernel->values[0];
4438 kernel->values[0] = kernel->values[3];
4439 kernel->values[3] = kernel->values[6];
4440 kernel->values[6] = kernel->values[7];
4441 kernel->values[7] = kernel->values[8];
4442 kernel->values[8] = kernel->values[5];
4443 kernel->values[5] = kernel->values[2];
4444 kernel->values[2] = kernel->values[1];
4445 kernel->values[1] = t;
4446 /* rotate non-centered origin */
4447 if ( kernel->x != 1 || kernel->y != 1 ) {
4449 x = (ssize_t) kernel->x-1;
4450 y = (ssize_t) kernel->y-1;
4451 if ( x == y ) x = 0;
4452 else if ( x == 0 ) x = -y;
4453 else if ( x == -y ) y = 0;
4454 else if ( y == 0 ) y = x;
4455 kernel->x = (ssize_t) x+1;
4456 kernel->y = (ssize_t) y+1;
4458 angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */
4459 kernel->angle = fmod(kernel->angle+45.0, 360.0);
4462 perror("Unable to rotate non-3x3 kernel by 45 degrees");
4464 if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 )
4466 if ( kernel->width == 1 || kernel->height == 1 )
4467 { /* Do a transpose of a 1 dimensional kernel,
4468 ** which results in a fast 90 degree rotation of some type.
4472 t = (ssize_t) kernel->width;
4473 kernel->width = kernel->height;
4474 kernel->height = (size_t) t;
4476 kernel->x = kernel->y;
4478 if ( kernel->width == 1 ) {
4479 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
4480 kernel->angle = fmod(kernel->angle+90.0, 360.0);
4482 angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */
4483 kernel->angle = fmod(kernel->angle+270.0, 360.0);
4486 else if ( kernel->width == kernel->height )
4487 { /* Rotate a square array of values by 90 degrees */
4493 for( i=0, x=kernel->width-1; i<=x; i++, x--)
4494 for( j=0, y=kernel->height-1; j<y; j++, y--)
4495 { t = k[i+j*kernel->width];
4496 k[i+j*kernel->width] = k[j+x*kernel->width];
4497 k[j+x*kernel->width] = k[x+y*kernel->width];
4498 k[x+y*kernel->width] = k[y+i*kernel->width];
4499 k[y+i*kernel->width] = t;
4502 /* rotate the origin - relative to center of array */
4503 { register ssize_t x,y;
4504 x = (ssize_t) (kernel->x*2-kernel->width+1);
4505 y = (ssize_t) (kernel->y*2-kernel->height+1);
4506 kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2;
4507 kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2;
4509 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
4510 kernel->angle = fmod(kernel->angle+90.0, 360.0);
4513 perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
4515 if ( 135.0 < angle && angle <= 225.0 )
4517 /* For a 180 degree rotation - also know as a reflection
4518 * This is actually a very very common operation!
4519 * Basically all that is needed is a reversal of the kernel data!
4520 * And a reflection of the origon
4533 j=(ssize_t) (kernel->width*kernel->height-1);
4534 for (i=0; i < j; i++, j--)
4535 t=k[i], k[i]=k[j], k[j]=t;
4537 kernel->x = (ssize_t) kernel->width - kernel->x - 1;
4538 kernel->y = (ssize_t) kernel->height - kernel->y - 1;
4539 angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */
4540 kernel->angle = fmod(kernel->angle+180.0, 360.0);
4542 /* At this point angle should at least between -45 (315) and +45 degrees
4543 * In the future some form of non-orthogonal angled rotates could be
4544 * performed here, posibily with a linear kernel restriction.
4551 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4555 % S c a l e G e o m e t r y K e r n e l I n f o %
4559 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4561 % ScaleGeometryKernelInfo() takes a geometry argument string, typically
4562 % provided as a "-set option:convolve:scale {geometry}" user setting,
4563 % and modifies the kernel according to the parsed arguments of that setting.
4565 % The first argument (and any normalization flags) are passed to
4566 % ScaleKernelInfo() to scale/normalize the kernel. The second argument
4567 % is then passed to UnityAddKernelInfo() to add a scled unity kernel
4568 % into the scaled/normalized kernel.
4570 % The format of the ScaleGeometryKernelInfo method is:
4572 % void ScaleGeometryKernelInfo(KernelInfo *kernel,
4573 % const double scaling_factor,const MagickStatusType normalize_flags)
4575 % A description of each parameter follows:
4577 % o kernel: the Morphology/Convolution kernel to modify
4580 % The geometry string to parse, typically from the user provided
4581 % "-set option:convolve:scale {geometry}" setting.
4584 MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
4585 const char *geometry)
4594 SetGeometryInfo(&args);
4595 flags = ParseGeometry(geometry, &args);
4598 /* For Debugging Geometry Input */
4599 (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
4600 flags, args.rho, args.sigma, args.xi, args.psi );
4603 if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/
4604 args.rho *= 0.01, args.sigma *= 0.01;
4606 if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */
4608 if ( (flags & SigmaValue) == 0 )
4611 /* Scale/Normalize the input kernel */
4612 ScaleKernelInfo(kernel, args.rho, flags);
4614 /* Add Unity Kernel, for blending with original */
4615 if ( (flags & SigmaValue) != 0 )
4616 UnityAddKernelInfo(kernel, args.sigma);
4621 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4625 % S c a l e K e r n e l I n f o %
4629 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4631 % ScaleKernelInfo() scales the given kernel list by the given amount, with or
4632 % without normalization of the sum of the kernel values (as per given flags).
4634 % By default (no flags given) the values within the kernel is scaled
4635 % directly using given scaling factor without change.
4637 % If either of the two 'normalize_flags' are given the kernel will first be
4638 % normalized and then further scaled by the scaling factor value given.
4640 % Kernel normalization ('normalize_flags' given) is designed to ensure that
4641 % any use of the kernel scaling factor with 'Convolve' or 'Correlate'
4642 % morphology methods will fall into -1.0 to +1.0 range. Note that for
4643 % non-HDRI versions of IM this may cause images to have any negative results
4644 % clipped, unless some 'bias' is used.
4646 % More specifically. Kernels which only contain positive values (such as a
4647 % 'Gaussian' kernel) will be scaled so that those values sum to +1.0,
4648 % ensuring a 0.0 to +1.0 output range for non-HDRI images.
4650 % For Kernels that contain some negative values, (such as 'Sharpen' kernels)
4651 % the kernel will be scaled by the absolute of the sum of kernel values, so
4652 % that it will generally fall within the +/- 1.0 range.
4654 % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
4655 % will be scaled by just the sum of the postive values, so that its output
4656 % range will again fall into the +/- 1.0 range.
4658 % For special kernels designed for locating shapes using 'Correlate', (often
4659 % only containing +1 and -1 values, representing foreground/brackground
4660 % matching) a special normalization method is provided to scale the positive
4661 % values separately to those of the negative values, so the kernel will be
4662 % forced to become a zero-sum kernel better suited to such searches.
4664 % WARNING: Correct normalization of the kernel assumes that the '*_range'
4665 % attributes within the kernel structure have been correctly set during the
4668 % NOTE: The values used for 'normalize_flags' have been selected specifically
4669 % to match the use of geometry options, so that '!' means NormalizeValue, '^'
4670 % means CorrelateNormalizeValue. All other GeometryFlags values are ignored.
4672 % The format of the ScaleKernelInfo method is:
4674 % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
4675 % const MagickStatusType normalize_flags )
4677 % A description of each parameter follows:
4679 % o kernel: the Morphology/Convolution kernel
4682 % multiply all values (after normalization) by this factor if not
4683 % zero. If the kernel is normalized regardless of any flags.
4685 % o normalize_flags:
4686 % GeometryFlags defining normalization method to use.
4687 % specifically: NormalizeValue, CorrelateNormalizeValue,
4688 % and/or PercentValue
4691 MagickExport void ScaleKernelInfo(KernelInfo *kernel,
4692 const double scaling_factor,const GeometryFlags normalize_flags)
4701 /* do the other kernels in a multi-kernel list first */
4702 if ( kernel->next != (KernelInfo *) NULL)
4703 ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
4705 /* Normalization of Kernel */
4707 if ( (normalize_flags&NormalizeValue) != 0 ) {
4708 if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon )
4709 /* non-zero-summing kernel (generally positive) */
4710 pos_scale = fabs(kernel->positive_range + kernel->negative_range);
4712 /* zero-summing kernel */
4713 pos_scale = kernel->positive_range;
4715 /* Force kernel into a normalized zero-summing kernel */
4716 if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
4717 pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon )
4718 ? kernel->positive_range : 1.0;
4719 neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon )
4720 ? -kernel->negative_range : 1.0;
4723 neg_scale = pos_scale;
4725 /* finialize scaling_factor for positive and negative components */
4726 pos_scale = scaling_factor/pos_scale;
4727 neg_scale = scaling_factor/neg_scale;
4729 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
4730 if ( ! IsNan(kernel->values[i]) )
4731 kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
4733 /* convolution output range */
4734 kernel->positive_range *= pos_scale;
4735 kernel->negative_range *= neg_scale;
4736 /* maximum and minimum values in kernel */
4737 kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
4738 kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
4740 /* swap kernel settings if user's scaling factor is negative */
4741 if ( scaling_factor < MagickEpsilon ) {
4743 t = kernel->positive_range;
4744 kernel->positive_range = kernel->negative_range;
4745 kernel->negative_range = t;
4746 t = kernel->maximum;
4747 kernel->maximum = kernel->minimum;
4748 kernel->minimum = 1;
4755 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4759 % S h o w K e r n e l I n f o %
4763 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4765 % ShowKernelInfo() outputs the details of the given kernel defination to
4766 % standard error, generally due to a users 'showkernel' option request.
4768 % The format of the ShowKernel method is:
4770 % void ShowKernelInfo(const KernelInfo *kernel)
4772 % A description of each parameter follows:
4774 % o kernel: the Morphology/Convolution kernel
4777 MagickPrivate void ShowKernelInfo(const KernelInfo *kernel)
4785 for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) {
4787 (void) FormatLocaleFile(stderr, "Kernel");
4788 if ( kernel->next != (KernelInfo *) NULL )
4789 (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c );
4790 (void) FormatLocaleFile(stderr, " \"%s",
4791 CommandOptionToMnemonic(MagickKernelOptions, k->type) );
4792 if ( fabs(k->angle) > MagickEpsilon )
4793 (void) FormatLocaleFile(stderr, "@%lg", k->angle);
4794 (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long)
4795 k->width,(unsigned long) k->height,(long) k->x,(long) k->y);
4796 (void) FormatLocaleFile(stderr,
4797 " with values from %.*lg to %.*lg\n",
4798 GetMagickPrecision(), k->minimum,
4799 GetMagickPrecision(), k->maximum);
4800 (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg",
4801 GetMagickPrecision(), k->negative_range,
4802 GetMagickPrecision(), k->positive_range);
4803 if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
4804 (void) FormatLocaleFile(stderr, " (Zero-Summing)\n");
4805 else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
4806 (void) FormatLocaleFile(stderr, " (Normalized)\n");
4808 (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n",
4809 GetMagickPrecision(), k->positive_range+k->negative_range);
4810 for (i=v=0; v < k->height; v++) {
4811 (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v );
4812 for (u=0; u < k->width; u++, i++)
4813 if ( IsNan(k->values[i]) )
4814 (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan");
4816 (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3,
4817 GetMagickPrecision(), k->values[i]);
4818 (void) FormatLocaleFile(stderr,"\n");
4824 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4828 % U n i t y A d d K e r n a l I n f o %
4832 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4834 % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
4835 % to the given pre-scaled and normalized Kernel. This in effect adds that
4836 % amount of the original image into the resulting convolution kernel. This
4837 % value is usually provided by the user as a percentage value in the
4838 % 'convolve:scale' setting.
4840 % The resulting effect is to convert the defined kernels into blended
4841 % soft-blurs, unsharp kernels or into sharpening kernels.
4843 % The format of the UnityAdditionKernelInfo method is:
4845 % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
4847 % A description of each parameter follows:
4849 % o kernel: the Morphology/Convolution kernel
4852 % scaling factor for the unity kernel to be added to
4856 MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
4859 /* do the other kernels in a multi-kernel list first */
4860 if ( kernel->next != (KernelInfo *) NULL)
4861 UnityAddKernelInfo(kernel->next, scale);
4863 /* Add the scaled unity kernel to the existing kernel */
4864 kernel->values[kernel->x+kernel->y*kernel->width] += scale;
4865 CalcKernelMetaData(kernel); /* recalculate the meta-data */
4871 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4875 % Z e r o K e r n e l N a n s %
4879 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4881 % ZeroKernelNans() replaces any special 'nan' value that may be present in
4882 % the kernel with a zero value. This is typically done when the kernel will
4883 % be used in special hardware (GPU) convolution processors, to simply
4886 % The format of the ZeroKernelNans method is:
4888 % void ZeroKernelNans (KernelInfo *kernel)
4890 % A description of each parameter follows:
4892 % o kernel: the Morphology/Convolution kernel
4895 MagickPrivate void ZeroKernelNans(KernelInfo *kernel)
4900 /* do the other kernels in a multi-kernel list first */
4901 if ( kernel->next != (KernelInfo *) NULL)
4902 ZeroKernelNans(kernel->next);
4904 for (i=0; i < (kernel->width*kernel->height); i++)
4905 if ( IsNan(kernel->values[i]) )
4906 kernel->values[i] = 0.0;