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/token.h"
82 #include "MagickCore/utility.h"
83 #include "MagickCore/utility-private.h"
87 ** The following test is for special floating point numbers of value NaN (not
88 ** a number), that may be used within a Kernel Definition. NaN's are defined
89 ** as part of the IEEE standard for floating point number representation.
91 ** These are used as a Kernel value to mean that this kernel position is not
92 ** part of the kernel neighbourhood for convolution or morphology processing,
93 ** and thus should be ignored. This allows the use of 'shaped' kernels.
95 ** The special properity that two NaN's are never equal, even if they are from
96 ** the same variable allow you to test if a value is special NaN value.
98 ** This macro IsNaN() is thus is only true if the value given is NaN.
100 #define IsNan(a) ((a)!=(a))
103 Other global definitions used by module.
105 static inline double MagickMin(const double x,const double y)
107 return( x < y ? x : y);
109 static inline double MagickMax(const double x,const double y)
111 return( x > y ? x : y);
113 #define Minimize(assign,value) assign=MagickMin(assign,value)
114 #define Maximize(assign,value) assign=MagickMax(assign,value)
116 /* Currently these are only internal to this module */
118 CalcKernelMetaData(KernelInfo *),
119 ExpandMirrorKernelInfo(KernelInfo *),
120 ExpandRotateKernelInfo(KernelInfo *, const double),
121 RotateKernelInfo(KernelInfo *, double);
124 /* Quick function to find last kernel in a kernel list */
125 static inline KernelInfo *LastKernelInfo(KernelInfo *kernel)
127 while (kernel->next != (KernelInfo *) NULL)
128 kernel = kernel->next;
133 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
137 % A c q u i r e K e r n e l I n f o %
141 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
143 % AcquireKernelInfo() takes the given string (generally supplied by the
144 % user) and converts it into a Morphology/Convolution Kernel. This allows
145 % users to specify a kernel from a number of pre-defined kernels, or to fully
146 % specify their own kernel for a specific Convolution or Morphology
149 % The kernel so generated can be any rectangular array of floating point
150 % values (doubles) with the 'control point' or 'pixel being affected'
151 % anywhere within that array of values.
153 % Previously IM was restricted to a square of odd size using the exact
154 % center as origin, this is no longer the case, and any rectangular kernel
155 % with any value being declared the origin. This in turn allows the use of
156 % highly asymmetrical kernels.
158 % The floating point values in the kernel can also include a special value
159 % known as 'nan' or 'not a number' to indicate that this value is not part
160 % of the kernel array. This allows you to shaped the kernel within its
161 % rectangular area. That is 'nan' values provide a 'mask' for the kernel
162 % shape. However at least one non-nan value must be provided for correct
163 % working of a kernel.
165 % The returned kernel should be freed using the DestroyKernelInfo() when you
166 % are finished with it. Do not free this memory yourself.
168 % Input kernel defintion strings can consist of any of three types.
171 % Select from one of the built in kernels, using the name and
172 % geometry arguments supplied. See AcquireKernelBuiltIn()
174 % "WxH[+X+Y][@><]:num, num, num ..."
175 % a kernel of size W by H, with W*H floating point numbers following.
176 % the 'center' can be optionally be defined at +X+Y (such that +0+0
177 % is top left corner). If not defined the pixel in the center, for
178 % odd sizes, or to the immediate top or left of center for even sizes
179 % is automatically selected.
181 % "num, num, num, num, ..."
182 % list of floating point numbers defining an 'old style' odd sized
183 % square kernel. At least 9 values should be provided for a 3x3
184 % square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc.
185 % Values can be space or comma separated. This is not recommended.
187 % You can define a 'list of kernels' which can be used by some morphology
188 % operators A list is defined as a semi-colon separated list kernels.
190 % " kernel ; kernel ; kernel ; "
192 % Any extra ';' characters, at start, end or between kernel defintions are
195 % The special flags will expand a single kernel, into a list of rotated
196 % kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree
197 % cyclic rotations, while a '>' will generate a list of 90-degree rotations.
198 % The '<' also exands using 90-degree rotates, but giving a 180-degree
199 % reflected kernel before the +/- 90-degree rotations, which can be important
200 % for Thinning operations.
202 % Note that 'name' kernels will start with an alphabetic character while the
203 % new kernel specification has a ':' character in its specification string.
204 % If neither is the case, it is assumed an old style of a simple list of
205 % numbers generating a odd-sized square kernel has been given.
207 % The format of the AcquireKernal method is:
209 % KernelInfo *AcquireKernelInfo(const char *kernel_string)
211 % A description of each parameter follows:
213 % o kernel_string: the Morphology/Convolution kernel wanted.
217 /* This was separated so that it could be used as a separate
218 ** array input handling function, such as for -color-matrix
220 static KernelInfo *ParseKernelArray(const char *kernel_string)
226 token[MaxTextExtent];
236 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
244 kernel=(KernelInfo *) AcquireQuantumMemory(1,sizeof(*kernel));
245 if (kernel == (KernelInfo *)NULL)
247 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
248 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
249 kernel->negative_range = kernel->positive_range = 0.0;
250 kernel->type = UserDefinedKernel;
251 kernel->next = (KernelInfo *) NULL;
252 kernel->signature = MagickSignature;
253 if (kernel_string == (const char *) NULL)
256 /* find end of this specific kernel definition string */
257 end = strchr(kernel_string, ';');
258 if ( end == (char *) NULL )
259 end = strchr(kernel_string, '\0');
261 /* clear flags - for Expanding kernel lists thorugh rotations */
264 /* Has a ':' in argument - New user kernel specification
265 FUTURE: this split on ':' could be done by StringToken()
267 p = strchr(kernel_string, ':');
268 if ( p != (char *) NULL && p < end)
270 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
271 memcpy(token, kernel_string, (size_t) (p-kernel_string));
272 token[p-kernel_string] = '\0';
273 SetGeometryInfo(&args);
274 flags = ParseGeometry(token, &args);
276 /* Size handling and checks of geometry settings */
277 if ( (flags & WidthValue) == 0 ) /* if no width then */
278 args.rho = args.sigma; /* then width = height */
279 if ( args.rho < 1.0 ) /* if width too small */
280 args.rho = 1.0; /* then width = 1 */
281 if ( args.sigma < 1.0 ) /* if height too small */
282 args.sigma = args.rho; /* then height = width */
283 kernel->width = (size_t)args.rho;
284 kernel->height = (size_t)args.sigma;
286 /* Offset Handling and Checks */
287 if ( args.xi < 0.0 || args.psi < 0.0 )
288 return(DestroyKernelInfo(kernel));
289 kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi
290 : (ssize_t) (kernel->width-1)/2;
291 kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi
292 : (ssize_t) (kernel->height-1)/2;
293 if ( kernel->x >= (ssize_t) kernel->width ||
294 kernel->y >= (ssize_t) kernel->height )
295 return(DestroyKernelInfo(kernel));
297 p++; /* advance beyond the ':' */
300 { /* ELSE - Old old specification, forming odd-square kernel */
301 /* count up number of values given */
302 p=(const char *) kernel_string;
303 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
304 p++; /* ignore "'" chars for convolve filter usage - Cristy */
305 for (i=0; p < end; i++)
307 GetMagickToken(p,&p,token);
309 GetMagickToken(p,&p,token);
311 /* set the size of the kernel - old sized square */
312 kernel->width = kernel->height= (size_t) sqrt((double) i+1.0);
313 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
314 p=(const char *) kernel_string;
315 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
316 p++; /* ignore "'" chars for convolve filter usage - Cristy */
319 /* Read in the kernel values from rest of input string argument */
320 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
321 kernel->height*sizeof(*kernel->values));
322 if (kernel->values == (MagickRealType *) NULL)
323 return(DestroyKernelInfo(kernel));
324 kernel->minimum = +MagickHuge;
325 kernel->maximum = -MagickHuge;
326 kernel->negative_range = kernel->positive_range = 0.0;
327 for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++)
329 GetMagickToken(p,&p,token);
331 GetMagickToken(p,&p,token);
332 if ( LocaleCompare("nan",token) == 0
333 || LocaleCompare("-",token) == 0 ) {
334 kernel->values[i] = nan; /* this value is not part of neighbourhood */
337 kernel->values[i] = StringToDouble(token,(char **) NULL);
338 ( kernel->values[i] < 0)
339 ? ( kernel->negative_range += kernel->values[i] )
340 : ( kernel->positive_range += kernel->values[i] );
341 Minimize(kernel->minimum, kernel->values[i]);
342 Maximize(kernel->maximum, kernel->values[i]);
346 /* sanity check -- no more values in kernel definition */
347 GetMagickToken(p,&p,token);
348 if ( *token != '\0' && *token != ';' && *token != '\'' )
349 return(DestroyKernelInfo(kernel));
352 /* this was the old method of handling a incomplete kernel */
353 if ( i < (ssize_t) (kernel->width*kernel->height) ) {
354 Minimize(kernel->minimum, kernel->values[i]);
355 Maximize(kernel->maximum, kernel->values[i]);
356 for ( ; i < (ssize_t) (kernel->width*kernel->height); i++)
357 kernel->values[i]=0.0;
360 /* Number of values for kernel was not enough - Report Error */
361 if ( i < (ssize_t) (kernel->width*kernel->height) )
362 return(DestroyKernelInfo(kernel));
365 /* check that we recieved at least one real (non-nan) value! */
366 if ( kernel->minimum == MagickHuge )
367 return(DestroyKernelInfo(kernel));
369 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */
370 ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */
371 else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
372 ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */
373 else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
374 ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */
379 static KernelInfo *ParseKernelName(const char *kernel_string)
382 token[MaxTextExtent];
400 /* Parse special 'named' kernel */
401 GetMagickToken(kernel_string,&p,token);
402 type=ParseCommandOption(MagickKernelOptions,MagickFalse,token);
403 if ( type < 0 || type == UserDefinedKernel )
404 return((KernelInfo *)NULL); /* not a valid named kernel */
406 while (((isspace((int) ((unsigned char) *p)) != 0) ||
407 (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
410 end = strchr(p, ';'); /* end of this kernel defintion */
411 if ( end == (char *) NULL )
412 end = strchr(p, '\0');
414 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
415 memcpy(token, p, (size_t) (end-p));
417 SetGeometryInfo(&args);
418 flags = ParseGeometry(token, &args);
421 /* For Debugging Geometry Input */
422 (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
423 flags, args.rho, args.sigma, args.xi, args.psi );
426 /* special handling of missing values in input string */
428 /* Shape Kernel Defaults */
430 if ( (flags & WidthValue) == 0 )
431 args.rho = 1.0; /* Default scale = 1.0, zero is valid */
439 if ( (flags & HeightValue) == 0 )
440 args.sigma = 1.0; /* Default scale = 1.0, zero is valid */
443 if ( (flags & XValue) == 0 )
444 args.xi = 1.0; /* Default scale = 1.0, zero is valid */
446 case RectangleKernel: /* Rectangle - set size defaults */
447 if ( (flags & WidthValue) == 0 ) /* if no width then */
448 args.rho = args.sigma; /* then width = height */
449 if ( args.rho < 1.0 ) /* if width too small */
450 args.rho = 3; /* then width = 3 */
451 if ( args.sigma < 1.0 ) /* if height too small */
452 args.sigma = args.rho; /* then height = width */
453 if ( (flags & XValue) == 0 ) /* center offset if not defined */
454 args.xi = (double)(((ssize_t)args.rho-1)/2);
455 if ( (flags & YValue) == 0 )
456 args.psi = (double)(((ssize_t)args.sigma-1)/2);
458 /* Distance Kernel Defaults */
459 case ChebyshevKernel:
460 case ManhattanKernel:
461 case OctagonalKernel:
462 case EuclideanKernel:
463 if ( (flags & HeightValue) == 0 ) /* no distance scale */
464 args.sigma = 100.0; /* default distance scaling */
465 else if ( (flags & AspectValue ) != 0 ) /* '!' flag */
466 args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */
467 else if ( (flags & PercentValue ) != 0 ) /* '%' flag */
468 args.sigma *= QuantumRange/100.0; /* percentage of color range */
474 kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args);
475 if ( kernel == (KernelInfo *) NULL )
478 /* global expand to rotated kernel list - only for single kernels */
479 if ( kernel->next == (KernelInfo *) NULL ) {
480 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */
481 ExpandRotateKernelInfo(kernel, 45.0);
482 else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
483 ExpandRotateKernelInfo(kernel, 90.0);
484 else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
485 ExpandMirrorKernelInfo(kernel);
491 MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string)
499 token[MaxTextExtent];
507 if (kernel_string == (const char *) NULL)
508 return(ParseKernelArray(kernel_string));
513 while ( GetMagickToken(p,NULL,token), *token != '\0' ) {
515 /* ignore extra or multiple ';' kernel separators */
516 if ( *token != ';' ) {
518 /* tokens starting with alpha is a Named kernel */
519 if (isalpha((int) *token) != 0)
520 new_kernel = ParseKernelName(p);
521 else /* otherwise a user defined kernel array */
522 new_kernel = ParseKernelArray(p);
524 /* Error handling -- this is not proper error handling! */
525 if ( new_kernel == (KernelInfo *) NULL ) {
526 (void) FormatLocaleFile(stderr, "Failed to parse kernel number #%.20g\n",
527 (double) kernel_number);
528 if ( kernel != (KernelInfo *) NULL )
529 kernel=DestroyKernelInfo(kernel);
530 return((KernelInfo *) NULL);
533 /* initialise or append the kernel list */
534 if ( kernel == (KernelInfo *) NULL )
537 LastKernelInfo(kernel)->next = new_kernel;
540 /* look for the next kernel in list */
542 if ( p == (char *) NULL )
552 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
556 % A c q u i r e K e r n e l B u i l t I n %
560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
562 % AcquireKernelBuiltIn() returned one of the 'named' built-in types of
563 % kernels used for special purposes such as gaussian blurring, skeleton
564 % pruning, and edge distance determination.
566 % They take a KernelType, and a set of geometry style arguments, which were
567 % typically decoded from a user supplied string, or from a more complex
568 % Morphology Method that was requested.
570 % The format of the AcquireKernalBuiltIn method is:
572 % KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
573 % const GeometryInfo args)
575 % A description of each parameter follows:
577 % o type: the pre-defined type of kernel wanted
579 % o args: arguments defining or modifying the kernel
581 % Convolution Kernels
584 % The a No-Op or Scaling single element kernel.
586 % Gaussian:{radius},{sigma}
587 % Generate a two-dimensional gaussian kernel, as used by -gaussian.
588 % The sigma for the curve is required. The resulting kernel is
591 % If 'sigma' is zero, you get a single pixel on a field of zeros.
593 % NOTE: that the 'radius' is optional, but if provided can limit (clip)
594 % the final size of the resulting kernel to a square 2*radius+1 in size.
595 % The radius should be at least 2 times that of the sigma value, or
596 % sever clipping and aliasing may result. If not given or set to 0 the
597 % radius will be determined so as to produce the best minimal error
598 % result, which is usally much larger than is normally needed.
600 % LoG:{radius},{sigma}
601 % "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
602 % The supposed ideal edge detection, zero-summing kernel.
604 % An alturnative to this kernel is to use a "DoG" with a sigma ratio of
605 % approx 1.6 (according to wikipedia).
607 % DoG:{radius},{sigma1},{sigma2}
608 % "Difference of Gaussians" Kernel.
609 % As "Gaussian" but with a gaussian produced by 'sigma2' subtracted
610 % from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1.
611 % The result is a zero-summing kernel.
613 % Blur:{radius},{sigma}[,{angle}]
614 % Generates a 1 dimensional or linear gaussian blur, at the angle given
615 % (current restricted to orthogonal angles). If a 'radius' is given the
616 % kernel is clipped to a width of 2*radius+1. Kernel can be rotated
617 % by a 90 degree angle.
619 % If 'sigma' is zero, you get a single pixel on a field of zeros.
621 % Note that two convolutions with two "Blur" kernels perpendicular to
622 % each other, is equivalent to a far larger "Gaussian" kernel with the
623 % same sigma value, However it is much faster to apply. This is how the
624 % "-blur" operator actually works.
626 % Comet:{width},{sigma},{angle}
627 % Blur in one direction only, much like how a bright object leaves
628 % a comet like trail. The Kernel is actually half a gaussian curve,
629 % Adding two such blurs in opposite directions produces a Blur Kernel.
630 % Angle can be rotated in multiples of 90 degrees.
632 % Note that the first argument is the width of the kernel and not the
633 % radius of the kernel.
635 % # Still to be implemented...
639 % # Set kernel values using a resize filter, and given scale (sigma)
640 % # Cylindrical or Linear. Is this possible with an image?
643 % Named Constant Convolution Kernels
645 % All these are unscaled, zero-summing kernels by default. As such for
646 % non-HDRI version of ImageMagick some form of normalization, user scaling,
647 % and biasing the results is recommended, to prevent the resulting image
650 % The 3x3 kernels (most of these) can be circularly rotated in multiples of
651 % 45 degrees to generate the 8 angled varients of each of the kernels.
654 % Discrete Lapacian Kernels, (without normalization)
655 % Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood)
656 % Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood)
657 % Type 2 : 3x3 with center:4 edge:1 corner:-2
658 % Type 3 : 3x3 with center:4 edge:-2 corner:1
659 % Type 5 : 5x5 laplacian
660 % Type 7 : 7x7 laplacian
661 % Type 15 : 5x5 LoG (sigma approx 1.4)
662 % Type 19 : 9x9 LoG (sigma approx 1.4)
665 % Sobel 'Edge' convolution kernel (3x3)
671 % Roberts convolution kernel (3x3)
677 % Prewitt Edge convolution kernel (3x3)
683 % Prewitt's "Compass" convolution kernel (3x3)
689 % Kirsch's "Compass" convolution kernel (3x3)
695 % Frei-Chen Edge Detector is based on a kernel that is similar to
696 % the Sobel Kernel, but is designed to be isotropic. That is it takes
697 % into account the distance of the diagonal in the kernel.
700 % | sqrt(2), 0, -sqrt(2) |
703 % FreiChen:{type},{angle}
705 % Frei-Chen Pre-weighted kernels...
707 % Type 0: default un-nomalized version shown above.
709 % Type 1: Orthogonal Kernel (same as type 11 below)
711 % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
714 % Type 2: Diagonal form of Kernel...
716 % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
719 % However this kernel is als at the heart of the FreiChen Edge Detection
720 % Process which uses a set of 9 specially weighted kernel. These 9
721 % kernels not be normalized, but directly applied to the image. The
722 % results is then added together, to produce the intensity of an edge in
723 % a specific direction. The square root of the pixel value can then be
724 % taken as the cosine of the edge, and at least 2 such runs at 90 degrees
725 % from each other, both the direction and the strength of the edge can be
728 % Type 10: All 9 of the following pre-weighted kernels...
730 % Type 11: | 1, 0, -1 |
731 % | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
734 % Type 12: | 1, sqrt(2), 1 |
735 % | 0, 0, 0 | / 2*sqrt(2)
738 % Type 13: | sqrt(2), -1, 0 |
739 % | -1, 0, 1 | / 2*sqrt(2)
742 % Type 14: | 0, 1, -sqrt(2) |
743 % | -1, 0, 1 | / 2*sqrt(2)
746 % Type 15: | 0, -1, 0 |
750 % Type 16: | 1, 0, -1 |
754 % Type 17: | 1, -2, 1 |
758 % Type 18: | -2, 1, -2 |
762 % Type 19: | 1, 1, 1 |
766 % The first 4 are for edge detection, the next 4 are for line detection
767 % and the last is to add a average component to the results.
769 % Using a special type of '-1' will return all 9 pre-weighted kernels
770 % as a multi-kernel list, so that you can use them directly (without
771 % normalization) with the special "-set option:morphology:compose Plus"
772 % setting to apply the full FreiChen Edge Detection Technique.
774 % If 'type' is large it will be taken to be an actual rotation angle for
775 % the default FreiChen (type 0) kernel. As such FreiChen:45 will look
776 % like a Sobel:45 but with 'sqrt(2)' instead of '2' values.
778 % WARNING: The above was layed out as per
779 % http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf
780 % But rotated 90 degrees so direction is from left rather than the top.
781 % I have yet to find any secondary confirmation of the above. The only
782 % other source found was actual source code at
783 % http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf
784 % Neigher paper defineds the kernels in a way that looks locical or
785 % correct when taken as a whole.
789 % Diamond:[{radius}[,{scale}]]
790 % Generate a diamond shaped kernel with given radius to the points.
791 % Kernel size will again be radius*2+1 square and defaults to radius 1,
792 % generating a 3x3 kernel that is slightly larger than a square.
794 % Square:[{radius}[,{scale}]]
795 % Generate a square shaped kernel of size radius*2+1, and defaulting
796 % to a 3x3 (radius 1).
798 % Octagon:[{radius}[,{scale}]]
799 % Generate octagonal shaped kernel of given radius and constant scale.
800 % Default radius is 3 producing a 7x7 kernel. A radius of 1 will result
801 % in "Diamond" kernel.
803 % Disk:[{radius}[,{scale}]]
804 % Generate a binary disk, thresholded at the radius given, the radius
805 % may be a float-point value. Final Kernel size is floor(radius)*2+1
806 % square. A radius of 5.3 is the default.
808 % NOTE: That a low radii Disk kernels produce the same results as
809 % many of the previously defined kernels, but differ greatly at larger
810 % radii. Here is a table of equivalences...
811 % "Disk:1" => "Diamond", "Octagon:1", or "Cross:1"
812 % "Disk:1.5" => "Square"
813 % "Disk:2" => "Diamond:2"
814 % "Disk:2.5" => "Octagon"
815 % "Disk:2.9" => "Square:2"
816 % "Disk:3.5" => "Octagon:3"
817 % "Disk:4.5" => "Octagon:4"
818 % "Disk:5.4" => "Octagon:5"
819 % "Disk:6.4" => "Octagon:6"
820 % All other Disk shapes are unique to this kernel, but because a "Disk"
821 % is more circular when using a larger radius, using a larger radius is
822 % preferred over iterating the morphological operation.
824 % Rectangle:{geometry}
825 % Simply generate a rectangle of 1's with the size given. You can also
826 % specify the location of the 'control point', otherwise the closest
827 % pixel to the center of the rectangle is selected.
829 % Properly centered and odd sized rectangles work the best.
831 % Symbol Dilation Kernels
833 % These kernel is not a good general morphological kernel, but is used
834 % more for highlighting and marking any single pixels in an image using,
835 % a "Dilate" method as appropriate.
837 % For the same reasons iterating these kernels does not produce the
838 % same result as using a larger radius for the symbol.
840 % Plus:[{radius}[,{scale}]]
841 % Cross:[{radius}[,{scale}]]
842 % Generate a kernel in the shape of a 'plus' or a 'cross' with
843 % a each arm the length of the given radius (default 2).
845 % NOTE: "plus:1" is equivalent to a "Diamond" kernel.
847 % Ring:{radius1},{radius2}[,{scale}]
848 % A ring of the values given that falls between the two radii.
849 % Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
850 % This is the 'edge' pixels of the default "Disk" kernel,
851 % More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
853 % Hit and Miss Kernels
855 % Peak:radius1,radius2
856 % Find any peak larger than the pixels the fall between the two radii.
857 % The default ring of pixels is as per "Ring".
859 % Find flat orthogonal edges of a binary shape
861 % Find 90 degree corners of a binary shape
863 % A special kernel to thin the 'outside' of diagonals
865 % Find end points of lines (for pruning a skeletion)
866 % Two types of lines ends (default to both) can be searched for
867 % Type 0: All line ends
868 % Type 1: single kernel for 4-conneected line ends
869 % Type 2: single kernel for simple line ends
871 % Find three line junctions (within a skeletion)
872 % Type 0: all line junctions
873 % Type 1: Y Junction kernel
874 % Type 2: Diagonal T Junction kernel
875 % Type 3: Orthogonal T Junction kernel
876 % Type 4: Diagonal X Junction kernel
877 % Type 5: Orthogonal + Junction kernel
879 % Find single pixel ridges or thin lines
880 % Type 1: Fine single pixel thick lines and ridges
881 % Type 2: Find two pixel thick lines and ridges
883 % Octagonal Thickening Kernel, to generate convex hulls of 45 degrees
885 % Traditional skeleton generating kernels.
886 % Type 1: Tradional Skeleton kernel (4 connected skeleton)
887 % Type 2: HIPR2 Skeleton kernel (8 connected skeleton)
888 % Type 3: Thinning skeleton based on a ressearch paper by
889 % Dan S. Bloomberg (Default Type)
891 % A huge variety of Thinning Kernels designed to preserve conectivity.
892 % many other kernel sets use these kernels as source definitions.
893 % Type numbers are 41-49, 81-89, 481, and 482 which are based on
894 % the super and sub notations used in the source research paper.
896 % Distance Measuring Kernels
898 % Different types of distance measuring methods, which are used with the
899 % a 'Distance' morphology method for generating a gradient based on
900 % distance from an edge of a binary shape, though there is a technique
901 % for handling a anti-aliased shape.
903 % See the 'Distance' Morphological Method, for information of how it is
906 % Chebyshev:[{radius}][x{scale}[%!]]
907 % Chebyshev Distance (also known as Tchebychev or Chessboard distance)
908 % is a value of one to any neighbour, orthogonal or diagonal. One why
909 % of thinking of it is the number of squares a 'King' or 'Queen' in
910 % chess needs to traverse reach any other position on a chess board.
911 % It results in a 'square' like distance function, but one where
912 % diagonals are given a value that is closer than expected.
914 % Manhattan:[{radius}][x{scale}[%!]]
915 % Manhattan Distance (also known as Rectilinear, City Block, or the Taxi
916 % Cab distance metric), it is the distance needed when you can only
917 % travel in horizontal or vertical directions only. It is the
918 % distance a 'Rook' in chess would have to travel, and results in a
919 % diamond like distances, where diagonals are further than expected.
921 % Octagonal:[{radius}][x{scale}[%!]]
922 % An interleving of Manhatten and Chebyshev metrics producing an
923 % increasing octagonally shaped distance. Distances matches those of
924 % the "Octagon" shaped kernel of the same radius. The minimum radius
925 % and default is 2, producing a 5x5 kernel.
927 % Euclidean:[{radius}][x{scale}[%!]]
928 % Euclidean distance is the 'direct' or 'as the crow flys' distance.
929 % However by default the kernel size only has a radius of 1, which
930 % limits the distance to 'Knight' like moves, with only orthogonal and
931 % diagonal measurements being correct. As such for the default kernel
932 % you will get octagonal like distance function.
934 % However using a larger radius such as "Euclidean:4" you will get a
935 % much smoother distance gradient from the edge of the shape. Especially
936 % if the image is pre-processed to include any anti-aliasing pixels.
937 % Of course a larger kernel is slower to use, and not always needed.
939 % The first three Distance Measuring Kernels will only generate distances
940 % of exact multiples of {scale} in binary images. As such you can use a
941 % scale of 1 without loosing any information. However you also need some
942 % scaling when handling non-binary anti-aliased shapes.
944 % The "Euclidean" Distance Kernel however does generate a non-integer
945 % fractional results, and as such scaling is vital even for binary shapes.
949 MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
950 const GeometryInfo *args)
963 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
965 /* Generate a new empty kernel if needed */
966 kernel=(KernelInfo *) NULL;
968 case UndefinedKernel: /* These should not call this function */
969 case UserDefinedKernel:
970 assert("Should not call this function" != (char *)NULL);
972 case LaplacianKernel: /* Named Descrete Convolution Kernels */
973 case SobelKernel: /* these are defined using other kernels */
979 case EdgesKernel: /* Hit and Miss kernels */
981 case DiagonalsKernel:
983 case LineJunctionsKernel:
985 case ConvexHullKernel:
988 break; /* A pre-generated kernel is not needed */
990 /* set to 1 to do a compile-time check that we haven't missed anything */
999 case RectangleKernel:
1006 case ChebyshevKernel:
1007 case ManhattanKernel:
1008 case OctangonalKernel:
1009 case EuclideanKernel:
1013 /* Generate the base Kernel Structure */
1014 kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
1015 if (kernel == (KernelInfo *) NULL)
1017 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
1018 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
1019 kernel->negative_range = kernel->positive_range = 0.0;
1020 kernel->type = type;
1021 kernel->next = (KernelInfo *) NULL;
1022 kernel->signature = MagickSignature;
1032 kernel->height = kernel->width = (size_t) 1;
1033 kernel->x = kernel->y = (ssize_t) 0;
1034 kernel->values=(MagickRealType *) AcquireAlignedMemory(1,
1035 sizeof(*kernel->values));
1036 if (kernel->values == (MagickRealType *) NULL)
1037 return(DestroyKernelInfo(kernel));
1038 kernel->maximum = kernel->values[0] = args->rho;
1042 case GaussianKernel:
1046 sigma = fabs(args->sigma),
1047 sigma2 = fabs(args->xi),
1050 if ( args->rho >= 1.0 )
1051 kernel->width = (size_t)args->rho*2+1;
1052 else if ( (type != DoGKernel) || (sigma >= sigma2) )
1053 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
1055 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
1056 kernel->height = kernel->width;
1057 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1058 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1059 kernel->height*sizeof(*kernel->values));
1060 if (kernel->values == (MagickRealType *) NULL)
1061 return(DestroyKernelInfo(kernel));
1063 /* WARNING: The following generates a 'sampled gaussian' kernel.
1064 * What we really want is a 'discrete gaussian' kernel.
1066 * How to do this is I don't know, but appears to be basied on the
1067 * Error Function 'erf()' (intergral of a gaussian)
1070 if ( type == GaussianKernel || type == DoGKernel )
1071 { /* Calculate a Gaussian, OR positive half of a DoG */
1072 if ( sigma > MagickEpsilon )
1073 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1074 B = (double) (1.0/(Magick2PI*sigma*sigma));
1075 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1076 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1077 kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
1079 else /* limiting case - a unity (normalized Dirac) kernel */
1080 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1081 kernel->width*kernel->height*sizeof(double));
1082 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1086 if ( type == DoGKernel )
1087 { /* Subtract a Negative Gaussian for "Difference of Gaussian" */
1088 if ( sigma2 > MagickEpsilon )
1089 { sigma = sigma2; /* simplify loop expressions */
1090 A = 1.0/(2.0*sigma*sigma);
1091 B = (double) (1.0/(Magick2PI*sigma*sigma));
1092 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1093 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1094 kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
1096 else /* limiting case - a unity (normalized Dirac) kernel */
1097 kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1100 if ( type == LoGKernel )
1101 { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
1102 if ( sigma > MagickEpsilon )
1103 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1104 B = (double) (1.0/(MagickPI*sigma*sigma*sigma*sigma));
1105 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1106 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1107 { R = ((double)(u*u+v*v))*A;
1108 kernel->values[i] = (1-R)*exp(-R)*B;
1111 else /* special case - generate a unity kernel */
1112 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1113 kernel->width*kernel->height*sizeof(double));
1114 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1118 /* Note the above kernels may have been 'clipped' by a user defined
1119 ** radius, producing a smaller (darker) kernel. Also for very small
1120 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1121 ** producing a very bright kernel.
1123 ** Normalization will still be needed.
1126 /* Normalize the 2D Gaussian Kernel
1128 ** NB: a CorrelateNormalize performs a normal Normalize if
1129 ** there are no negative values.
1131 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1132 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1138 sigma = fabs(args->sigma),
1141 if ( args->rho >= 1.0 )
1142 kernel->width = (size_t)args->rho*2+1;
1144 kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
1146 kernel->x = (ssize_t) (kernel->width-1)/2;
1148 kernel->negative_range = kernel->positive_range = 0.0;
1149 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1150 kernel->height*sizeof(*kernel->values));
1151 if (kernel->values == (MagickRealType *) NULL)
1152 return(DestroyKernelInfo(kernel));
1155 #define KernelRank 3
1156 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix).
1157 ** It generates a gaussian 3 times the width, and compresses it into
1158 ** the expected range. This produces a closer normalization of the
1159 ** resulting kernel, especially for very low sigma values.
1160 ** As such while wierd it is prefered.
1162 ** I am told this method originally came from Photoshop.
1164 ** A properly normalized curve is generated (apart from edge clipping)
1165 ** even though we later normalize the result (for edge clipping)
1166 ** to allow the correct generation of a "Difference of Blurs".
1170 v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */
1171 (void) ResetMagickMemory(kernel->values,0, (size_t)
1172 kernel->width*kernel->height*sizeof(double));
1173 /* Calculate a Positive 1D Gaussian */
1174 if ( sigma > MagickEpsilon )
1175 { sigma *= KernelRank; /* simplify loop expressions */
1176 alpha = 1.0/(2.0*sigma*sigma);
1177 beta= (double) (1.0/(MagickSQ2PI*sigma ));
1178 for ( u=-v; u <= v; u++) {
1179 kernel->values[(u+v)/KernelRank] +=
1180 exp(-((double)(u*u))*alpha)*beta;
1183 else /* special case - generate a unity kernel */
1184 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1186 /* Direct calculation without curve averaging */
1188 /* Calculate a Positive Gaussian */
1189 if ( sigma > MagickEpsilon )
1190 { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1191 beta = 1.0/(MagickSQ2PI*sigma);
1192 for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1193 kernel->values[i] = exp(-((double)(u*u))*alpha)*beta;
1195 else /* special case - generate a unity kernel */
1196 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1197 kernel->width*kernel->height*sizeof(double));
1198 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1201 /* Note the above kernel may have been 'clipped' by a user defined
1202 ** radius, producing a smaller (darker) kernel. Also for very small
1203 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1204 ** producing a very bright kernel.
1206 ** Normalization will still be needed.
1209 /* Normalize the 1D Gaussian Kernel
1211 ** NB: a CorrelateNormalize performs a normal Normalize if
1212 ** there are no negative values.
1214 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1215 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
1217 /* rotate the 1D kernel by given angle */
1218 RotateKernelInfo(kernel, args->xi );
1223 sigma = fabs(args->sigma),
1226 if ( args->rho < 1.0 )
1227 kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
1229 kernel->width = (size_t)args->rho;
1230 kernel->x = kernel->y = 0;
1232 kernel->negative_range = kernel->positive_range = 0.0;
1233 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1234 kernel->height*sizeof(*kernel->values));
1235 if (kernel->values == (MagickRealType *) NULL)
1236 return(DestroyKernelInfo(kernel));
1238 /* A comet blur is half a 1D gaussian curve, so that the object is
1239 ** blurred in one direction only. This may not be quite the right
1240 ** curve to use so may change in the future. The function must be
1241 ** normalised after generation, which also resolves any clipping.
1243 ** As we are normalizing and not subtracting gaussians,
1244 ** there is no need for a divisor in the gaussian formula
1246 ** It is less comples
1248 if ( sigma > MagickEpsilon )
1251 #define KernelRank 3
1252 v = (ssize_t) kernel->width*KernelRank; /* start/end points */
1253 (void) ResetMagickMemory(kernel->values,0, (size_t)
1254 kernel->width*sizeof(double));
1255 sigma *= KernelRank; /* simplify the loop expression */
1256 A = 1.0/(2.0*sigma*sigma);
1257 /* B = 1.0/(MagickSQ2PI*sigma); */
1258 for ( u=0; u < v; u++) {
1259 kernel->values[u/KernelRank] +=
1260 exp(-((double)(u*u))*A);
1261 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1263 for (i=0; i < (ssize_t) kernel->width; i++)
1264 kernel->positive_range += kernel->values[i];
1266 A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
1267 /* B = 1.0/(MagickSQ2PI*sigma); */
1268 for ( i=0; i < (ssize_t) kernel->width; i++)
1269 kernel->positive_range +=
1271 exp(-((double)(i*i))*A);
1272 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1275 else /* special case - generate a unity kernel */
1276 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1277 kernel->width*kernel->height*sizeof(double));
1278 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1279 kernel->positive_range = 1.0;
1282 kernel->minimum = 0.0;
1283 kernel->maximum = kernel->values[0];
1284 kernel->negative_range = 0.0;
1286 ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1287 RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
1292 Convolution Kernels - Well Known Named Constant Kernels
1294 case LaplacianKernel:
1295 { switch ( (int) args->rho ) {
1297 default: /* laplacian square filter -- default */
1298 kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
1300 case 1: /* laplacian diamond filter */
1301 kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
1304 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1307 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
1309 case 5: /* a 5x5 laplacian */
1310 kernel=ParseKernelArray(
1311 "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");
1313 case 7: /* a 7x7 laplacian */
1314 kernel=ParseKernelArray(
1315 "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" );
1317 case 15: /* a 5x5 LoG (sigma approx 1.4) */
1318 kernel=ParseKernelArray(
1319 "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");
1321 case 19: /* a 9x9 LoG (sigma approx 1.4) */
1322 /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1323 kernel=ParseKernelArray(
1324 "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");
1327 if (kernel == (KernelInfo *) NULL)
1329 kernel->type = type;
1333 { /* Simple Sobel Kernel */
1334 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1335 if (kernel == (KernelInfo *) NULL)
1337 kernel->type = type;
1338 RotateKernelInfo(kernel, args->rho);
1343 kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0");
1344 if (kernel == (KernelInfo *) NULL)
1346 kernel->type = type;
1347 RotateKernelInfo(kernel, args->rho);
1352 kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1");
1353 if (kernel == (KernelInfo *) NULL)
1355 kernel->type = type;
1356 RotateKernelInfo(kernel, args->rho);
1361 kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1");
1362 if (kernel == (KernelInfo *) NULL)
1364 kernel->type = type;
1365 RotateKernelInfo(kernel, args->rho);
1370 kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3");
1371 if (kernel == (KernelInfo *) NULL)
1373 kernel->type = type;
1374 RotateKernelInfo(kernel, args->rho);
1377 case FreiChenKernel:
1378 /* Direction is set to be left to right positive */
1379 /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
1380 /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
1381 { switch ( (int) args->rho ) {
1384 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1385 if (kernel == (KernelInfo *) NULL)
1387 kernel->type = type;
1388 kernel->values[3]+=(MagickRealType) MagickSQ2;
1389 kernel->values[5]-=(MagickRealType) MagickSQ2;
1390 CalcKernelMetaData(kernel); /* recalculate meta-data */
1393 kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1");
1394 if (kernel == (KernelInfo *) NULL)
1396 kernel->type = type;
1397 kernel->values[1] = kernel->values[3]+=(MagickRealType) MagickSQ2;
1398 kernel->values[5] = kernel->values[7]-=(MagickRealType) MagickSQ2;
1399 CalcKernelMetaData(kernel); /* recalculate meta-data */
1400 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1403 kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19");
1404 if (kernel == (KernelInfo *) NULL)
1409 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1410 if (kernel == (KernelInfo *) NULL)
1412 kernel->type = type;
1413 kernel->values[3]+=(MagickRealType) MagickSQ2;
1414 kernel->values[5]-=(MagickRealType) MagickSQ2;
1415 CalcKernelMetaData(kernel); /* recalculate meta-data */
1416 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1419 kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1");
1420 if (kernel == (KernelInfo *) NULL)
1422 kernel->type = type;
1423 kernel->values[1]+=(MagickRealType) MagickSQ2;
1424 kernel->values[7]+=(MagickRealType) MagickSQ2;
1425 CalcKernelMetaData(kernel);
1426 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1429 kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
1430 if (kernel == (KernelInfo *) NULL)
1432 kernel->type = type;
1433 kernel->values[0]+=(MagickRealType) MagickSQ2;
1434 kernel->values[8]-=(MagickRealType) MagickSQ2;
1435 CalcKernelMetaData(kernel);
1436 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1439 kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0");
1440 if (kernel == (KernelInfo *) NULL)
1442 kernel->type = type;
1443 kernel->values[2]-=(MagickRealType) MagickSQ2;
1444 kernel->values[6]+=(MagickRealType) MagickSQ2;
1445 CalcKernelMetaData(kernel);
1446 ScaleKernelInfo(kernel, (double) (1.0/2.0*MagickSQ2), NoValue);
1449 kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0");
1450 if (kernel == (KernelInfo *) NULL)
1452 kernel->type = type;
1453 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1456 kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1");
1457 if (kernel == (KernelInfo *) NULL)
1459 kernel->type = type;
1460 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1463 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1");
1464 if (kernel == (KernelInfo *) NULL)
1466 kernel->type = type;
1467 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1470 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1471 if (kernel == (KernelInfo *) NULL)
1473 kernel->type = type;
1474 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1477 kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
1478 if (kernel == (KernelInfo *) NULL)
1480 kernel->type = type;
1481 ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1484 if ( fabs(args->sigma) > MagickEpsilon )
1485 /* Rotate by correctly supplied 'angle' */
1486 RotateKernelInfo(kernel, args->sigma);
1487 else if ( args->rho > 30.0 || args->rho < -30.0 )
1488 /* Rotate by out of bounds 'type' */
1489 RotateKernelInfo(kernel, args->rho);
1494 Boolean or Shaped Kernels
1498 if (args->rho < 1.0)
1499 kernel->width = kernel->height = 3; /* default radius = 1 */
1501 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1502 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1504 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1505 kernel->height*sizeof(*kernel->values));
1506 if (kernel->values == (MagickRealType *) NULL)
1507 return(DestroyKernelInfo(kernel));
1509 /* set all kernel values within diamond area to scale given */
1510 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1511 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1512 if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
1513 kernel->positive_range += kernel->values[i] = args->sigma;
1515 kernel->values[i] = nan;
1516 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1520 case RectangleKernel:
1523 if ( type == SquareKernel )
1525 if (args->rho < 1.0)
1526 kernel->width = kernel->height = 3; /* default radius = 1 */
1528 kernel->width = kernel->height = (size_t) (2*args->rho+1);
1529 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1530 scale = args->sigma;
1533 /* NOTE: user defaults set in "AcquireKernelInfo()" */
1534 if ( args->rho < 1.0 || args->sigma < 1.0 )
1535 return(DestroyKernelInfo(kernel)); /* invalid args given */
1536 kernel->width = (size_t)args->rho;
1537 kernel->height = (size_t)args->sigma;
1538 if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
1539 args->psi < 0.0 || args->psi > (double)kernel->height )
1540 return(DestroyKernelInfo(kernel)); /* invalid args given */
1541 kernel->x = (ssize_t) args->xi;
1542 kernel->y = (ssize_t) args->psi;
1545 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1546 kernel->height*sizeof(*kernel->values));
1547 if (kernel->values == (MagickRealType *) NULL)
1548 return(DestroyKernelInfo(kernel));
1550 /* set all kernel values to scale given */
1551 u=(ssize_t) (kernel->width*kernel->height);
1552 for ( i=0; i < u; i++)
1553 kernel->values[i] = scale;
1554 kernel->minimum = kernel->maximum = scale; /* a flat shape */
1555 kernel->positive_range = scale*u;
1560 if (args->rho < 1.0)
1561 kernel->width = kernel->height = 5; /* default radius = 2 */
1563 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1564 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1566 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1567 kernel->height*sizeof(*kernel->values));
1568 if (kernel->values == (MagickRealType *) NULL)
1569 return(DestroyKernelInfo(kernel));
1571 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1572 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1573 if ( (labs((long) u)+labs((long) v)) <=
1574 ((long)kernel->x + (long)(kernel->x/2)) )
1575 kernel->positive_range += kernel->values[i] = args->sigma;
1577 kernel->values[i] = nan;
1578 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1584 limit = (ssize_t)(args->rho*args->rho);
1586 if (args->rho < 0.4) /* default radius approx 4.3 */
1587 kernel->width = kernel->height = 9L, limit = 18L;
1589 kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1;
1590 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1592 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1593 kernel->height*sizeof(*kernel->values));
1594 if (kernel->values == (MagickRealType *) NULL)
1595 return(DestroyKernelInfo(kernel));
1597 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1598 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1599 if ((u*u+v*v) <= limit)
1600 kernel->positive_range += kernel->values[i] = args->sigma;
1602 kernel->values[i] = nan;
1603 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1608 if (args->rho < 1.0)
1609 kernel->width = kernel->height = 5; /* default radius 2 */
1611 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1612 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1614 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1615 kernel->height*sizeof(*kernel->values));
1616 if (kernel->values == (MagickRealType *) NULL)
1617 return(DestroyKernelInfo(kernel));
1619 /* set all kernel values along axises to given scale */
1620 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1621 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1622 kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1623 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1624 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1629 if (args->rho < 1.0)
1630 kernel->width = kernel->height = 5; /* default radius 2 */
1632 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1633 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1635 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1636 kernel->height*sizeof(*kernel->values));
1637 if (kernel->values == (MagickRealType *) NULL)
1638 return(DestroyKernelInfo(kernel));
1640 /* set all kernel values along axises to given scale */
1641 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1642 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1643 kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1644 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1645 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1659 if (args->rho < args->sigma)
1661 kernel->width = ((size_t)args->sigma)*2+1;
1662 limit1 = (ssize_t)(args->rho*args->rho);
1663 limit2 = (ssize_t)(args->sigma*args->sigma);
1667 kernel->width = ((size_t)args->rho)*2+1;
1668 limit1 = (ssize_t)(args->sigma*args->sigma);
1669 limit2 = (ssize_t)(args->rho*args->rho);
1672 kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1674 kernel->height = kernel->width;
1675 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1676 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
1677 kernel->height*sizeof(*kernel->values));
1678 if (kernel->values == (MagickRealType *) NULL)
1679 return(DestroyKernelInfo(kernel));
1681 /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
1682 scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
1683 for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
1684 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1685 { ssize_t radius=u*u+v*v;
1686 if (limit1 < radius && radius <= limit2)
1687 kernel->positive_range += kernel->values[i] = (double) scale;
1689 kernel->values[i] = nan;
1691 kernel->minimum = kernel->maximum = (double) scale;
1692 if ( type == PeaksKernel ) {
1693 /* set the central point in the middle */
1694 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1695 kernel->positive_range = 1.0;
1696 kernel->maximum = 1.0;
1702 kernel=AcquireKernelInfo("ThinSE:482");
1703 if (kernel == (KernelInfo *) NULL)
1705 kernel->type = type;
1706 ExpandMirrorKernelInfo(kernel); /* mirror expansion of kernels */
1711 kernel=AcquireKernelInfo("ThinSE:87");
1712 if (kernel == (KernelInfo *) NULL)
1714 kernel->type = type;
1715 ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
1718 case DiagonalsKernel:
1720 switch ( (int) args->rho ) {
1725 kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
1726 if (kernel == (KernelInfo *) NULL)
1728 kernel->type = type;
1729 new_kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
1730 if (new_kernel == (KernelInfo *) NULL)
1731 return(DestroyKernelInfo(kernel));
1732 new_kernel->type = type;
1733 LastKernelInfo(kernel)->next = new_kernel;
1734 ExpandMirrorKernelInfo(kernel);
1738 kernel=ParseKernelArray("3: 0,0,0 0,-,1 1,1,-");
1741 kernel=ParseKernelArray("3: 0,0,1 0,-,1 0,1,-");
1744 if (kernel == (KernelInfo *) NULL)
1746 kernel->type = type;
1747 RotateKernelInfo(kernel, args->sigma);
1750 case LineEndsKernel:
1751 { /* Kernels for finding the end of thin lines */
1752 switch ( (int) args->rho ) {
1755 /* set of kernels to find all end of lines */
1756 return(AcquireKernelInfo("LineEnds:1>;LineEnds:2>"));
1758 /* kernel for 4-connected line ends - no rotation */
1759 kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-");
1762 /* kernel to add for 8-connected lines - no rotation */
1763 kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
1766 /* kernel to add for orthogonal line ends - does not find corners */
1767 kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0");
1770 /* traditional line end - fails on last T end */
1771 kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-");
1774 if (kernel == (KernelInfo *) NULL)
1776 kernel->type = type;
1777 RotateKernelInfo(kernel, args->sigma);
1780 case LineJunctionsKernel:
1781 { /* kernels for finding the junctions of multiple lines */
1782 switch ( (int) args->rho ) {
1785 /* set of kernels to find all line junctions */
1786 return(AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>"));
1789 kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-");
1792 /* Diagonal T Junctions */
1793 kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
1796 /* Orthogonal T Junctions */
1797 kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-");
1800 /* Diagonal X Junctions */
1801 kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1");
1804 /* Orthogonal X Junctions - minimal diamond kernel */
1805 kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-");
1808 if (kernel == (KernelInfo *) NULL)
1810 kernel->type = type;
1811 RotateKernelInfo(kernel, args->sigma);
1815 { /* Ridges - Ridge finding kernels */
1818 switch ( (int) args->rho ) {
1821 kernel=ParseKernelArray("3x1:0,1,0");
1822 if (kernel == (KernelInfo *) NULL)
1824 kernel->type = type;
1825 ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
1828 kernel=ParseKernelArray("4x1:0,1,1,0");
1829 if (kernel == (KernelInfo *) NULL)
1831 kernel->type = type;
1832 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
1834 /* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */
1835 /* Unfortunatally we can not yet rotate a non-square kernel */
1836 /* But then we can't flip a non-symetrical kernel either */
1837 new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1838 if (new_kernel == (KernelInfo *) NULL)
1839 return(DestroyKernelInfo(kernel));
1840 new_kernel->type = type;
1841 LastKernelInfo(kernel)->next = new_kernel;
1842 new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
1843 if (new_kernel == (KernelInfo *) NULL)
1844 return(DestroyKernelInfo(kernel));
1845 new_kernel->type = type;
1846 LastKernelInfo(kernel)->next = new_kernel;
1847 new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
1848 if (new_kernel == (KernelInfo *) NULL)
1849 return(DestroyKernelInfo(kernel));
1850 new_kernel->type = type;
1851 LastKernelInfo(kernel)->next = new_kernel;
1852 new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
1853 if (new_kernel == (KernelInfo *) NULL)
1854 return(DestroyKernelInfo(kernel));
1855 new_kernel->type = type;
1856 LastKernelInfo(kernel)->next = new_kernel;
1857 new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
1858 if (new_kernel == (KernelInfo *) NULL)
1859 return(DestroyKernelInfo(kernel));
1860 new_kernel->type = type;
1861 LastKernelInfo(kernel)->next = new_kernel;
1862 new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
1863 if (new_kernel == (KernelInfo *) NULL)
1864 return(DestroyKernelInfo(kernel));
1865 new_kernel->type = type;
1866 LastKernelInfo(kernel)->next = new_kernel;
1867 new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
1868 if (new_kernel == (KernelInfo *) NULL)
1869 return(DestroyKernelInfo(kernel));
1870 new_kernel->type = type;
1871 LastKernelInfo(kernel)->next = new_kernel;
1872 new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
1873 if (new_kernel == (KernelInfo *) NULL)
1874 return(DestroyKernelInfo(kernel));
1875 new_kernel->type = type;
1876 LastKernelInfo(kernel)->next = new_kernel;
1881 case ConvexHullKernel:
1885 /* first set of 8 kernels */
1886 kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
1887 if (kernel == (KernelInfo *) NULL)
1889 kernel->type = type;
1890 ExpandRotateKernelInfo(kernel, 90.0);
1891 /* append the mirror versions too - no flip function yet */
1892 new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0");
1893 if (new_kernel == (KernelInfo *) NULL)
1894 return(DestroyKernelInfo(kernel));
1895 new_kernel->type = type;
1896 ExpandRotateKernelInfo(new_kernel, 90.0);
1897 LastKernelInfo(kernel)->next = new_kernel;
1900 case SkeletonKernel:
1902 switch ( (int) args->rho ) {
1905 /* Traditional Skeleton...
1906 ** A cyclically rotated single kernel
1908 kernel=AcquireKernelInfo("ThinSE:482");
1909 if (kernel == (KernelInfo *) NULL)
1911 kernel->type = type;
1912 ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */
1915 /* HIPR Variation of the cyclic skeleton
1916 ** Corners of the traditional method made more forgiving,
1917 ** but the retain the same cyclic order.
1919 kernel=AcquireKernelInfo("ThinSE:482; ThinSE:87x90;");
1920 if (kernel == (KernelInfo *) NULL)
1922 if (kernel->next == (KernelInfo *) NULL)
1923 return(DestroyKernelInfo(kernel));
1924 kernel->type = type;
1925 kernel->next->type = type;
1926 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */
1929 /* Dan Bloomberg Skeleton, from his paper on 3x3 thinning SE's
1930 ** "Connectivity-Preserving Morphological Image Thransformations"
1931 ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1932 ** http://www.leptonica.com/papers/conn.pdf
1934 kernel=AcquireKernelInfo(
1935 "ThinSE:41; ThinSE:42; ThinSE:43");
1936 if (kernel == (KernelInfo *) NULL)
1938 kernel->type = type;
1939 kernel->next->type = type;
1940 kernel->next->next->type = type;
1941 ExpandMirrorKernelInfo(kernel); /* 12 kernels total */
1947 { /* Special kernels for general thinning, while preserving connections
1948 ** "Connectivity-Preserving Morphological Image Thransformations"
1949 ** by Dan S. Bloomberg, available on Leptonica, Selected Papers,
1950 ** http://www.leptonica.com/papers/conn.pdf
1952 ** http://tpgit.github.com/Leptonica/ccthin_8c_source.html
1954 ** Note kernels do not specify the origin pixel, allowing them
1955 ** to be used for both thickening and thinning operations.
1957 switch ( (int) args->rho ) {
1958 /* SE for 4-connected thinning */
1959 case 41: /* SE_4_1 */
1960 kernel=ParseKernelArray("3: -,-,1 0,-,1 -,-,1");
1962 case 42: /* SE_4_2 */
1963 kernel=ParseKernelArray("3: -,-,1 0,-,1 -,0,-");
1965 case 43: /* SE_4_3 */
1966 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,-,1");
1968 case 44: /* SE_4_4 */
1969 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,-");
1971 case 45: /* SE_4_5 */
1972 kernel=ParseKernelArray("3: -,0,1 0,-,1 -,0,-");
1974 case 46: /* SE_4_6 */
1975 kernel=ParseKernelArray("3: -,0,- 0,-,1 -,0,1");
1977 case 47: /* SE_4_7 */
1978 kernel=ParseKernelArray("3: -,1,1 0,-,1 -,0,-");
1980 case 48: /* SE_4_8 */
1981 kernel=ParseKernelArray("3: -,-,1 0,-,1 0,-,1");
1983 case 49: /* SE_4_9 */
1984 kernel=ParseKernelArray("3: 0,-,1 0,-,1 -,-,1");
1986 /* SE for 8-connected thinning - negatives of the above */
1987 case 81: /* SE_8_0 */
1988 kernel=ParseKernelArray("3: -,1,- 0,-,1 -,1,-");
1990 case 82: /* SE_8_2 */
1991 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,-,-");
1993 case 83: /* SE_8_3 */
1994 kernel=ParseKernelArray("3: 0,-,- 0,-,1 -,1,-");
1996 case 84: /* SE_8_4 */
1997 kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,-");
1999 case 85: /* SE_8_5 */
2000 kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,-");
2002 case 86: /* SE_8_6 */
2003 kernel=ParseKernelArray("3: 0,-,- 0,-,1 0,-,1");
2005 case 87: /* SE_8_7 */
2006 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,0,-");
2008 case 88: /* SE_8_8 */
2009 kernel=ParseKernelArray("3: -,1,- 0,-,1 0,1,-");
2011 case 89: /* SE_8_9 */
2012 kernel=ParseKernelArray("3: 0,1,- 0,-,1 -,1,-");
2014 /* Special combined SE kernels */
2015 case 423: /* SE_4_2 , SE_4_3 Combined Kernel */
2016 kernel=ParseKernelArray("3: -,-,1 0,-,- -,0,-");
2018 case 823: /* SE_8_2 , SE_8_3 Combined Kernel */
2019 kernel=ParseKernelArray("3: -,1,- -,-,1 0,-,-");
2021 case 481: /* SE_48_1 - General Connected Corner Kernel */
2022 kernel=ParseKernelArray("3: -,1,1 0,-,1 0,0,-");
2025 case 482: /* SE_48_2 - General Edge Kernel */
2026 kernel=ParseKernelArray("3: 0,-,1 0,-,1 0,-,1");
2029 if (kernel == (KernelInfo *) NULL)
2031 kernel->type = type;
2032 RotateKernelInfo(kernel, args->sigma);
2036 Distance Measuring Kernels
2038 case ChebyshevKernel:
2040 if (args->rho < 1.0)
2041 kernel->width = kernel->height = 3; /* default radius = 1 */
2043 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2044 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2046 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2047 kernel->height*sizeof(*kernel->values));
2048 if (kernel->values == (MagickRealType *) NULL)
2049 return(DestroyKernelInfo(kernel));
2051 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2052 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2053 kernel->positive_range += ( kernel->values[i] =
2054 args->sigma*MagickMax(fabs((double)u),fabs((double)v)) );
2055 kernel->maximum = kernel->values[0];
2058 case ManhattanKernel:
2060 if (args->rho < 1.0)
2061 kernel->width = kernel->height = 3; /* default radius = 1 */
2063 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2064 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2066 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2067 kernel->height*sizeof(*kernel->values));
2068 if (kernel->values == (MagickRealType *) NULL)
2069 return(DestroyKernelInfo(kernel));
2071 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2072 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2073 kernel->positive_range += ( kernel->values[i] =
2074 args->sigma*(labs((long) u)+labs((long) v)) );
2075 kernel->maximum = kernel->values[0];
2078 case OctagonalKernel:
2080 if (args->rho < 2.0)
2081 kernel->width = kernel->height = 5; /* default/minimum radius = 2 */
2083 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2084 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2086 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2087 kernel->height*sizeof(*kernel->values));
2088 if (kernel->values == (MagickRealType *) NULL)
2089 return(DestroyKernelInfo(kernel));
2091 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2092 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2095 r1 = MagickMax(fabs((double)u),fabs((double)v)),
2096 r2 = floor((double)(labs((long)u)+labs((long)v)+1)/1.5);
2097 kernel->positive_range += kernel->values[i] =
2098 args->sigma*MagickMax(r1,r2);
2100 kernel->maximum = kernel->values[0];
2103 case EuclideanKernel:
2105 if (args->rho < 1.0)
2106 kernel->width = kernel->height = 3; /* default radius = 1 */
2108 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2109 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
2111 kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2112 kernel->height*sizeof(*kernel->values));
2113 if (kernel->values == (MagickRealType *) NULL)
2114 return(DestroyKernelInfo(kernel));
2116 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2117 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
2118 kernel->positive_range += ( kernel->values[i] =
2119 args->sigma*sqrt((double)(u*u+v*v)) );
2120 kernel->maximum = kernel->values[0];
2125 /* No-Op Kernel - Basically just a single pixel on its own */
2126 kernel=ParseKernelArray("1:1");
2127 if (kernel == (KernelInfo *) NULL)
2129 kernel->type = UndefinedKernel;
2138 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2142 % C l o n e K e r n e l I n f o %
2146 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2148 % CloneKernelInfo() creates a new clone of the given Kernel List so that its
2149 % can be modified without effecting the original. The cloned kernel should
2150 % be destroyed using DestoryKernelInfo() when no longer needed.
2152 % The format of the CloneKernelInfo method is:
2154 % KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2156 % A description of each parameter follows:
2158 % o kernel: the Morphology/Convolution kernel to be cloned
2161 MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
2169 assert(kernel != (KernelInfo *) NULL);
2170 new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
2171 if (new_kernel == (KernelInfo *) NULL)
2173 *new_kernel=(*kernel); /* copy values in structure */
2175 /* replace the values with a copy of the values */
2176 new_kernel->values=(MagickRealType *) AcquireAlignedMemory(kernel->width,
2177 kernel->height*sizeof(*kernel->values));
2178 if (new_kernel->values == (MagickRealType *) NULL)
2179 return(DestroyKernelInfo(new_kernel));
2180 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
2181 new_kernel->values[i]=kernel->values[i];
2183 /* Also clone the next kernel in the kernel list */
2184 if ( kernel->next != (KernelInfo *) NULL ) {
2185 new_kernel->next = CloneKernelInfo(kernel->next);
2186 if ( new_kernel->next == (KernelInfo *) NULL )
2187 return(DestroyKernelInfo(new_kernel));
2194 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2198 % D e s t r o y K e r n e l I n f o %
2202 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2204 % DestroyKernelInfo() frees the memory used by a Convolution/Morphology
2207 % The format of the DestroyKernelInfo method is:
2209 % KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2211 % A description of each parameter follows:
2213 % o kernel: the Morphology/Convolution kernel to be destroyed
2216 MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
2218 assert(kernel != (KernelInfo *) NULL);
2219 if ( kernel->next != (KernelInfo *) NULL )
2220 kernel->next=DestroyKernelInfo(kernel->next);
2221 kernel->values=(MagickRealType *) RelinquishAlignedMemory(kernel->values);
2222 kernel=(KernelInfo *) RelinquishMagickMemory(kernel);
2227 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2231 + E x p a n d M i r r o r K e r n e l I n f o %
2235 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2237 % ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
2238 % sequence of 90-degree rotated kernels but providing a reflected 180
2239 % rotatation, before the -/+ 90-degree rotations.
2241 % This special rotation order produces a better, more symetrical thinning of
2244 % The format of the ExpandMirrorKernelInfo method is:
2246 % void ExpandMirrorKernelInfo(KernelInfo *kernel)
2248 % A description of each parameter follows:
2250 % o kernel: the Morphology/Convolution kernel
2252 % This function is only internel to this module, as it is not finalized,
2253 % especially with regard to non-orthogonal angles, and rotation of larger
2258 static void FlopKernelInfo(KernelInfo *kernel)
2259 { /* Do a Flop by reversing each row. */
2267 for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
2268 for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
2269 t=k[x], k[x]=k[r], k[r]=t;
2271 kernel->x = kernel->width - kernel->x - 1;
2272 angle = fmod(angle+180.0, 360.0);
2276 static void ExpandMirrorKernelInfo(KernelInfo *kernel)
2284 clone = CloneKernelInfo(last);
2285 RotateKernelInfo(clone, 180); /* flip */
2286 LastKernelInfo(last)->next = clone;
2289 clone = CloneKernelInfo(last);
2290 RotateKernelInfo(clone, 90); /* transpose */
2291 LastKernelInfo(last)->next = clone;
2294 clone = CloneKernelInfo(last);
2295 RotateKernelInfo(clone, 180); /* flop */
2296 LastKernelInfo(last)->next = clone;
2302 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2306 + E x p a n d R o t a t e K e r n e l I n f o %
2310 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2312 % ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
2313 % incrementally by the angle given, until the kernel repeats.
2315 % WARNING: 45 degree rotations only works for 3x3 kernels.
2316 % While 90 degree roatations only works for linear and square kernels
2318 % The format of the ExpandRotateKernelInfo method is:
2320 % void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
2322 % A description of each parameter follows:
2324 % o kernel: the Morphology/Convolution kernel
2326 % o angle: angle to rotate in degrees
2328 % This function is only internel to this module, as it is not finalized,
2329 % especially with regard to non-orthogonal angles, and rotation of larger
2333 /* Internal Routine - Return true if two kernels are the same */
2334 static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
2335 const KernelInfo *kernel2)
2340 /* check size and origin location */
2341 if ( kernel1->width != kernel2->width
2342 || kernel1->height != kernel2->height
2343 || kernel1->x != kernel2->x
2344 || kernel1->y != kernel2->y )
2347 /* check actual kernel values */
2348 for (i=0; i < (kernel1->width*kernel1->height); i++) {
2349 /* Test for Nan equivalence */
2350 if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
2352 if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
2354 /* Test actual values are equivalent */
2355 if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
2362 static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
2370 clone = CloneKernelInfo(last);
2371 RotateKernelInfo(clone, angle);
2372 if ( SameKernelInfo(kernel, clone) == MagickTrue )
2374 LastKernelInfo(last)->next = clone;
2377 clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
2382 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2386 + C a l c M e t a K e r n a l I n f o %
2390 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2392 % CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2393 % using the kernel values. This should only ne used if it is not possible to
2394 % calculate that meta-data in some easier way.
2396 % It is important that the meta-data is correct before ScaleKernelInfo() is
2397 % used to perform kernel normalization.
2399 % The format of the CalcKernelMetaData method is:
2401 % void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2403 % A description of each parameter follows:
2405 % o kernel: the Morphology/Convolution kernel to modify
2407 % WARNING: Minimum and Maximum values are assumed to include zero, even if
2408 % zero is not part of the kernel (as in Gaussian Derived kernels). This
2409 % however is not true for flat-shaped morphological kernels.
2411 % WARNING: Only the specific kernel pointed to is modified, not a list of
2414 % This is an internal function and not expected to be useful outside this
2415 % module. This could change however.
2417 static void CalcKernelMetaData(KernelInfo *kernel)
2422 kernel->minimum = kernel->maximum = 0.0;
2423 kernel->negative_range = kernel->positive_range = 0.0;
2424 for (i=0; i < (kernel->width*kernel->height); i++)
2426 if ( fabs(kernel->values[i]) < MagickEpsilon )
2427 kernel->values[i] = 0.0;
2428 ( kernel->values[i] < 0)
2429 ? ( kernel->negative_range += kernel->values[i] )
2430 : ( kernel->positive_range += kernel->values[i] );
2431 Minimize(kernel->minimum, kernel->values[i]);
2432 Maximize(kernel->maximum, kernel->values[i]);
2439 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2443 % M o r p h o l o g y A p p l y %
2447 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2449 % MorphologyApply() applies a morphological method, multiple times using
2450 % a list of multiple kernels. This is the method that should be called by
2451 % other 'operators' that internally use morphology operations as part of
2454 % It is basically equivalent to as MorphologyImage() (see below) but
2455 % without any user controls. This allows internel programs to use this
2456 % function, to actually perform a specific task without possible interference
2457 % by any API user supplied settings.
2459 % It is MorphologyImage() task to extract any such user controls, and
2460 % pass them to this function for processing.
2462 % More specifically all given kernels should already be scaled, normalised,
2463 % and blended appropriatally before being parred to this routine. The
2464 % appropriate bias, and compose (typically 'UndefinedComposeOp') given.
2466 % The format of the MorphologyApply method is:
2468 % Image *MorphologyApply(const Image *image,MorphologyMethod method,
2469 % const ssize_t iterations,const KernelInfo *kernel,
2470 % const CompositeMethod compose,const double bias,
2471 % ExceptionInfo *exception)
2473 % A description of each parameter follows:
2475 % o image: the source image
2477 % o method: the morphology method to be applied.
2479 % o iterations: apply the operation this many times (or no change).
2480 % A value of -1 means loop until no change found.
2481 % How this is applied may depend on the morphology method.
2482 % Typically this is a value of 1.
2484 % o channel: the channel type.
2486 % o kernel: An array of double representing the morphology kernel.
2488 % o compose: How to handle or merge multi-kernel results.
2489 % If 'UndefinedCompositeOp' use default for the Morphology method.
2490 % If 'NoCompositeOp' force image to be re-iterated by each kernel.
2491 % Otherwise merge the results using the compose method given.
2493 % o bias: Convolution Output Bias.
2495 % o exception: return any errors or warnings in this structure.
2499 /* Apply a Morphology Primative to an image using the given kernel.
2500 ** Two pre-created images must be provided, and no image is created.
2501 ** It returns the number of pixels that changed between the images
2502 ** for result convergence determination.
2504 static ssize_t MorphologyPrimitive(const Image *image,Image *morphology_image,
2505 const MorphologyMethod method,const KernelInfo *kernel,const double bias,
2506 ExceptionInfo *exception)
2508 #define MorphologyTag "Morphology/Image"
2527 assert(image != (Image *) NULL);
2528 assert(image->signature == MagickSignature);
2529 assert(morphology_image != (Image *) NULL);
2530 assert(morphology_image->signature == MagickSignature);
2531 assert(kernel != (KernelInfo *) NULL);
2532 assert(kernel->signature == MagickSignature);
2533 assert(exception != (ExceptionInfo *) NULL);
2534 assert(exception->signature == MagickSignature);
2540 image_view=AcquireVirtualCacheView(image,exception);
2541 morphology_view=AcquireAuthenticCacheView(morphology_image,exception);
2542 virt_width=image->columns+kernel->width-1;
2544 /* Some methods (including convolve) needs use a reflected kernel.
2545 * Adjust 'origin' offsets to loop though kernel as a reflection.
2550 case ConvolveMorphology:
2551 case DilateMorphology:
2552 case DilateIntensityMorphology:
2553 case IterativeDistanceMorphology:
2554 /* kernel needs to used with reflection about origin */
2555 offx = (ssize_t) kernel->width-offx-1;
2556 offy = (ssize_t) kernel->height-offy-1;
2558 case ErodeMorphology:
2559 case ErodeIntensityMorphology:
2560 case HitAndMissMorphology:
2561 case ThinningMorphology:
2562 case ThickenMorphology:
2563 /* kernel is used as is, without reflection */
2566 assert("Not a Primitive Morphology Method" != (char *) NULL);
2570 if ( method == ConvolveMorphology && kernel->width == 1 )
2571 { /* Special handling (for speed) of vertical (blur) kernels.
2572 ** This performs its handling in columns rather than in rows.
2573 ** This is only done for convolve as it is the only method that
2574 ** generates very large 1-D vertical kernels (such as a 'BlurKernel')
2576 ** Timing tests (on single CPU laptop)
2577 ** Using a vertical 1-d Blue with normal row-by-row (below)
2578 ** time convert logo: -morphology Convolve Blur:0x10+90 null:
2580 ** Using this column method
2581 ** time convert logo: -morphology Convolve Blur:0x10+90 null:
2584 ** Anthony Thyssen, 14 June 2010
2589 #if defined(MAGICKCORE_OPENMP_SUPPORT)
2590 #pragma omp parallel for schedule(static,4) shared(progress,status) \
2591 if ((image->rows*image->columns) > 8192) \
2592 num_threads(GetMagickResourceLimit(ThreadResource))
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 if ((image->rows*image->columns) > 8192) \
2770 num_threads(GetMagickResourceLimit(ThreadResource))
2772 for (y=0; y < (ssize_t) image->rows; y++)
2774 register const Quantum
2786 if (status == MagickFalse)
2788 p=GetCacheViewVirtualPixels(image_view, -offx, y-offy, virt_width,
2789 kernel->height, exception);
2790 q=GetCacheViewAuthenticPixels(morphology_view,0,y,
2791 morphology_image->columns,1,exception);
2792 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
2797 /* offset to origin in 'p'. while 'q' points to it directly */
2798 r = virt_width*offy + offx;
2800 for (x=0; x < (ssize_t) image->columns; x++)
2808 register const double
2811 register const Quantum
2819 /* Copy input image to the output image for unused channels
2820 * This removes need for 'cloning' a new image every iteration
2822 SetPixelRed(morphology_image,GetPixelRed(image,p+r*
2823 GetPixelChannels(image)),q);
2824 SetPixelGreen(morphology_image,GetPixelGreen(image,p+r*
2825 GetPixelChannels(image)),q);
2826 SetPixelBlue(morphology_image,GetPixelBlue(image,p+r*
2827 GetPixelChannels(image)),q);
2828 if (image->colorspace == CMYKColorspace)
2829 SetPixelBlack(morphology_image,GetPixelBlack(image,p+r*
2830 GetPixelChannels(image)),q);
2837 min.black = (MagickRealType) QuantumRange;
2842 max.black = (MagickRealType) 0;
2843 /* default result is the original pixel value */
2844 result.red = (MagickRealType) GetPixelRed(image,p+r*GetPixelChannels(image));
2845 result.green = (MagickRealType) GetPixelGreen(image,p+r*GetPixelChannels(image));
2846 result.blue = (MagickRealType) GetPixelBlue(image,p+r*GetPixelChannels(image));
2848 if (image->colorspace == CMYKColorspace)
2849 result.black = (MagickRealType) GetPixelBlack(image,p+r*GetPixelChannels(image));
2850 result.alpha=(MagickRealType) GetPixelAlpha(image,p+r*GetPixelChannels(image));
2853 case ConvolveMorphology:
2854 /* Set the bias of the weighted average output */
2859 result.black = bias;
2861 case DilateIntensityMorphology:
2862 case ErodeIntensityMorphology:
2863 /* use a boolean flag indicating when first match found */
2864 result.red = 0.0; /* result is not used otherwise */
2871 case ConvolveMorphology:
2872 /* Weighted Average of pixels using reflected kernel
2874 ** NOTE for correct working of this operation for asymetrical
2875 ** kernels, the kernel needs to be applied in its reflected form.
2876 ** That is its values needs to be reversed.
2878 ** Correlation is actually the same as this but without reflecting
2879 ** the kernel, and thus 'lower-level' that Convolution. However
2880 ** as Convolution is the more common method used, and it does not
2881 ** really cost us much in terms of processing to use a reflected
2882 ** kernel, so it is Convolution that is implemented.
2884 ** Correlation will have its kernel reflected before calling
2885 ** this function to do a Convolve.
2887 ** For more details of Correlation vs Convolution see
2888 ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
2890 k = &kernel->values[ kernel->width*kernel->height-1 ];
2892 if ( (image->channel_mask != DefaultChannels) ||
2893 (image->matte == MagickFalse) )
2894 { /* No 'Sync' involved.
2895 ** Convolution is simple greyscale channel operation
2897 for (v=0; v < (ssize_t) kernel->height; v++) {
2898 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2899 if ( IsNan(*k) ) continue;
2901 GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2902 result.green += (*k)*
2903 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2904 result.blue += (*k)*
2905 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2906 if (image->colorspace == CMYKColorspace)
2907 result.black += (*k)*
2908 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2909 result.alpha += (*k)*
2910 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2912 k_pixels += virt_width*GetPixelChannels(image);
2914 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
2915 SetPixelRed(morphology_image,ClampToQuantum(result.red),
2917 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
2918 SetPixelGreen(morphology_image,ClampToQuantum(result.green),
2920 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
2921 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),
2923 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
2924 (image->colorspace == CMYKColorspace))
2925 SetPixelBlack(morphology_image,ClampToQuantum(result.black),
2927 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
2928 (image->matte == MagickTrue))
2929 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),
2933 { /* Channel 'Sync' Flag, and Alpha Channel enabled.
2934 ** Weight the color channels with Alpha Channel so that
2935 ** transparent pixels are not part of the results.
2938 alpha, /* alpha weighting for colors : alpha */
2939 gamma; /* divisor, sum of color alpha weighting */
2941 count; /* alpha valus collected, number kernel values */
2945 for (v=0; v < (ssize_t) kernel->height; v++) {
2946 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
2947 if ( IsNan(*k) ) continue;
2948 alpha=QuantumScale*GetPixelAlpha(image,
2949 k_pixels+u*GetPixelChannels(image));
2950 gamma += alpha; /* normalize alpha weights only */
2951 count++; /* number of alpha values collected */
2952 alpha=alpha*(*k); /* include kernel weighting now */
2953 result.red += alpha*
2954 GetPixelRed(image,k_pixels+u*GetPixelChannels(image));
2955 result.green += alpha*
2956 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image));
2957 result.blue += alpha*
2958 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image));
2959 if (image->colorspace == CMYKColorspace)
2960 result.black += alpha*
2961 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image));
2962 result.alpha += (*k)*
2963 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image));
2965 k_pixels += virt_width*GetPixelChannels(image);
2967 /* Sync'ed channels, all channels are modified */
2968 gamma=(double)count/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2969 SetPixelRed(morphology_image,
2970 ClampToQuantum(gamma*result.red),q);
2971 SetPixelGreen(morphology_image,
2972 ClampToQuantum(gamma*result.green),q);
2973 SetPixelBlue(morphology_image,
2974 ClampToQuantum(gamma*result.blue),q);
2975 if (image->colorspace == CMYKColorspace)
2976 SetPixelBlack(morphology_image,
2977 ClampToQuantum(gamma*result.black),q);
2978 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
2982 case ErodeMorphology:
2983 /* Minimum Value within kernel neighbourhood
2985 ** NOTE that the kernel is not reflected for this operation!
2987 ** NOTE: in normal Greyscale Morphology, the kernel value should
2988 ** be added to the real value, this is currently not done, due to
2989 ** the nature of the boolean kernels being used.
2993 for (v=0; v < (ssize_t) kernel->height; v++) {
2994 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
2995 if ( IsNan(*k) || (*k) < 0.5 ) continue;
2996 Minimize(min.red, (double)
2997 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
2998 Minimize(min.green, (double)
2999 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3000 Minimize(min.blue, (double)
3001 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3002 Minimize(min.alpha, (double)
3003 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3004 if (image->colorspace == CMYKColorspace)
3005 Minimize(min.black, (double)
3006 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3008 k_pixels += virt_width*GetPixelChannels(image);
3012 case DilateMorphology:
3013 /* Maximum Value within kernel neighbourhood
3015 ** NOTE for correct working of this operation for asymetrical
3016 ** kernels, the kernel needs to be applied in its reflected form.
3017 ** That is its values needs to be reversed.
3019 ** NOTE: in normal Greyscale Morphology, the kernel value should
3020 ** be added to the real value, this is currently not done, due to
3021 ** the nature of the boolean kernels being used.
3024 k = &kernel->values[ kernel->width*kernel->height-1 ];
3026 for (v=0; v < (ssize_t) kernel->height; v++) {
3027 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3028 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3029 Maximize(max.red, (double)
3030 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3031 Maximize(max.green, (double)
3032 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3033 Maximize(max.blue, (double)
3034 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3035 Maximize(max.alpha, (double)
3036 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3037 if (image->colorspace == CMYKColorspace)
3038 Maximize(max.black, (double)
3039 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3041 k_pixels += virt_width*GetPixelChannels(image);
3045 case HitAndMissMorphology:
3046 case ThinningMorphology:
3047 case ThickenMorphology:
3048 /* Minimum of Foreground Pixel minus Maxumum of Background Pixels
3050 ** NOTE that the kernel is not reflected for this operation,
3051 ** and consists of both foreground and background pixel
3052 ** neighbourhoods, 0.0 for background, and 1.0 for foreground
3053 ** with either Nan or 0.5 values for don't care.
3055 ** Note that this will never produce a meaningless negative
3056 ** result. Such results can cause Thinning/Thicken to not work
3057 ** correctly when used against a greyscale image.
3061 for (v=0; v < (ssize_t) kernel->height; v++) {
3062 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3063 if ( IsNan(*k) ) continue;
3065 { /* minimim of foreground pixels */
3066 Minimize(min.red, (double)
3067 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3068 Minimize(min.green, (double)
3069 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3070 Minimize(min.blue, (double)
3071 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3072 Minimize(min.alpha,(double)
3073 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3074 if ( image->colorspace == CMYKColorspace)
3075 Minimize(min.black,(double)
3076 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3078 else if ( (*k) < 0.3 )
3079 { /* maximum of background pixels */
3080 Maximize(max.red, (double)
3081 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3082 Maximize(max.green, (double)
3083 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3084 Maximize(max.blue, (double)
3085 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3086 Maximize(max.alpha,(double)
3087 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3088 if (image->colorspace == CMYKColorspace)
3089 Maximize(max.black, (double)
3090 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3093 k_pixels += virt_width*GetPixelChannels(image);
3095 /* Pattern Match if difference is positive */
3096 min.red -= max.red; Maximize( min.red, 0.0 );
3097 min.green -= max.green; Maximize( min.green, 0.0 );
3098 min.blue -= max.blue; Maximize( min.blue, 0.0 );
3099 min.black -= max.black; Maximize( min.black, 0.0 );
3100 min.alpha -= max.alpha; Maximize( min.alpha, 0.0 );
3103 case ErodeIntensityMorphology:
3104 /* Select Pixel with Minimum Intensity within kernel neighbourhood
3106 ** WARNING: the intensity test fails for CMYK and does not
3107 ** take into account the moderating effect of the alpha channel
3108 ** on the intensity.
3110 ** NOTE that the kernel is not reflected for this operation!
3114 for (v=0; v < (ssize_t) kernel->height; v++) {
3115 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
3116 if ( IsNan(*k) || (*k) < 0.5 ) continue;
3117 if ( result.red == 0.0 ||
3118 GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) < GetPixelIntensity(morphology_image,q) ) {
3119 /* copy the whole pixel - no channel selection */
3120 SetPixelRed(morphology_image,GetPixelRed(image,
3121 k_pixels+u*GetPixelChannels(image)),q);
3122 SetPixelGreen(morphology_image,GetPixelGreen(image,
3123 k_pixels+u*GetPixelChannels(image)),q);
3124 SetPixelBlue(morphology_image,GetPixelBlue(image,
3125 k_pixels+u*GetPixelChannels(image)),q);
3126 SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3127 k_pixels+u*GetPixelChannels(image)),q);
3128 if ( result.red > 0.0 ) changed++;
3132 k_pixels += virt_width*GetPixelChannels(image);
3136 case DilateIntensityMorphology:
3137 /* Select Pixel with Maximum Intensity within kernel neighbourhood
3139 ** WARNING: the intensity test fails for CMYK and does not
3140 ** take into account the moderating effect of the alpha channel
3141 ** on the intensity (yet).
3143 ** NOTE for correct working of this operation for asymetrical
3144 ** kernels, the kernel needs to be applied in its reflected form.
3145 ** That is its values needs to be reversed.
3147 k = &kernel->values[ kernel->width*kernel->height-1 ];
3149 for (v=0; v < (ssize_t) kernel->height; v++) {
3150 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3151 if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */
3152 if ( result.red == 0.0 ||
3153 GetPixelIntensity(image,k_pixels+u*GetPixelChannels(image)) > GetPixelIntensity(morphology_image,q) ) {
3154 /* copy the whole pixel - no channel selection */
3155 SetPixelRed(morphology_image,GetPixelRed(image,
3156 k_pixels+u*GetPixelChannels(image)),q);
3157 SetPixelGreen(morphology_image,GetPixelGreen(image,
3158 k_pixels+u*GetPixelChannels(image)),q);
3159 SetPixelBlue(morphology_image,GetPixelBlue(image,
3160 k_pixels+u*GetPixelChannels(image)),q);
3161 SetPixelAlpha(morphology_image,GetPixelAlpha(image,
3162 k_pixels+u*GetPixelChannels(image)),q);
3163 if ( result.red > 0.0 ) changed++;
3167 k_pixels += virt_width*GetPixelChannels(image);
3171 case IterativeDistanceMorphology:
3172 /* Work out an iterative distance from black edge of a white image
3173 ** shape. Essentually white values are decreased to the smallest
3174 ** 'distance from edge' it can find.
3176 ** It works by adding kernel values to the neighbourhood, and and
3177 ** select the minimum value found. The kernel is rotated before
3178 ** use, so kernel distances match resulting distances, when a user
3179 ** provided asymmetric kernel is applied.
3182 ** This code is almost identical to True GrayScale Morphology But
3185 ** GreyDilate Kernel values added, maximum value found Kernel is
3186 ** rotated before use.
3188 ** GrayErode: Kernel values subtracted and minimum value found No
3189 ** kernel rotation used.
3191 ** Note the the Iterative Distance method is essentially a
3192 ** GrayErode, but with negative kernel values, and kernel
3193 ** rotation applied.
3195 k = &kernel->values[ kernel->width*kernel->height-1 ];
3197 for (v=0; v < (ssize_t) kernel->height; v++) {
3198 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3199 if ( IsNan(*k) ) continue;
3200 Minimize(result.red, (*k)+(double)
3201 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3202 Minimize(result.green, (*k)+(double)
3203 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3204 Minimize(result.blue, (*k)+(double)
3205 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3206 Minimize(result.alpha, (*k)+(double)
3207 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3208 if ( image->colorspace == CMYKColorspace)
3209 Maximize(result.black, (*k)+(double)
3210 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3212 k_pixels += virt_width*GetPixelChannels(image);
3216 case UndefinedMorphology:
3218 break; /* Do nothing */
3220 /* Final mathematics of results (combine with original image?)
3222 ** NOTE: Difference Morphology operators Edge* and *Hat could also
3223 ** be done here but works better with iteration as a image difference
3224 ** in the controling function (below). Thicken and Thinning however
3225 ** should be done here so thay can be iterated correctly.
3228 case HitAndMissMorphology:
3229 case ErodeMorphology:
3230 result = min; /* minimum of neighbourhood */
3232 case DilateMorphology:
3233 result = max; /* maximum of neighbourhood */
3235 case ThinningMorphology:
3236 /* subtract pattern match from original */
3237 result.red -= min.red;
3238 result.green -= min.green;
3239 result.blue -= min.blue;
3240 result.black -= min.black;
3241 result.alpha -= min.alpha;
3243 case ThickenMorphology:
3244 /* Add the pattern matchs to the original */
3245 result.red += min.red;
3246 result.green += min.green;
3247 result.blue += min.blue;
3248 result.black += min.black;
3249 result.alpha += min.alpha;
3252 /* result directly calculated or assigned */
3255 /* Assign the resulting pixel values - Clamping Result */
3257 case UndefinedMorphology:
3258 case ConvolveMorphology:
3259 case DilateIntensityMorphology:
3260 case ErodeIntensityMorphology:
3261 break; /* full pixel was directly assigned - not a channel method */
3263 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3264 SetPixelRed(morphology_image,ClampToQuantum(result.red),q);
3265 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3266 SetPixelGreen(morphology_image,ClampToQuantum(result.green),q);
3267 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3268 SetPixelBlue(morphology_image,ClampToQuantum(result.blue),q);
3269 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3270 (image->colorspace == CMYKColorspace))
3271 SetPixelBlack(morphology_image,ClampToQuantum(result.black),q);
3272 if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
3273 (image->matte == MagickTrue))
3274 SetPixelAlpha(morphology_image,ClampToQuantum(result.alpha),q);
3277 /* Count up changed pixels */
3278 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(morphology_image,q)) ||
3279 (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(morphology_image,q)) ||
3280 (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(morphology_image,q)) ||
3281 (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(morphology_image,q)) ||
3282 ((image->colorspace == CMYKColorspace) &&
3283 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(morphology_image,q))))
3284 changed++; /* The pixel was changed in some way! */
3285 p+=GetPixelChannels(image);
3286 q+=GetPixelChannels(morphology_image);
3288 if ( SyncCacheViewAuthenticPixels(morphology_view,exception) == MagickFalse)
3290 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3295 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3296 #pragma omp critical (MagickCore_MorphologyImage)
3298 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
3299 if (proceed == MagickFalse)
3303 morphology_view=DestroyCacheView(morphology_view);
3304 image_view=DestroyCacheView(image_view);
3305 return(status ? (ssize_t)changed : -1);
3308 /* This is almost identical to the MorphologyPrimative() function above,
3309 ** but will apply the primitive directly to the actual image using two
3310 ** passes, once in each direction, with the results of the previous (and
3311 ** current) row being re-used.
3313 ** That is after each row is 'Sync'ed' into the image, the next row will
3314 ** make use of those values as part of the calculation of the next row.
3315 ** It then repeats, but going in the oppisite (bottom-up) direction.
3317 ** Because of this 're-use of results' this function can not make use
3318 ** of multi-threaded, parellel processing.
3320 static ssize_t MorphologyPrimitiveDirect(Image *image,
3321 const MorphologyMethod method,const KernelInfo *kernel,
3322 ExceptionInfo *exception)
3345 assert(image != (Image *) NULL);
3346 assert(image->signature == MagickSignature);
3347 assert(kernel != (KernelInfo *) NULL);
3348 assert(kernel->signature == MagickSignature);
3349 assert(exception != (ExceptionInfo *) NULL);
3350 assert(exception->signature == MagickSignature);
3352 /* Some methods (including convolve) needs use a reflected kernel.
3353 * Adjust 'origin' offsets to loop though kernel as a reflection.
3358 case DistanceMorphology:
3359 case VoronoiMorphology:
3360 /* kernel needs to used with reflection about origin */
3361 offx = (ssize_t) kernel->width-offx-1;
3362 offy = (ssize_t) kernel->height-offy-1;
3365 case ?????Morphology:
3366 /* kernel is used as is, without reflection */
3370 assert("Not a PrimativeDirect Morphology Method" != (char *) NULL);
3374 /* DO NOT THREAD THIS CODE! */
3375 /* two views into same image (virtual, and actual) */
3376 virt_view=AcquireVirtualCacheView(image,exception);
3377 auth_view=AcquireAuthenticCacheView(image,exception);
3378 virt_width=image->columns+kernel->width-1;
3380 for (y=0; y < (ssize_t) image->rows; y++)
3382 register const Quantum
3394 /* NOTE read virtual pixels, and authentic pixels, from the same image!
3395 ** we read using virtual to get virtual pixel handling, but write back
3396 ** into the same image.
3398 ** Only top half of kernel is processed as we do a single pass downward
3399 ** through the image iterating the distance function as we go.
3401 if (status == MagickFalse)
3403 p=GetCacheViewVirtualPixels(virt_view,-offx,y-offy,virt_width,(size_t)
3405 q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3407 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3409 if (status == MagickFalse)
3412 /* offset to origin in 'p'. while 'q' points to it directly */
3413 r = (ssize_t) virt_width*offy + offx;
3415 for (x=0; x < (ssize_t) image->columns; x++)
3423 register const double
3426 register const Quantum
3432 /* Starting Defaults */
3433 GetPixelInfo(image,&result);
3434 GetPixelInfoPixel(image,q,&result);
3435 if ( method != VoronoiMorphology )
3436 result.alpha = QuantumRange - result.alpha;
3439 case DistanceMorphology:
3440 /* Add kernel Value and select the minimum value found. */
3441 k = &kernel->values[ kernel->width*kernel->height-1 ];
3443 for (v=0; v <= (ssize_t) offy; v++) {
3444 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3445 if ( IsNan(*k) ) continue;
3446 Minimize(result.red, (*k)+
3447 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3448 Minimize(result.green, (*k)+
3449 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3450 Minimize(result.blue, (*k)+
3451 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3452 if (image->colorspace == CMYKColorspace)
3453 Minimize(result.black,(*k)+
3454 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3455 Minimize(result.alpha, (*k)+
3456 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3458 k_pixels += virt_width*GetPixelChannels(image);
3460 /* repeat with the just processed pixels of this row */
3461 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3462 k_pixels = q-offx*GetPixelChannels(image);
3463 for (u=0; u < (ssize_t) offx; u++, k--) {
3464 if ( x+u-offx < 0 ) continue; /* off the edge! */
3465 if ( IsNan(*k) ) continue;
3466 Minimize(result.red, (*k)+
3467 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3468 Minimize(result.green, (*k)+
3469 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3470 Minimize(result.blue, (*k)+
3471 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3472 if (image->colorspace == CMYKColorspace)
3473 Minimize(result.black,(*k)+
3474 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3475 Minimize(result.alpha,(*k)+
3476 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3479 case VoronoiMorphology:
3480 /* Apply Distance to 'Matte' channel, while coping the color
3481 ** values of the closest pixel.
3483 ** This is experimental, and realy the 'alpha' component should
3484 ** be completely separate 'masking' channel so that alpha can
3485 ** also be used as part of the results.
3487 k = &kernel->values[ kernel->width*kernel->height-1 ];
3489 for (v=0; v <= (ssize_t) offy; v++) {
3490 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3491 if ( IsNan(*k) ) continue;
3492 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3494 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3499 k_pixels += virt_width*GetPixelChannels(image);
3501 /* repeat with the just processed pixels of this row */
3502 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3503 k_pixels = q-offx*GetPixelChannels(image);
3504 for (u=0; u < (ssize_t) offx; u++, k--) {
3505 if ( x+u-offx < 0 ) continue; /* off the edge! */
3506 if ( IsNan(*k) ) continue;
3507 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3509 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3516 /* result directly calculated or assigned */
3519 /* Assign the resulting pixel values - Clamping Result */
3521 case VoronoiMorphology:
3522 SetPixelInfoPixel(image,&result,q);
3525 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3526 SetPixelRed(image,ClampToQuantum(result.red),q);
3527 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3528 SetPixelGreen(image,ClampToQuantum(result.green),q);
3529 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3530 SetPixelBlue(image,ClampToQuantum(result.blue),q);
3531 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3532 (image->colorspace == CMYKColorspace))
3533 SetPixelBlack(image,ClampToQuantum(result.black),q);
3534 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3535 (image->matte == MagickTrue))
3536 SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3539 /* Count up changed pixels */
3540 if ((GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q)) ||
3541 (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q)) ||
3542 (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q)) ||
3543 (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q)) ||
3544 ((image->colorspace == CMYKColorspace) &&
3545 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3546 changed++; /* The pixel was changed in some way! */
3548 p+=GetPixelChannels(image); /* increment pixel buffers */
3549 q+=GetPixelChannels(image);
3552 if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3554 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3555 if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3561 /* Do the reversed pass through the image */
3562 for (y=(ssize_t)image->rows-1; y >= 0; y--)
3564 register const Quantum
3576 if (status == MagickFalse)
3578 /* NOTE read virtual pixels, and authentic pixels, from the same image!
3579 ** we read using virtual to get virtual pixel handling, but write back
3580 ** into the same image.
3582 ** Only the bottom half of the kernel will be processes as we
3585 p=GetCacheViewVirtualPixels(virt_view,-offx,y,virt_width,(size_t)
3586 kernel->y+1,exception);
3587 q=GetCacheViewAuthenticPixels(auth_view, 0, y, image->columns, 1,
3589 if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
3591 if (status == MagickFalse)
3594 /* adjust positions to end of row */
3595 p += (image->columns-1)*GetPixelChannels(image);
3596 q += (image->columns-1)*GetPixelChannels(image);
3598 /* offset to origin in 'p'. while 'q' points to it directly */
3601 for (x=(ssize_t)image->columns-1; x >= 0; x--)
3609 register const double
3612 register const Quantum
3618 /* Default - previously modified pixel */
3619 GetPixelInfo(image,&result);
3620 GetPixelInfoPixel(image,q,&result);
3621 if ( method != VoronoiMorphology )
3622 result.alpha = QuantumRange - result.alpha;
3625 case DistanceMorphology:
3626 /* Add kernel Value and select the minimum value found. */
3627 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3629 for (v=offy; v < (ssize_t) kernel->height; v++) {
3630 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3631 if ( IsNan(*k) ) continue;
3632 Minimize(result.red, (*k)+
3633 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3634 Minimize(result.green, (*k)+
3635 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3636 Minimize(result.blue, (*k)+
3637 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3638 if ( image->colorspace == CMYKColorspace)
3639 Minimize(result.black,(*k)+
3640 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3641 Minimize(result.alpha, (*k)+
3642 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3644 k_pixels += virt_width*GetPixelChannels(image);
3646 /* repeat with the just processed pixels of this row */
3647 k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3648 k_pixels = q-offx*GetPixelChannels(image);
3649 for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3650 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3651 if ( IsNan(*k) ) continue;
3652 Minimize(result.red, (*k)+
3653 GetPixelRed(image,k_pixels+u*GetPixelChannels(image)));
3654 Minimize(result.green, (*k)+
3655 GetPixelGreen(image,k_pixels+u*GetPixelChannels(image)));
3656 Minimize(result.blue, (*k)+
3657 GetPixelBlue(image,k_pixels+u*GetPixelChannels(image)));
3658 if ( image->colorspace == CMYKColorspace)
3659 Minimize(result.black, (*k)+
3660 GetPixelBlack(image,k_pixels+u*GetPixelChannels(image)));
3661 Minimize(result.alpha, (*k)+
3662 GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)));
3665 case VoronoiMorphology:
3666 /* Apply Distance to 'Matte' channel, coping the closest color.
3668 ** This is experimental, and realy the 'alpha' component should
3669 ** be completely separate 'masking' channel.
3671 k = &kernel->values[ kernel->width*(kernel->y+1)-1 ];
3673 for (v=offy; v < (ssize_t) kernel->height; v++) {
3674 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
3675 if ( IsNan(*k) ) continue;
3676 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3678 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3683 k_pixels += virt_width*GetPixelChannels(image);
3685 /* repeat with the just processed pixels of this row */
3686 k = &kernel->values[ kernel->width*(kernel->y)+kernel->x-1 ];
3687 k_pixels = q-offx*GetPixelChannels(image);
3688 for (u=offx+1; u < (ssize_t) kernel->width; u++, k--) {
3689 if ( (x+u-offx) >= (ssize_t)image->columns ) continue;
3690 if ( IsNan(*k) ) continue;
3691 if( result.alpha > (*k)+GetPixelAlpha(image,k_pixels+u*GetPixelChannels(image)) )
3693 GetPixelInfoPixel(image,k_pixels+u*GetPixelChannels(image),
3700 /* result directly calculated or assigned */
3703 /* Assign the resulting pixel values - Clamping Result */
3705 case VoronoiMorphology:
3706 SetPixelInfoPixel(image,&result,q);
3709 if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
3710 SetPixelRed(image,ClampToQuantum(result.red),q);
3711 if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
3712 SetPixelGreen(image,ClampToQuantum(result.green),q);
3713 if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
3714 SetPixelBlue(image,ClampToQuantum(result.blue),q);
3715 if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
3716 (image->colorspace == CMYKColorspace))
3717 SetPixelBlack(image,ClampToQuantum(result.black),q);
3718 if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0 &&
3719 (image->matte == MagickTrue))
3720 SetPixelAlpha(image,ClampToQuantum(result.alpha),q);
3723 /* Count up changed pixels */
3724 if ( (GetPixelRed(image,p+r*GetPixelChannels(image)) != GetPixelRed(image,q))
3725 || (GetPixelGreen(image,p+r*GetPixelChannels(image)) != GetPixelGreen(image,q))
3726 || (GetPixelBlue(image,p+r*GetPixelChannels(image)) != GetPixelBlue(image,q))
3727 || (GetPixelAlpha(image,p+r*GetPixelChannels(image)) != GetPixelAlpha(image,q))
3728 || ((image->colorspace == CMYKColorspace) &&
3729 (GetPixelBlack(image,p+r*GetPixelChannels(image)) != GetPixelBlack(image,q))))
3730 changed++; /* The pixel was changed in some way! */
3732 p-=GetPixelChannels(image); /* go backward through pixel buffers */
3733 q-=GetPixelChannels(image);
3735 if ( SyncCacheViewAuthenticPixels(auth_view,exception) == MagickFalse)
3737 if (image->progress_monitor != (MagickProgressMonitor) NULL)
3738 if ( SetImageProgress(image,MorphologyTag,progress++,image->rows)
3744 auth_view=DestroyCacheView(auth_view);
3745 virt_view=DestroyCacheView(virt_view);
3746 return(status ? (ssize_t) changed : -1);
3749 /* Apply a Morphology by calling one of the above low level primitive
3750 ** application functions. This function handles any iteration loops,
3751 ** composition or re-iteration of results, and compound morphology methods
3752 ** that is based on multiple low-level (staged) morphology methods.
3754 ** Basically this provides the complex glue between the requested morphology
3755 ** method and raw low-level implementation (above).
3757 MagickPrivate Image *MorphologyApply(const Image *image,
3758 const MorphologyMethod method, const ssize_t iterations,
3759 const KernelInfo *kernel, const CompositeOperator compose,const double bias,
3760 ExceptionInfo *exception)
3766 *curr_image, /* Image we are working with or iterating */
3767 *work_image, /* secondary image for primitive iteration */
3768 *save_image, /* saved image - for 'edge' method only */
3769 *rslt_image; /* resultant image - after multi-kernel handling */
3772 *reflected_kernel, /* A reflected copy of the kernel (if needed) */
3773 *norm_kernel, /* the current normal un-reflected kernel */
3774 *rflt_kernel, /* the current reflected kernel (if needed) */
3775 *this_kernel; /* the kernel being applied */
3778 primitive; /* the current morphology primitive being applied */
3781 rslt_compose; /* multi-kernel compose method for results to use */
3784 special, /* do we use a direct modify function? */
3785 verbose; /* verbose output of results */
3788 method_loop, /* Loop 1: number of compound method iterations (norm 1) */
3789 method_limit, /* maximum number of compound method iterations */
3790 kernel_number, /* Loop 2: the kernel number being applied */
3791 stage_loop, /* Loop 3: primitive loop for compound morphology */
3792 stage_limit, /* how many primitives are in this compound */
3793 kernel_loop, /* Loop 4: iterate the kernel over image */
3794 kernel_limit, /* number of times to iterate kernel */
3795 count, /* total count of primitive steps applied */
3796 kernel_changed, /* total count of changed using iterated kernel */
3797 method_changed; /* total count of changed over method iteration */
3800 changed; /* number pixels changed by last primitive operation */
3805 assert(image != (Image *) NULL);
3806 assert(image->signature == MagickSignature);
3807 assert(kernel != (KernelInfo *) NULL);
3808 assert(kernel->signature == MagickSignature);
3809 assert(exception != (ExceptionInfo *) NULL);
3810 assert(exception->signature == MagickSignature);
3812 count = 0; /* number of low-level morphology primitives performed */
3813 if ( iterations == 0 )
3814 return((Image *)NULL); /* null operation - nothing to do! */
3816 kernel_limit = (size_t) iterations;
3817 if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
3818 kernel_limit = image->columns>image->rows ? image->columns : image->rows;
3820 verbose = IsStringTrue(GetImageArtifact(image,"verbose"));
3822 /* initialise for cleanup */
3823 curr_image = (Image *) image;
3824 curr_compose = image->compose;
3825 (void) curr_compose;
3826 work_image = save_image = rslt_image = (Image *) NULL;
3827 reflected_kernel = (KernelInfo *) NULL;
3829 /* Initialize specific methods
3830 * + which loop should use the given iteratations
3831 * + how many primitives make up the compound morphology
3832 * + multi-kernel compose method to use (by default)
3834 method_limit = 1; /* just do method once, unless otherwise set */
3835 stage_limit = 1; /* assume method is not a compound */
3836 special = MagickFalse; /* assume it is NOT a direct modify primitive */
3837 rslt_compose = compose; /* and we are composing multi-kernels as given */
3839 case SmoothMorphology: /* 4 primitive compound morphology */
3842 case OpenMorphology: /* 2 primitive compound morphology */
3843 case OpenIntensityMorphology:
3844 case TopHatMorphology:
3845 case CloseMorphology:
3846 case CloseIntensityMorphology:
3847 case BottomHatMorphology:
3848 case EdgeMorphology:
3851 case HitAndMissMorphology:
3852 rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
3854 case ThinningMorphology:
3855 case ThickenMorphology:
3856 method_limit = kernel_limit; /* iterate the whole method */
3857 kernel_limit = 1; /* do not do kernel iteration */
3859 case DistanceMorphology:
3860 case VoronoiMorphology:
3861 special = MagickTrue; /* use special direct primative */
3867 /* Apply special methods with special requirments
3868 ** For example, single run only, or post-processing requirements
3870 if ( special == MagickTrue )
3872 rslt_image=CloneImage(image,0,0,MagickTrue,exception);
3873 if (rslt_image == (Image *) NULL)
3875 if (SetImageStorageClass(rslt_image,DirectClass,exception) == MagickFalse)
3878 changed = MorphologyPrimitiveDirect(rslt_image, method,
3881 if ( IfMagickTrue(verbose) )
3882 (void) (void) FormatLocaleFile(stderr,
3883 "%s:%.20g.%.20g #%.20g => Changed %.20g\n",
3884 CommandOptionToMnemonic(MagickMorphologyOptions, method),
3885 1.0,0.0,1.0, (double) changed);
3890 if ( method == VoronoiMorphology ) {
3891 /* Preserve the alpha channel of input image - but turned off */
3892 (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3894 (void) CompositeImage(rslt_image,image,CopyAlphaCompositeOp,
3895 MagickTrue,0,0,exception);
3896 (void) SetImageAlphaChannel(rslt_image, DeactivateAlphaChannel,
3902 /* Handle user (caller) specified multi-kernel composition method */
3903 if ( compose != UndefinedCompositeOp )
3904 rslt_compose = compose; /* override default composition for method */
3905 if ( rslt_compose == UndefinedCompositeOp )
3906 rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
3908 /* Some methods require a reflected kernel to use with primitives.
3909 * Create the reflected kernel for those methods. */
3911 case CorrelateMorphology:
3912 case CloseMorphology:
3913 case CloseIntensityMorphology:
3914 case BottomHatMorphology:
3915 case SmoothMorphology:
3916 reflected_kernel = CloneKernelInfo(kernel);
3917 if (reflected_kernel == (KernelInfo *) NULL)
3919 RotateKernelInfo(reflected_kernel,180);
3925 /* Loops around more primitive morpholgy methods
3926 ** erose, dilate, open, close, smooth, edge, etc...
3928 /* Loop 1: iterate the compound method */
3931 while ( method_loop < method_limit && method_changed > 0 ) {
3935 /* Loop 2: iterate over each kernel in a multi-kernel list */
3936 norm_kernel = (KernelInfo *) kernel;
3937 this_kernel = (KernelInfo *) kernel;
3938 rflt_kernel = reflected_kernel;
3941 while ( norm_kernel != NULL ) {
3943 /* Loop 3: Compound Morphology Staging - Select Primative to apply */
3944 stage_loop = 0; /* the compound morphology stage number */
3945 while ( stage_loop < stage_limit ) {
3946 stage_loop++; /* The stage of the compound morphology */
3948 /* Select primitive morphology for this stage of compound method */
3949 this_kernel = norm_kernel; /* default use unreflected kernel */
3950 primitive = method; /* Assume method is a primitive */
3952 case ErodeMorphology: /* just erode */
3953 case EdgeInMorphology: /* erode and image difference */
3954 primitive = ErodeMorphology;
3956 case DilateMorphology: /* just dilate */
3957 case EdgeOutMorphology: /* dilate and image difference */
3958 primitive = DilateMorphology;
3960 case OpenMorphology: /* erode then dialate */
3961 case TopHatMorphology: /* open and image difference */
3962 primitive = ErodeMorphology;
3963 if ( stage_loop == 2 )
3964 primitive = DilateMorphology;
3966 case OpenIntensityMorphology:
3967 primitive = ErodeIntensityMorphology;
3968 if ( stage_loop == 2 )
3969 primitive = DilateIntensityMorphology;
3971 case CloseMorphology: /* dilate, then erode */
3972 case BottomHatMorphology: /* close and image difference */
3973 this_kernel = rflt_kernel; /* use the reflected kernel */
3974 primitive = DilateMorphology;
3975 if ( stage_loop == 2 )
3976 primitive = ErodeMorphology;
3978 case CloseIntensityMorphology:
3979 this_kernel = rflt_kernel; /* use the reflected kernel */
3980 primitive = DilateIntensityMorphology;
3981 if ( stage_loop == 2 )
3982 primitive = ErodeIntensityMorphology;
3984 case SmoothMorphology: /* open, close */
3985 switch ( stage_loop ) {
3986 case 1: /* start an open method, which starts with Erode */
3987 primitive = ErodeMorphology;
3989 case 2: /* now Dilate the Erode */
3990 primitive = DilateMorphology;
3992 case 3: /* Reflect kernel a close */
3993 this_kernel = rflt_kernel; /* use the reflected kernel */
3994 primitive = DilateMorphology;
3996 case 4: /* Finish the Close */
3997 this_kernel = rflt_kernel; /* use the reflected kernel */
3998 primitive = ErodeMorphology;
4002 case EdgeMorphology: /* dilate and erode difference */
4003 primitive = DilateMorphology;
4004 if ( stage_loop == 2 ) {
4005 save_image = curr_image; /* save the image difference */
4006 curr_image = (Image *) image;
4007 primitive = ErodeMorphology;
4010 case CorrelateMorphology:
4011 /* A Correlation is a Convolution with a reflected kernel.
4012 ** However a Convolution is a weighted sum using a reflected
4013 ** kernel. It may seem stange to convert a Correlation into a
4014 ** Convolution as the Correlation is the simplier method, but
4015 ** Convolution is much more commonly used, and it makes sense to
4016 ** implement it directly so as to avoid the need to duplicate the
4017 ** kernel when it is not required (which is typically the
4020 this_kernel = rflt_kernel; /* use the reflected kernel */
4021 primitive = ConvolveMorphology;
4026 assert( this_kernel != (KernelInfo *) NULL );
4028 /* Extra information for debugging compound operations */
4029 if ( IfMagickTrue(verbose) ) {
4030 if ( stage_limit > 1 )
4031 (void) FormatLocaleString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ",
4032 CommandOptionToMnemonic(MagickMorphologyOptions,method),(double)
4033 method_loop,(double) stage_loop);
4034 else if ( primitive != method )
4035 (void) FormatLocaleString(v_info, MaxTextExtent, "%s:%.20g -> ",
4036 CommandOptionToMnemonic(MagickMorphologyOptions, method),(double)
4042 /* Loop 4: Iterate the kernel with primitive */
4046 while ( kernel_loop < kernel_limit && changed > 0 ) {
4047 kernel_loop++; /* the iteration of this kernel */
4049 /* Create a clone as the destination image, if not yet defined */
4050 if ( work_image == (Image *) NULL )
4052 work_image=CloneImage(image,0,0,MagickTrue,exception);
4053 if (work_image == (Image *) NULL)
4055 if (SetImageStorageClass(work_image,DirectClass,exception) == MagickFalse)
4057 /* work_image->type=image->type; ??? */
4060 /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
4062 changed = MorphologyPrimitive(curr_image, work_image, primitive,
4063 this_kernel, bias, exception);
4065 if ( IfMagickTrue(verbose) ) {
4066 if ( kernel_loop > 1 )
4067 (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line from previous */
4068 (void) (void) FormatLocaleFile(stderr,
4069 "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
4070 v_info,CommandOptionToMnemonic(MagickMorphologyOptions,
4071 primitive),(this_kernel == rflt_kernel ) ? "*" : "",
4072 (double) (method_loop+kernel_loop-1),(double) kernel_number,
4073 (double) count,(double) changed);
4077 kernel_changed += changed;
4078 method_changed += changed;
4080 /* prepare next loop */
4081 { Image *tmp = work_image; /* swap images for iteration */
4082 work_image = curr_image;
4085 if ( work_image == image )
4086 work_image = (Image *) NULL; /* replace input 'image' */
4088 } /* End Loop 4: Iterate the kernel with primitive */
4090 if ( IfMagickTrue(verbose) && kernel_changed != (size_t)changed )
4091 (void) FormatLocaleFile(stderr, " Total %.20g",(double) kernel_changed);
4092 if ( IfMagickTrue(verbose) && stage_loop < stage_limit )
4093 (void) FormatLocaleFile(stderr, "\n"); /* add end-of-line before looping */
4096 (void) FormatLocaleFile(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
4097 (void) FormatLocaleFile(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
4098 (void) FormatLocaleFile(stderr, " work =0x%lx\n", (unsigned long)work_image);
4099 (void) FormatLocaleFile(stderr, " save =0x%lx\n", (unsigned long)save_image);
4100 (void) FormatLocaleFile(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
4103 } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
4105 /* Final Post-processing for some Compound Methods
4107 ** The removal of any 'Sync' channel flag in the Image Compositon
4108 ** below ensures the methematical compose method is applied in a
4109 ** purely mathematical way, and only to the selected channels.
4110 ** Turn off SVG composition 'alpha blending'.
4113 case EdgeOutMorphology:
4114 case EdgeInMorphology:
4115 case TopHatMorphology:
4116 case BottomHatMorphology:
4117 if ( IfMagickTrue(verbose) )
4118 (void) FormatLocaleFile(stderr,
4119 "\n%s: Difference with original image",CommandOptionToMnemonic(
4120 MagickMorphologyOptions, method) );
4121 (void) CompositeImage(curr_image,image,DifferenceCompositeOp,
4122 MagickTrue,0,0,exception);
4124 case EdgeMorphology:
4125 if ( IfMagickTrue(verbose) )
4126 (void) FormatLocaleFile(stderr,
4127 "\n%s: Difference of Dilate and Erode",CommandOptionToMnemonic(
4128 MagickMorphologyOptions, method) );
4129 (void) CompositeImage(curr_image,save_image,DifferenceCompositeOp,
4130 MagickTrue,0,0,exception);
4131 save_image = DestroyImage(save_image); /* finished with save image */
4137 /* multi-kernel handling: re-iterate, or compose results */
4138 if ( kernel->next == (KernelInfo *) NULL )
4139 rslt_image = curr_image; /* just return the resulting image */
4140 else if ( rslt_compose == NoCompositeOp )
4141 { if ( IfMagickTrue(verbose) ) {
4142 if ( this_kernel->next != (KernelInfo *) NULL )
4143 (void) FormatLocaleFile(stderr, " (re-iterate)");
4145 (void) FormatLocaleFile(stderr, " (done)");
4147 rslt_image = curr_image; /* return result, and re-iterate */
4149 else if ( rslt_image == (Image *) NULL)
4150 { if ( IfMagickTrue(verbose) )
4151 (void) FormatLocaleFile(stderr, " (save for compose)");
4152 rslt_image = curr_image;
4153 curr_image = (Image *) image; /* continue with original image */
4156 { /* Add the new 'current' result to the composition
4158 ** The removal of any 'Sync' channel flag in the Image Compositon
4159 ** below ensures the methematical compose method is applied in a
4160 ** purely mathematical way, and only to the selected channels.
4161 ** IE: Turn off SVG composition 'alpha blending'.
4163 if ( IfMagickTrue(verbose) )
4164 (void) FormatLocaleFile(stderr, " (compose \"%s\")",
4165 CommandOptionToMnemonic(MagickComposeOptions, rslt_compose) );
4166 (void) CompositeImage(rslt_image,curr_image,rslt_compose,MagickTrue,
4168 curr_image = DestroyImage(curr_image);
4169 curr_image = (Image *) image; /* continue with original image */
4171 if ( IfMagickTrue(verbose) )
4172 (void) FormatLocaleFile(stderr, "\n");
4174 /* loop to the next kernel in a multi-kernel list */
4175 norm_kernel = norm_kernel->next;
4176 if ( rflt_kernel != (KernelInfo *) NULL )
4177 rflt_kernel = rflt_kernel->next;
4179 } /* End Loop 2: Loop over each kernel */
4181 } /* End Loop 1: compound method interation */
4185 /* Yes goto's are bad, but it makes cleanup lot more efficient */
4187 if ( curr_image == rslt_image )
4188 curr_image = (Image *) NULL;
4189 if ( rslt_image != (Image *) NULL )
4190 rslt_image = DestroyImage(rslt_image);
4192 if ( curr_image == rslt_image || curr_image == image )
4193 curr_image = (Image *) NULL;
4194 if ( curr_image != (Image *) NULL )
4195 curr_image = DestroyImage(curr_image);
4196 if ( work_image != (Image *) NULL )
4197 work_image = DestroyImage(work_image);
4198 if ( save_image != (Image *) NULL )
4199 save_image = DestroyImage(save_image);
4200 if ( reflected_kernel != (KernelInfo *) NULL )
4201 reflected_kernel = DestroyKernelInfo(reflected_kernel);
4207 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4211 % M o r p h o l o g y I m a g e %
4215 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4217 % MorphologyImage() applies a user supplied kernel to the image
4218 % according to the given mophology method.
4220 % This function applies any and all user defined settings before calling
4221 % the above internal function MorphologyApply().
4223 % User defined settings include...
4224 % * Output Bias for Convolution and correlation ("-define convolve:bias=??")
4225 % * Kernel Scale/normalize settings ("-define convolve:scale=??")
4226 % This can also includes the addition of a scaled unity kernel.
4227 % * Show Kernel being applied ("-define showkernel=1")
4229 % Other operators that do not want user supplied options interfering,
4230 % especially "convolve:bias" and "showkernel" should use MorphologyApply()
4233 % The format of the MorphologyImage method is:
4235 % Image *MorphologyImage(const Image *image,MorphologyMethod method,
4236 % const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
4238 % A description of each parameter follows:
4240 % o image: the image.
4242 % o method: the morphology method to be applied.
4244 % o iterations: apply the operation this many times (or no change).
4245 % A value of -1 means loop until no change found.
4246 % How this is applied may depend on the morphology method.
4247 % Typically this is a value of 1.
4249 % o kernel: An array of double representing the morphology kernel.
4250 % Warning: kernel may be normalized for the Convolve method.
4252 % o exception: return any errors or warnings in this structure.
4255 MagickExport Image *MorphologyImage(const Image *image,
4256 const MorphologyMethod method,const ssize_t iterations,
4257 const KernelInfo *kernel,ExceptionInfo *exception)
4271 curr_kernel = (KernelInfo *) kernel;
4273 compose = (ssize_t)UndefinedCompositeOp; /* use default for method */
4275 /* Apply Convolve/Correlate Normalization and Scaling Factors.
4276 * This is done BEFORE the ShowKernelInfo() function is called so that
4277 * users can see the results of the 'option:convolve:scale' option.
4279 if ( method == ConvolveMorphology || method == CorrelateMorphology ) {
4283 /* Get the bias value as it will be needed */
4284 artifact = GetImageArtifact(image,"convolve:bias");
4285 if ( artifact != (const char *) NULL) {
4286 if (IfMagickFalse(IsGeometry(artifact)))
4287 (void) ThrowMagickException(exception,GetMagickModule(),
4288 OptionWarning,"InvalidSetting","'%s' '%s'",
4289 "convolve:bias",artifact);
4291 bias=StringToDoubleInterval(artifact,(double) QuantumRange+1.0);
4294 /* Scale kernel according to user wishes */
4295 artifact = GetImageArtifact(image,"convolve:scale");
4296 if ( artifact != (const char *)NULL ) {
4297 if (IfMagickFalse(IsGeometry(artifact)))
4298 (void) ThrowMagickException(exception,GetMagickModule(),
4299 OptionWarning,"InvalidSetting","'%s' '%s'",
4300 "convolve:scale",artifact);
4302 if ( curr_kernel == kernel )
4303 curr_kernel = CloneKernelInfo(kernel);
4304 if (curr_kernel == (KernelInfo *) NULL)
4305 return((Image *) NULL);
4306 ScaleGeometryKernelInfo(curr_kernel, artifact);
4311 /* display the (normalized) kernel via stderr */
4312 if ( IfStringTrue(GetImageArtifact(image,"showkernel"))
4313 || IfStringTrue(GetImageArtifact(image,"convolve:showkernel"))
4314 || IfStringTrue(GetImageArtifact(image,"morphology:showkernel")) )
4315 ShowKernelInfo(curr_kernel);
4317 /* Override the default handling of multi-kernel morphology results
4318 * If 'Undefined' use the default method
4319 * If 'None' (default for 'Convolve') re-iterate previous result
4320 * Otherwise merge resulting images using compose method given.
4321 * Default for 'HitAndMiss' is 'Lighten'.
4328 artifact = GetImageArtifact(image,"morphology:compose");
4329 if ( artifact != (const char *) NULL) {
4330 parse=ParseCommandOption(MagickComposeOptions,
4331 MagickFalse,artifact);
4333 (void) ThrowMagickException(exception,GetMagickModule(),
4334 OptionWarning,"UnrecognizedComposeOperator","'%s' '%s'",
4335 "morphology:compose",artifact);
4337 compose=(CompositeOperator)parse;
4340 /* Apply the Morphology */
4341 morphology_image = MorphologyApply(image,method,iterations,
4342 curr_kernel,compose,bias,exception);
4344 /* Cleanup and Exit */
4345 if ( curr_kernel != kernel )
4346 curr_kernel=DestroyKernelInfo(curr_kernel);
4347 return(morphology_image);
4351 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4355 + R o t a t e K e r n e l I n f o %
4359 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4361 % RotateKernelInfo() rotates the kernel by the angle given.
4363 % Currently it is restricted to 90 degree angles, of either 1D kernels
4364 % or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
4365 % It will ignore usless rotations for specific 'named' built-in kernels.
4367 % The format of the RotateKernelInfo method is:
4369 % void RotateKernelInfo(KernelInfo *kernel, double angle)
4371 % A description of each parameter follows:
4373 % o kernel: the Morphology/Convolution kernel
4375 % o angle: angle to rotate in degrees
4377 % This function is currently internal to this module only, but can be exported
4378 % to other modules if needed.
4380 static void RotateKernelInfo(KernelInfo *kernel, double angle)
4382 /* angle the lower kernels first */
4383 if ( kernel->next != (KernelInfo *) NULL)
4384 RotateKernelInfo(kernel->next, angle);
4386 /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
4388 ** TODO: expand beyond simple 90 degree rotates, flips and flops
4391 /* Modulus the angle */
4392 angle = fmod(angle, 360.0);
4396 if ( 337.5 < angle || angle <= 22.5 )
4397 return; /* Near zero angle - no change! - At least not at this time */
4399 /* Handle special cases */
4400 switch (kernel->type) {
4401 /* These built-in kernels are cylindrical kernels, rotating is useless */
4402 case GaussianKernel:
4407 case LaplacianKernel:
4408 case ChebyshevKernel:
4409 case ManhattanKernel:
4410 case EuclideanKernel:
4413 /* These may be rotatable at non-90 angles in the future */
4414 /* but simply rotating them in multiples of 90 degrees is useless */
4421 /* These only allows a +/-90 degree rotation (by transpose) */
4422 /* A 180 degree rotation is useless */
4424 if ( 135.0 < angle && angle <= 225.0 )
4426 if ( 225.0 < angle && angle <= 315.0 )
4433 /* Attempt rotations by 45 degrees -- 3x3 kernels only */
4434 if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
4436 if ( kernel->width == 3 && kernel->height == 3 )
4437 { /* Rotate a 3x3 square by 45 degree angle */
4438 MagickRealType t = kernel->values[0];
4439 kernel->values[0] = kernel->values[3];
4440 kernel->values[3] = kernel->values[6];
4441 kernel->values[6] = kernel->values[7];
4442 kernel->values[7] = kernel->values[8];
4443 kernel->values[8] = kernel->values[5];
4444 kernel->values[5] = kernel->values[2];
4445 kernel->values[2] = kernel->values[1];
4446 kernel->values[1] = t;
4447 /* rotate non-centered origin */
4448 if ( kernel->x != 1 || kernel->y != 1 ) {
4450 x = (ssize_t) kernel->x-1;
4451 y = (ssize_t) kernel->y-1;
4452 if ( x == y ) x = 0;
4453 else if ( x == 0 ) x = -y;
4454 else if ( x == -y ) y = 0;
4455 else if ( y == 0 ) y = x;
4456 kernel->x = (ssize_t) x+1;
4457 kernel->y = (ssize_t) y+1;
4459 angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */
4460 kernel->angle = fmod(kernel->angle+45.0, 360.0);
4463 perror("Unable to rotate non-3x3 kernel by 45 degrees");
4465 if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 )
4467 if ( kernel->width == 1 || kernel->height == 1 )
4468 { /* Do a transpose of a 1 dimensional kernel,
4469 ** which results in a fast 90 degree rotation of some type.
4473 t = (ssize_t) kernel->width;
4474 kernel->width = kernel->height;
4475 kernel->height = (size_t) t;
4477 kernel->x = kernel->y;
4479 if ( kernel->width == 1 ) {
4480 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
4481 kernel->angle = fmod(kernel->angle+90.0, 360.0);
4483 angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */
4484 kernel->angle = fmod(kernel->angle+270.0, 360.0);
4487 else if ( kernel->width == kernel->height )
4488 { /* Rotate a square array of values by 90 degrees */
4494 for( i=0, x=kernel->width-1; i<=x; i++, x--)
4495 for( j=0, y=kernel->height-1; j<y; j++, y--)
4496 { t = k[i+j*kernel->width];
4497 k[i+j*kernel->width] = k[j+x*kernel->width];
4498 k[j+x*kernel->width] = k[x+y*kernel->width];
4499 k[x+y*kernel->width] = k[y+i*kernel->width];
4500 k[y+i*kernel->width] = t;
4503 /* rotate the origin - relative to center of array */
4504 { register ssize_t x,y;
4505 x = (ssize_t) (kernel->x*2-kernel->width+1);
4506 y = (ssize_t) (kernel->y*2-kernel->height+1);
4507 kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2;
4508 kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2;
4510 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
4511 kernel->angle = fmod(kernel->angle+90.0, 360.0);
4514 perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
4516 if ( 135.0 < angle && angle <= 225.0 )
4518 /* For a 180 degree rotation - also know as a reflection
4519 * This is actually a very very common operation!
4520 * Basically all that is needed is a reversal of the kernel data!
4521 * And a reflection of the origon
4534 j=(ssize_t) (kernel->width*kernel->height-1);
4535 for (i=0; i < j; i++, j--)
4536 t=k[i], k[i]=k[j], k[j]=t;
4538 kernel->x = (ssize_t) kernel->width - kernel->x - 1;
4539 kernel->y = (ssize_t) kernel->height - kernel->y - 1;
4540 angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */
4541 kernel->angle = fmod(kernel->angle+180.0, 360.0);
4543 /* At this point angle should at least between -45 (315) and +45 degrees
4544 * In the future some form of non-orthogonal angled rotates could be
4545 * performed here, posibily with a linear kernel restriction.
4552 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4556 % S c a l e G e o m e t r y K e r n e l I n f o %
4560 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4562 % ScaleGeometryKernelInfo() takes a geometry argument string, typically
4563 % provided as a "-set option:convolve:scale {geometry}" user setting,
4564 % and modifies the kernel according to the parsed arguments of that setting.
4566 % The first argument (and any normalization flags) are passed to
4567 % ScaleKernelInfo() to scale/normalize the kernel. The second argument
4568 % is then passed to UnityAddKernelInfo() to add a scled unity kernel
4569 % into the scaled/normalized kernel.
4571 % The format of the ScaleGeometryKernelInfo method is:
4573 % void ScaleGeometryKernelInfo(KernelInfo *kernel,
4574 % const double scaling_factor,const MagickStatusType normalize_flags)
4576 % A description of each parameter follows:
4578 % o kernel: the Morphology/Convolution kernel to modify
4581 % The geometry string to parse, typically from the user provided
4582 % "-set option:convolve:scale {geometry}" setting.
4585 MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
4586 const char *geometry)
4595 SetGeometryInfo(&args);
4596 flags = ParseGeometry(geometry, &args);
4599 /* For Debugging Geometry Input */
4600 (void) FormatLocaleFile(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
4601 flags, args.rho, args.sigma, args.xi, args.psi );
4604 if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/
4605 args.rho *= 0.01, args.sigma *= 0.01;
4607 if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */
4609 if ( (flags & SigmaValue) == 0 )
4612 /* Scale/Normalize the input kernel */
4613 ScaleKernelInfo(kernel, args.rho, flags);
4615 /* Add Unity Kernel, for blending with original */
4616 if ( (flags & SigmaValue) != 0 )
4617 UnityAddKernelInfo(kernel, args.sigma);
4622 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4626 % S c a l e K e r n e l I n f o %
4630 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4632 % ScaleKernelInfo() scales the given kernel list by the given amount, with or
4633 % without normalization of the sum of the kernel values (as per given flags).
4635 % By default (no flags given) the values within the kernel is scaled
4636 % directly using given scaling factor without change.
4638 % If either of the two 'normalize_flags' are given the kernel will first be
4639 % normalized and then further scaled by the scaling factor value given.
4641 % Kernel normalization ('normalize_flags' given) is designed to ensure that
4642 % any use of the kernel scaling factor with 'Convolve' or 'Correlate'
4643 % morphology methods will fall into -1.0 to +1.0 range. Note that for
4644 % non-HDRI versions of IM this may cause images to have any negative results
4645 % clipped, unless some 'bias' is used.
4647 % More specifically. Kernels which only contain positive values (such as a
4648 % 'Gaussian' kernel) will be scaled so that those values sum to +1.0,
4649 % ensuring a 0.0 to +1.0 output range for non-HDRI images.
4651 % For Kernels that contain some negative values, (such as 'Sharpen' kernels)
4652 % the kernel will be scaled by the absolute of the sum of kernel values, so
4653 % that it will generally fall within the +/- 1.0 range.
4655 % For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
4656 % will be scaled by just the sum of the postive values, so that its output
4657 % range will again fall into the +/- 1.0 range.
4659 % For special kernels designed for locating shapes using 'Correlate', (often
4660 % only containing +1 and -1 values, representing foreground/brackground
4661 % matching) a special normalization method is provided to scale the positive
4662 % values separately to those of the negative values, so the kernel will be
4663 % forced to become a zero-sum kernel better suited to such searches.
4665 % WARNING: Correct normalization of the kernel assumes that the '*_range'
4666 % attributes within the kernel structure have been correctly set during the
4669 % NOTE: The values used for 'normalize_flags' have been selected specifically
4670 % to match the use of geometry options, so that '!' means NormalizeValue, '^'
4671 % means CorrelateNormalizeValue. All other GeometryFlags values are ignored.
4673 % The format of the ScaleKernelInfo method is:
4675 % void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
4676 % const MagickStatusType normalize_flags )
4678 % A description of each parameter follows:
4680 % o kernel: the Morphology/Convolution kernel
4683 % multiply all values (after normalization) by this factor if not
4684 % zero. If the kernel is normalized regardless of any flags.
4686 % o normalize_flags:
4687 % GeometryFlags defining normalization method to use.
4688 % specifically: NormalizeValue, CorrelateNormalizeValue,
4689 % and/or PercentValue
4692 MagickExport void ScaleKernelInfo(KernelInfo *kernel,
4693 const double scaling_factor,const GeometryFlags normalize_flags)
4702 /* do the other kernels in a multi-kernel list first */
4703 if ( kernel->next != (KernelInfo *) NULL)
4704 ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
4706 /* Normalization of Kernel */
4708 if ( (normalize_flags&NormalizeValue) != 0 ) {
4709 if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon )
4710 /* non-zero-summing kernel (generally positive) */
4711 pos_scale = fabs(kernel->positive_range + kernel->negative_range);
4713 /* zero-summing kernel */
4714 pos_scale = kernel->positive_range;
4716 /* Force kernel into a normalized zero-summing kernel */
4717 if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
4718 pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon )
4719 ? kernel->positive_range : 1.0;
4720 neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon )
4721 ? -kernel->negative_range : 1.0;
4724 neg_scale = pos_scale;
4726 /* finialize scaling_factor for positive and negative components */
4727 pos_scale = scaling_factor/pos_scale;
4728 neg_scale = scaling_factor/neg_scale;
4730 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
4731 if ( ! IsNan(kernel->values[i]) )
4732 kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
4734 /* convolution output range */
4735 kernel->positive_range *= pos_scale;
4736 kernel->negative_range *= neg_scale;
4737 /* maximum and minimum values in kernel */
4738 kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
4739 kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
4741 /* swap kernel settings if user's scaling factor is negative */
4742 if ( scaling_factor < MagickEpsilon ) {
4744 t = kernel->positive_range;
4745 kernel->positive_range = kernel->negative_range;
4746 kernel->negative_range = t;
4747 t = kernel->maximum;
4748 kernel->maximum = kernel->minimum;
4749 kernel->minimum = 1;
4756 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4760 % S h o w K e r n e l I n f o %
4764 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4766 % ShowKernelInfo() outputs the details of the given kernel defination to
4767 % standard error, generally due to a users 'showkernel' option request.
4769 % The format of the ShowKernel method is:
4771 % void ShowKernelInfo(const KernelInfo *kernel)
4773 % A description of each parameter follows:
4775 % o kernel: the Morphology/Convolution kernel
4778 MagickPrivate void ShowKernelInfo(const KernelInfo *kernel)
4786 for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) {
4788 (void) FormatLocaleFile(stderr, "Kernel");
4789 if ( kernel->next != (KernelInfo *) NULL )
4790 (void) FormatLocaleFile(stderr, " #%lu", (unsigned long) c );
4791 (void) FormatLocaleFile(stderr, " \"%s",
4792 CommandOptionToMnemonic(MagickKernelOptions, k->type) );
4793 if ( fabs(k->angle) > MagickEpsilon )
4794 (void) FormatLocaleFile(stderr, "@%lg", k->angle);
4795 (void) FormatLocaleFile(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long)
4796 k->width,(unsigned long) k->height,(long) k->x,(long) k->y);
4797 (void) FormatLocaleFile(stderr,
4798 " with values from %.*lg to %.*lg\n",
4799 GetMagickPrecision(), k->minimum,
4800 GetMagickPrecision(), k->maximum);
4801 (void) FormatLocaleFile(stderr, "Forming a output range from %.*lg to %.*lg",
4802 GetMagickPrecision(), k->negative_range,
4803 GetMagickPrecision(), k->positive_range);
4804 if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
4805 (void) FormatLocaleFile(stderr, " (Zero-Summing)\n");
4806 else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
4807 (void) FormatLocaleFile(stderr, " (Normalized)\n");
4809 (void) FormatLocaleFile(stderr, " (Sum %.*lg)\n",
4810 GetMagickPrecision(), k->positive_range+k->negative_range);
4811 for (i=v=0; v < k->height; v++) {
4812 (void) FormatLocaleFile(stderr, "%2lu:", (unsigned long) v );
4813 for (u=0; u < k->width; u++, i++)
4814 if ( IsNan(k->values[i]) )
4815 (void) FormatLocaleFile(stderr," %*s", GetMagickPrecision()+3, "nan");
4817 (void) FormatLocaleFile(stderr," %*.*lg", GetMagickPrecision()+3,
4818 GetMagickPrecision(), k->values[i]);
4819 (void) FormatLocaleFile(stderr,"\n");
4825 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4829 % U n i t y A d d K e r n a l I n f o %
4833 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4835 % UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
4836 % to the given pre-scaled and normalized Kernel. This in effect adds that
4837 % amount of the original image into the resulting convolution kernel. This
4838 % value is usually provided by the user as a percentage value in the
4839 % 'convolve:scale' setting.
4841 % The resulting effect is to convert the defined kernels into blended
4842 % soft-blurs, unsharp kernels or into sharpening kernels.
4844 % The format of the UnityAdditionKernelInfo method is:
4846 % void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
4848 % A description of each parameter follows:
4850 % o kernel: the Morphology/Convolution kernel
4853 % scaling factor for the unity kernel to be added to
4857 MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
4860 /* do the other kernels in a multi-kernel list first */
4861 if ( kernel->next != (KernelInfo *) NULL)
4862 UnityAddKernelInfo(kernel->next, scale);
4864 /* Add the scaled unity kernel to the existing kernel */
4865 kernel->values[kernel->x+kernel->y*kernel->width] += scale;
4866 CalcKernelMetaData(kernel); /* recalculate the meta-data */
4872 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4876 % Z e r o K e r n e l N a n s %
4880 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4882 % ZeroKernelNans() replaces any special 'nan' value that may be present in
4883 % the kernel with a zero value. This is typically done when the kernel will
4884 % be used in special hardware (GPU) convolution processors, to simply
4887 % The format of the ZeroKernelNans method is:
4889 % void ZeroKernelNans (KernelInfo *kernel)
4891 % A description of each parameter follows:
4893 % o kernel: the Morphology/Convolution kernel
4896 MagickPrivate void ZeroKernelNans(KernelInfo *kernel)
4901 /* do the other kernels in a multi-kernel list first */
4902 if ( kernel->next != (KernelInfo *) NULL)
4903 ZeroKernelNans(kernel->next);
4905 for (i=0; i < (kernel->width*kernel->height); i++)
4906 if ( IsNan(kernel->values[i]) )
4907 kernel->values[i] = 0.0;