blob: 933a54284c56d3bc6bc11c2a25d04ea6a78554dc [file] [log] [blame]
cristy701db312009-11-20 03:14:08 +00001/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% %
6% M M OOO RRRR PPPP H H OOO L OOO GGGG Y Y %
7% MM MM O O R R P P H H O O L O O G Y Y %
8% M M M O O RRRR PPPP HHHHH O O L O O G GGG Y %
9% M M O O R R P H H O O L O O G G Y %
10% M M OOO R R P H H OOO LLLLL OOO GGG Y %
11% %
12% %
13% MagickCore Morphology Methods %
14% %
15% Software Design %
16% Anthony Thyssen %
anthonyc94cdb02010-01-06 08:15:29 +000017% January 2010 %
cristy701db312009-11-20 03:14:08 +000018% %
19% %
cristy16af1cb2009-12-11 21:38:29 +000020% Copyright 1999-2010 ImageMagick Studio LLC, a non-profit organization %
cristy701db312009-11-20 03:14:08 +000021% dedicated to making software imaging solutions freely available. %
22% %
23% You may not use this file except in compliance with the License. You may %
24% obtain a copy of the License at %
25% %
26% http://www.imagemagick.org/script/license.php %
27% %
28% Unless required by applicable law or agreed to in writing, software %
29% distributed under the License is distributed on an "AS IS" BASIS, %
30% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
31% See the License for the specific language governing permissions and %
32% limitations under the License. %
33% %
34%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35%
anthony1b2bc0a2010-05-12 05:25:22 +000036% Morpology is the the application of various kernels, of any size and even
anthony602ab9b2010-01-05 08:06:50 +000037% shape, to a image in various ways (typically binary, but not always).
cristy701db312009-11-20 03:14:08 +000038%
anthony602ab9b2010-01-05 08:06:50 +000039% 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.
42%
43% This module provides not only a general morphology function, and the ability
44% to apply more advanced or iterative morphologies, but also functions for the
45% generation of many different types of kernel arrays from user supplied
46% arguments. Prehaps even the generation of a kernel from a small image.
cristy701db312009-11-20 03:14:08 +000047*/
48
49/*
50 Include declarations.
51*/
52#include "magick/studio.h"
anthony602ab9b2010-01-05 08:06:50 +000053#include "magick/artifact.h"
cristy701db312009-11-20 03:14:08 +000054#include "magick/cache-view.h"
55#include "magick/color-private.h"
56#include "magick/enhance.h"
57#include "magick/exception.h"
58#include "magick/exception-private.h"
anthony602ab9b2010-01-05 08:06:50 +000059#include "magick/gem.h"
cristy701db312009-11-20 03:14:08 +000060#include "magick/hashmap.h"
61#include "magick/image.h"
cristybba804b2010-01-05 15:39:59 +000062#include "magick/image-private.h"
cristy701db312009-11-20 03:14:08 +000063#include "magick/list.h"
anthony29188a82010-01-22 10:12:34 +000064#include "magick/magick.h"
cristy701db312009-11-20 03:14:08 +000065#include "magick/memory_.h"
66#include "magick/monitor-private.h"
67#include "magick/morphology.h"
anthony46a369d2010-05-19 02:41:48 +000068#include "magick/morphology-private.h"
anthony602ab9b2010-01-05 08:06:50 +000069#include "magick/option.h"
cristy701db312009-11-20 03:14:08 +000070#include "magick/pixel-private.h"
71#include "magick/prepress.h"
72#include "magick/quantize.h"
73#include "magick/registry.h"
74#include "magick/semaphore.h"
75#include "magick/splay-tree.h"
76#include "magick/statistic.h"
77#include "magick/string_.h"
anthony602ab9b2010-01-05 08:06:50 +000078#include "magick/string-private.h"
79#include "magick/token.h"
cristya29d45f2010-03-05 21:14:54 +000080
anthonyc3cd15b2010-05-27 06:05:40 +000081
anthony602ab9b2010-01-05 08:06:50 +000082/*
anthonyc3cd15b2010-05-27 06:05:40 +000083** The following test is for special floating point numbers of value NaN (not
84** a number), that may be used within a Kernel Definition. NaN's are defined
85** as part of the IEEE standard for floating point number representation.
86**
87** These are used as a Kernel value to mean that this kernel position is not
88** part of the kernel neighbourhood for convolution or morphology processing,
89** and thus should be ignored. This allows the use of 'shaped' kernels.
90**
91** The special properity that two NaN's are never equal, even if they are from
92** the same variable allow you to test if a value is special NaN value.
93**
94** This macro IsNaN() is thus is only true if the value given is NaN.
cristya29d45f2010-03-05 21:14:54 +000095*/
anthony602ab9b2010-01-05 08:06:50 +000096#define IsNan(a) ((a)!=(a))
97
anthony29188a82010-01-22 10:12:34 +000098/*
cristya29d45f2010-03-05 21:14:54 +000099 Other global definitions used by module.
100*/
anthony29188a82010-01-22 10:12:34 +0000101static inline double MagickMin(const double x,const double y)
102{
103 return( x < y ? x : y);
104}
105static inline double MagickMax(const double x,const double y)
106{
107 return( x > y ? x : y);
108}
109#define Minimize(assign,value) assign=MagickMin(assign,value)
110#define Maximize(assign,value) assign=MagickMax(assign,value)
111
anthonyc4c86e02010-01-27 09:30:32 +0000112/* Currently these are only internal to this module */
113static void
anthony46a369d2010-05-19 02:41:48 +0000114 CalcKernelMetaData(KernelInfo *),
anthonybfb635a2010-06-04 00:18:04 +0000115 ExpandMirrorKernelInfo(KernelInfo *),
116 ExpandRotateKernelInfo(KernelInfo *, const double),
cristyef656912010-03-05 19:54:59 +0000117 RotateKernelInfo(KernelInfo *, double);
anthony602ab9b2010-01-05 08:06:50 +0000118
anthony3dd0f622010-05-13 12:57:32 +0000119
120/* Quick function to find last kernel in a kernel list */
121static inline KernelInfo *LastKernelInfo(KernelInfo *kernel)
122{
123 while (kernel->next != (KernelInfo *) NULL)
124 kernel = kernel->next;
125 return(kernel);
126}
127
128
anthony602ab9b2010-01-05 08:06:50 +0000129/*
130%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
131% %
132% %
133% %
anthony83ba99b2010-01-24 08:48:15 +0000134% A c q u i r e K e r n e l I n f o %
anthony602ab9b2010-01-05 08:06:50 +0000135% %
136% %
137% %
138%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
139%
cristy2be15382010-01-21 02:38:03 +0000140% AcquireKernelInfo() takes the given string (generally supplied by the
anthony602ab9b2010-01-05 08:06:50 +0000141% user) and converts it into a Morphology/Convolution Kernel. This allows
142% users to specify a kernel from a number of pre-defined kernels, or to fully
143% specify their own kernel for a specific Convolution or Morphology
144% Operation.
145%
146% The kernel so generated can be any rectangular array of floating point
147% values (doubles) with the 'control point' or 'pixel being affected'
148% anywhere within that array of values.
149%
anthony83ba99b2010-01-24 08:48:15 +0000150% Previously IM was restricted to a square of odd size using the exact
cristybb503372010-05-27 20:51:26 +0000151% center as origin, this is no ssize_ter the case, and any rectangular kernel
anthony83ba99b2010-01-24 08:48:15 +0000152% with any value being declared the origin. This in turn allows the use of
153% highly asymmetrical kernels.
anthony602ab9b2010-01-05 08:06:50 +0000154%
155% The floating point values in the kernel can also include a special value
anthony83ba99b2010-01-24 08:48:15 +0000156% known as 'nan' or 'not a number' to indicate that this value is not part
157% of the kernel array. This allows you to shaped the kernel within its
158% rectangular area. That is 'nan' values provide a 'mask' for the kernel
159% shape. However at least one non-nan value must be provided for correct
160% working of a kernel.
anthony602ab9b2010-01-05 08:06:50 +0000161%
anthony7a01dcf2010-05-11 12:25:52 +0000162% The returned kernel should be freed using the DestroyKernelInfo() when you
163% are finished with it. Do not free this memory yourself.
anthony602ab9b2010-01-05 08:06:50 +0000164%
165% Input kernel defintion strings can consist of any of three types.
166%
anthonybfb635a2010-06-04 00:18:04 +0000167% "name:args[[@><]"
anthony29188a82010-01-22 10:12:34 +0000168% Select from one of the built in kernels, using the name and
169% geometry arguments supplied. See AcquireKernelBuiltIn()
anthony602ab9b2010-01-05 08:06:50 +0000170%
anthonybfb635a2010-06-04 00:18:04 +0000171% "WxH[+X+Y][@><]:num, num, num ..."
anthony1b2bc0a2010-05-12 05:25:22 +0000172% a kernel of size W by H, with W*H floating point numbers following.
anthony602ab9b2010-01-05 08:06:50 +0000173% the 'center' can be optionally be defined at +X+Y (such that +0+0
anthony29188a82010-01-22 10:12:34 +0000174% is top left corner). If not defined the pixel in the center, for
175% odd sizes, or to the immediate top or left of center for even sizes
176% is automatically selected.
anthony602ab9b2010-01-05 08:06:50 +0000177%
anthony29188a82010-01-22 10:12:34 +0000178% "num, num, num, num, ..."
179% list of floating point numbers defining an 'old style' odd sized
180% square kernel. At least 9 values should be provided for a 3x3
181% square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc.
182% Values can be space or comma separated. This is not recommended.
anthony602ab9b2010-01-05 08:06:50 +0000183%
anthony7a01dcf2010-05-11 12:25:52 +0000184% You can define a 'list of kernels' which can be used by some morphology
185% operators A list is defined as a semi-colon seperated list kernels.
186%
anthonydbc89892010-05-12 07:05:27 +0000187% " kernel ; kernel ; kernel ; "
anthony7a01dcf2010-05-11 12:25:52 +0000188%
anthony1dd091a2010-05-27 06:31:15 +0000189% Any extra ';' characters, at start, end or between kernel defintions are
anthony43c49252010-05-18 10:59:50 +0000190% simply ignored.
191%
anthonybfb635a2010-06-04 00:18:04 +0000192% The special flags will expand a single kernel, into a list of rotated
193% kernels. A '@' flag will expand a 3x3 kernel into a list of 45-degree
194% cyclic rotations, while a '>' will generate a list of 90-degree rotations.
195% The '<' also exands using 90-degree rotates, but giving a 180-degree
196% reflected kernel before the +/- 90-degree rotations, which can be important
197% for Thinning operations.
198%
anthony43c49252010-05-18 10:59:50 +0000199% Note that 'name' kernels will start with an alphabetic character while the
200% new kernel specification has a ':' character in its specification string.
201% If neither is the case, it is assumed an old style of a simple list of
202% numbers generating a odd-sized square kernel has been given.
anthony7a01dcf2010-05-11 12:25:52 +0000203%
anthony602ab9b2010-01-05 08:06:50 +0000204% The format of the AcquireKernal method is:
205%
cristy2be15382010-01-21 02:38:03 +0000206% KernelInfo *AcquireKernelInfo(const char *kernel_string)
anthony602ab9b2010-01-05 08:06:50 +0000207%
208% A description of each parameter follows:
209%
210% o kernel_string: the Morphology/Convolution kernel wanted.
211%
212*/
213
anthonyc84dce52010-05-07 05:42:23 +0000214/* This was separated so that it could be used as a separate
anthony5ef8e942010-05-11 06:51:12 +0000215** array input handling function, such as for -color-matrix
anthonyc84dce52010-05-07 05:42:23 +0000216*/
anthony5ef8e942010-05-11 06:51:12 +0000217static KernelInfo *ParseKernelArray(const char *kernel_string)
anthony602ab9b2010-01-05 08:06:50 +0000218{
cristy2be15382010-01-21 02:38:03 +0000219 KernelInfo
anthony602ab9b2010-01-05 08:06:50 +0000220 *kernel;
221
222 char
223 token[MaxTextExtent];
224
anthony602ab9b2010-01-05 08:06:50 +0000225 const char
anthony5ef8e942010-05-11 06:51:12 +0000226 *p,
227 *end;
anthony602ab9b2010-01-05 08:06:50 +0000228
cristybb503372010-05-27 20:51:26 +0000229 register ssize_t
anthonyc84dce52010-05-07 05:42:23 +0000230 i;
anthony602ab9b2010-01-05 08:06:50 +0000231
anthony29188a82010-01-22 10:12:34 +0000232 double
233 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
234
anthony43c49252010-05-18 10:59:50 +0000235 MagickStatusType
236 flags;
237
238 GeometryInfo
239 args;
240
cristy2be15382010-01-21 02:38:03 +0000241 kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
242 if (kernel == (KernelInfo *)NULL)
anthony602ab9b2010-01-05 08:06:50 +0000243 return(kernel);
244 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
anthony43c49252010-05-18 10:59:50 +0000245 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
anthony7a01dcf2010-05-11 12:25:52 +0000246 kernel->negative_range = kernel->positive_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +0000247 kernel->type = UserDefinedKernel;
anthony7a01dcf2010-05-11 12:25:52 +0000248 kernel->next = (KernelInfo *) NULL;
cristyd43a46b2010-01-21 02:13:41 +0000249 kernel->signature = MagickSignature;
anthony602ab9b2010-01-05 08:06:50 +0000250
anthony5ef8e942010-05-11 06:51:12 +0000251 /* find end of this specific kernel definition string */
252 end = strchr(kernel_string, ';');
253 if ( end == (char *) NULL )
254 end = strchr(kernel_string, '\0');
255
anthony43c49252010-05-18 10:59:50 +0000256 /* clear flags - for Expanding kernal lists thorugh rotations */
257 flags = NoValue;
258
anthony602ab9b2010-01-05 08:06:50 +0000259 /* Has a ':' in argument - New user kernel specification */
260 p = strchr(kernel_string, ':');
anthony5ef8e942010-05-11 06:51:12 +0000261 if ( p != (char *) NULL && p < end)
anthony602ab9b2010-01-05 08:06:50 +0000262 {
anthony602ab9b2010-01-05 08:06:50 +0000263 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
cristy150989e2010-02-01 14:59:39 +0000264 memcpy(token, kernel_string, (size_t) (p-kernel_string));
anthony602ab9b2010-01-05 08:06:50 +0000265 token[p-kernel_string] = '\0';
anthonyc84dce52010-05-07 05:42:23 +0000266 SetGeometryInfo(&args);
anthony602ab9b2010-01-05 08:06:50 +0000267 flags = ParseGeometry(token, &args);
anthony602ab9b2010-01-05 08:06:50 +0000268
anthony29188a82010-01-22 10:12:34 +0000269 /* Size handling and checks of geometry settings */
anthony602ab9b2010-01-05 08:06:50 +0000270 if ( (flags & WidthValue) == 0 ) /* if no width then */
271 args.rho = args.sigma; /* then width = height */
272 if ( args.rho < 1.0 ) /* if width too small */
273 args.rho = 1.0; /* then width = 1 */
274 if ( args.sigma < 1.0 ) /* if height too small */
275 args.sigma = args.rho; /* then height = width */
cristybb503372010-05-27 20:51:26 +0000276 kernel->width = (size_t)args.rho;
277 kernel->height = (size_t)args.sigma;
anthony602ab9b2010-01-05 08:06:50 +0000278
279 /* Offset Handling and Checks */
280 if ( args.xi < 0.0 || args.psi < 0.0 )
anthony83ba99b2010-01-24 08:48:15 +0000281 return(DestroyKernelInfo(kernel));
cristybb503372010-05-27 20:51:26 +0000282 kernel->x = ((flags & XValue)!=0) ? (ssize_t)args.xi
283 : (ssize_t) (kernel->width-1)/2;
284 kernel->y = ((flags & YValue)!=0) ? (ssize_t)args.psi
285 : (ssize_t) (kernel->height-1)/2;
286 if ( kernel->x >= (ssize_t) kernel->width ||
287 kernel->y >= (ssize_t) kernel->height )
anthony83ba99b2010-01-24 08:48:15 +0000288 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000289
290 p++; /* advance beyond the ':' */
291 }
292 else
anthonyc84dce52010-05-07 05:42:23 +0000293 { /* ELSE - Old old specification, forming odd-square kernel */
anthony602ab9b2010-01-05 08:06:50 +0000294 /* count up number of values given */
295 p=(const char *) kernel_string;
cristya699b172010-01-06 16:48:49 +0000296 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
anthony29188a82010-01-22 10:12:34 +0000297 p++; /* ignore "'" chars for convolve filter usage - Cristy */
anthony5ef8e942010-05-11 06:51:12 +0000298 for (i=0; p < end; i++)
anthony602ab9b2010-01-05 08:06:50 +0000299 {
300 GetMagickToken(p,&p,token);
301 if (*token == ',')
302 GetMagickToken(p,&p,token);
303 }
304 /* set the size of the kernel - old sized square */
cristybb503372010-05-27 20:51:26 +0000305 kernel->width = kernel->height= (size_t) sqrt((double) i+1.0);
306 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +0000307 p=(const char *) kernel_string;
anthony29188a82010-01-22 10:12:34 +0000308 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
309 p++; /* ignore "'" chars for convolve filter usage - Cristy */
anthony602ab9b2010-01-05 08:06:50 +0000310 }
311
312 /* Read in the kernel values from rest of input string argument */
313 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
314 kernel->height*sizeof(double));
315 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +0000316 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000317
cristyc99304f2010-02-01 15:26:27 +0000318 kernel->minimum = +MagickHuge;
319 kernel->maximum = -MagickHuge;
320 kernel->negative_range = kernel->positive_range = 0.0;
anthonyc84dce52010-05-07 05:42:23 +0000321
cristybb503372010-05-27 20:51:26 +0000322 for (i=0; (i < (ssize_t) (kernel->width*kernel->height)) && (p < end); i++)
anthony602ab9b2010-01-05 08:06:50 +0000323 {
324 GetMagickToken(p,&p,token);
325 if (*token == ',')
326 GetMagickToken(p,&p,token);
anthony29188a82010-01-22 10:12:34 +0000327 if ( LocaleCompare("nan",token) == 0
anthonyc84dce52010-05-07 05:42:23 +0000328 || LocaleCompare("-",token) == 0 ) {
anthony29188a82010-01-22 10:12:34 +0000329 kernel->values[i] = nan; /* do not include this value in kernel */
330 }
331 else {
332 kernel->values[i] = StringToDouble(token);
333 ( kernel->values[i] < 0)
cristyc99304f2010-02-01 15:26:27 +0000334 ? ( kernel->negative_range += kernel->values[i] )
335 : ( kernel->positive_range += kernel->values[i] );
336 Minimize(kernel->minimum, kernel->values[i]);
337 Maximize(kernel->maximum, kernel->values[i]);
anthony29188a82010-01-22 10:12:34 +0000338 }
anthony602ab9b2010-01-05 08:06:50 +0000339 }
anthony29188a82010-01-22 10:12:34 +0000340
anthony5ef8e942010-05-11 06:51:12 +0000341 /* sanity check -- no more values in kernel definition */
342 GetMagickToken(p,&p,token);
343 if ( *token != '\0' && *token != ';' && *token != '\'' )
344 return(DestroyKernelInfo(kernel));
345
anthonyc84dce52010-05-07 05:42:23 +0000346#if 0
347 /* this was the old method of handling a incomplete kernel */
cristybb503372010-05-27 20:51:26 +0000348 if ( i < (ssize_t) (kernel->width*kernel->height) ) {
cristyc99304f2010-02-01 15:26:27 +0000349 Minimize(kernel->minimum, kernel->values[i]);
350 Maximize(kernel->maximum, kernel->values[i]);
cristybb503372010-05-27 20:51:26 +0000351 for ( ; i < (ssize_t) (kernel->width*kernel->height); i++)
anthony29188a82010-01-22 10:12:34 +0000352 kernel->values[i]=0.0;
353 }
anthonyc84dce52010-05-07 05:42:23 +0000354#else
355 /* Number of values for kernel was not enough - Report Error */
cristybb503372010-05-27 20:51:26 +0000356 if ( i < (ssize_t) (kernel->width*kernel->height) )
anthonyc84dce52010-05-07 05:42:23 +0000357 return(DestroyKernelInfo(kernel));
358#endif
359
360 /* check that we recieved at least one real (non-nan) value! */
361 if ( kernel->minimum == MagickHuge )
362 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000363
anthony43c49252010-05-18 10:59:50 +0000364 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */
anthonybfb635a2010-06-04 00:18:04 +0000365 ExpandRotateKernelInfo(kernel, 45.0); /* cyclic rotate 3x3 kernels */
366 else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
367 ExpandRotateKernelInfo(kernel, 90.0); /* 90 degree rotate of kernel */
368 else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
369 ExpandMirrorKernelInfo(kernel); /* 90 degree mirror rotate */
anthony43c49252010-05-18 10:59:50 +0000370
anthony602ab9b2010-01-05 08:06:50 +0000371 return(kernel);
372}
anthonyc84dce52010-05-07 05:42:23 +0000373
anthony43c49252010-05-18 10:59:50 +0000374static KernelInfo *ParseKernelName(const char *kernel_string)
anthonyc84dce52010-05-07 05:42:23 +0000375{
anthonyf0176c32010-05-23 23:08:57 +0000376 KernelInfo
377 *kernel;
378
anthonyc84dce52010-05-07 05:42:23 +0000379 char
380 token[MaxTextExtent];
381
cristybb503372010-05-27 20:51:26 +0000382 ssize_t
anthony5ef8e942010-05-11 06:51:12 +0000383 type;
384
anthonyc84dce52010-05-07 05:42:23 +0000385 const char
anthony7a01dcf2010-05-11 12:25:52 +0000386 *p,
387 *end;
anthonyc84dce52010-05-07 05:42:23 +0000388
389 MagickStatusType
390 flags;
391
392 GeometryInfo
393 args;
394
anthonyc84dce52010-05-07 05:42:23 +0000395 /* Parse special 'named' kernel */
anthony5ef8e942010-05-11 06:51:12 +0000396 GetMagickToken(kernel_string,&p,token);
anthonyc84dce52010-05-07 05:42:23 +0000397 type=ParseMagickOption(MagickKernelOptions,MagickFalse,token);
398 if ( type < 0 || type == UserDefinedKernel )
anthony5ef8e942010-05-11 06:51:12 +0000399 return((KernelInfo *)NULL); /* not a valid named kernel */
anthonyc84dce52010-05-07 05:42:23 +0000400
401 while (((isspace((int) ((unsigned char) *p)) != 0) ||
anthony5ef8e942010-05-11 06:51:12 +0000402 (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
anthonyc84dce52010-05-07 05:42:23 +0000403 p++;
anthony7a01dcf2010-05-11 12:25:52 +0000404
405 end = strchr(p, ';'); /* end of this kernel defintion */
406 if ( end == (char *) NULL )
407 end = strchr(p, '\0');
408
409 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
410 memcpy(token, p, (size_t) (end-p));
411 token[end-p] = '\0';
anthonyc84dce52010-05-07 05:42:23 +0000412 SetGeometryInfo(&args);
anthony7a01dcf2010-05-11 12:25:52 +0000413 flags = ParseGeometry(token, &args);
anthonyc84dce52010-05-07 05:42:23 +0000414
anthony3c10fc82010-05-13 02:40:51 +0000415#if 0
416 /* For Debugging Geometry Input */
anthony46a369d2010-05-19 02:41:48 +0000417 fprintf(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
anthony3c10fc82010-05-13 02:40:51 +0000418 flags, args.rho, args.sigma, args.xi, args.psi );
419#endif
420
anthonyc84dce52010-05-07 05:42:23 +0000421 /* special handling of missing values in input string */
422 switch( type ) {
anthony5ef8e942010-05-11 06:51:12 +0000423 case RectangleKernel:
424 if ( (flags & WidthValue) == 0 ) /* if no width then */
425 args.rho = args.sigma; /* then width = height */
426 if ( args.rho < 1.0 ) /* if width too small */
427 args.rho = 3; /* then width = 3 */
428 if ( args.sigma < 1.0 ) /* if height too small */
429 args.sigma = args.rho; /* then height = width */
430 if ( (flags & XValue) == 0 ) /* center offset if not defined */
cristybb503372010-05-27 20:51:26 +0000431 args.xi = (double)(((ssize_t)args.rho-1)/2);
anthony5ef8e942010-05-11 06:51:12 +0000432 if ( (flags & YValue) == 0 )
cristybb503372010-05-27 20:51:26 +0000433 args.psi = (double)(((ssize_t)args.sigma-1)/2);
anthony5ef8e942010-05-11 06:51:12 +0000434 break;
435 case SquareKernel:
436 case DiamondKernel:
437 case DiskKernel:
438 case PlusKernel:
anthony3dd0f622010-05-13 12:57:32 +0000439 case CrossKernel:
anthony5ef8e942010-05-11 06:51:12 +0000440 /* If no scale given (a 0 scale is valid! - set it to 1.0 */
441 if ( (flags & HeightValue) == 0 )
442 args.sigma = 1.0;
443 break;
anthonyc1061722010-05-14 06:23:49 +0000444 case RingKernel:
445 if ( (flags & XValue) == 0 )
446 args.xi = 1.0;
447 break;
anthony5ef8e942010-05-11 06:51:12 +0000448 case ChebyshevKernel:
anthonybee715c2010-06-04 01:25:57 +0000449 case ManhattanKernel:
anthony5ef8e942010-05-11 06:51:12 +0000450 case EuclideanKernel:
anthony43c49252010-05-18 10:59:50 +0000451 if ( (flags & HeightValue) == 0 ) /* no distance scale */
452 args.sigma = 100.0; /* default distance scaling */
453 else if ( (flags & AspectValue ) != 0 ) /* '!' flag */
454 args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */
455 else if ( (flags & PercentValue ) != 0 ) /* '%' flag */
456 args.sigma *= QuantumRange/100.0; /* percentage of color range */
anthony5ef8e942010-05-11 06:51:12 +0000457 break;
458 default:
459 break;
anthonyc84dce52010-05-07 05:42:23 +0000460 }
461
anthonyf0176c32010-05-23 23:08:57 +0000462 kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args);
463
464 /* global expand to rotated kernel list - only for single kernels */
465 if ( kernel->next == (KernelInfo *) NULL ) {
466 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */
anthonybfb635a2010-06-04 00:18:04 +0000467 ExpandRotateKernelInfo(kernel, 45.0);
468 else if ( (flags & GreaterValue) != 0 ) /* '>' symbol in kernel args */
469 ExpandRotateKernelInfo(kernel, 90.0);
470 else if ( (flags & LessValue) != 0 ) /* '<' symbol in kernel args */
471 ExpandMirrorKernelInfo(kernel);
anthonyf0176c32010-05-23 23:08:57 +0000472 }
473
474 return(kernel);
anthonyc84dce52010-05-07 05:42:23 +0000475}
476
anthony5ef8e942010-05-11 06:51:12 +0000477MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string)
478{
anthony7a01dcf2010-05-11 12:25:52 +0000479
480 KernelInfo
anthonydbc89892010-05-12 07:05:27 +0000481 *kernel,
anthony43c49252010-05-18 10:59:50 +0000482 *new_kernel;
anthony7a01dcf2010-05-11 12:25:52 +0000483
anthony5ef8e942010-05-11 06:51:12 +0000484 char
485 token[MaxTextExtent];
486
anthony7a01dcf2010-05-11 12:25:52 +0000487 const char
anthonydbc89892010-05-12 07:05:27 +0000488 *p;
anthony7a01dcf2010-05-11 12:25:52 +0000489
cristybb503372010-05-27 20:51:26 +0000490 size_t
anthonye108a3f2010-05-12 07:24:03 +0000491 kernel_number;
492
anthonydbc89892010-05-12 07:05:27 +0000493 p = kernel_string;
anthony43c49252010-05-18 10:59:50 +0000494 kernel = NULL;
anthonye108a3f2010-05-12 07:24:03 +0000495 kernel_number = 0;
anthony5ef8e942010-05-11 06:51:12 +0000496
anthonydbc89892010-05-12 07:05:27 +0000497 while ( GetMagickToken(p,NULL,token), *token != '\0' ) {
anthony7a01dcf2010-05-11 12:25:52 +0000498
anthony43c49252010-05-18 10:59:50 +0000499 /* ignore extra or multiple ';' kernel seperators */
anthonydbc89892010-05-12 07:05:27 +0000500 if ( *token != ';' ) {
anthony7a01dcf2010-05-11 12:25:52 +0000501
anthonydbc89892010-05-12 07:05:27 +0000502 /* tokens starting with alpha is a Named kernel */
anthony43c49252010-05-18 10:59:50 +0000503 if (isalpha((int) *token) != 0)
504 new_kernel = ParseKernelName(p);
anthonydbc89892010-05-12 07:05:27 +0000505 else /* otherwise a user defined kernel array */
anthony43c49252010-05-18 10:59:50 +0000506 new_kernel = ParseKernelArray(p);
anthony7a01dcf2010-05-11 12:25:52 +0000507
anthonye108a3f2010-05-12 07:24:03 +0000508 /* Error handling -- this is not proper error handling! */
509 if ( new_kernel == (KernelInfo *) NULL ) {
cristye8c25f92010-06-03 00:53:06 +0000510 fprintf(stderr, "Failed to parse kernel number #%.20g\n",(double)
cristyf2faecf2010-05-28 19:19:36 +0000511 kernel_number);
anthonye108a3f2010-05-12 07:24:03 +0000512 if ( kernel != (KernelInfo *) NULL )
513 kernel=DestroyKernelInfo(kernel);
514 return((KernelInfo *) NULL);
anthonydbc89892010-05-12 07:05:27 +0000515 }
anthonye108a3f2010-05-12 07:24:03 +0000516
517 /* initialise or append the kernel list */
anthony3dd0f622010-05-13 12:57:32 +0000518 if ( kernel == (KernelInfo *) NULL )
519 kernel = new_kernel;
520 else
anthony43c49252010-05-18 10:59:50 +0000521 LastKernelInfo(kernel)->next = new_kernel;
anthonydbc89892010-05-12 07:05:27 +0000522 }
523
524 /* look for the next kernel in list */
525 p = strchr(p, ';');
526 if ( p == (char *) NULL )
527 break;
528 p++;
529
530 }
anthony7a01dcf2010-05-11 12:25:52 +0000531 return(kernel);
anthony5ef8e942010-05-11 06:51:12 +0000532}
533
anthony602ab9b2010-01-05 08:06:50 +0000534
535/*
536%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
537% %
538% %
539% %
540% A c q u i r e K e r n e l B u i l t I n %
541% %
542% %
543% %
544%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
545%
546% AcquireKernelBuiltIn() returned one of the 'named' built-in types of
547% kernels used for special purposes such as gaussian blurring, skeleton
548% pruning, and edge distance determination.
549%
550% They take a KernelType, and a set of geometry style arguments, which were
551% typically decoded from a user supplied string, or from a more complex
552% Morphology Method that was requested.
553%
554% The format of the AcquireKernalBuiltIn method is:
555%
cristy2be15382010-01-21 02:38:03 +0000556% KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
anthony602ab9b2010-01-05 08:06:50 +0000557% const GeometryInfo args)
558%
559% A description of each parameter follows:
560%
561% o type: the pre-defined type of kernel wanted
562%
563% o args: arguments defining or modifying the kernel
564%
565% Convolution Kernels
566%
anthony46a369d2010-05-19 02:41:48 +0000567% Unity
568% the No-Op kernel, also requivelent to Gaussian of sigma zero.
569% Basically a 3x3 kernel of a 1 surrounded by zeros.
570%
anthony3c10fc82010-05-13 02:40:51 +0000571% Gaussian:{radius},{sigma}
572% Generate a two-dimentional gaussian kernel, as used by -gaussian.
anthonyc1061722010-05-14 06:23:49 +0000573% The sigma for the curve is required. The resulting kernel is
574% normalized,
575%
576% If 'sigma' is zero, you get a single pixel on a field of zeros.
anthony602ab9b2010-01-05 08:06:50 +0000577%
578% NOTE: that the 'radius' is optional, but if provided can limit (clip)
579% the final size of the resulting kernel to a square 2*radius+1 in size.
580% The radius should be at least 2 times that of the sigma value, or
581% sever clipping and aliasing may result. If not given or set to 0 the
582% radius will be determined so as to produce the best minimal error
583% result, which is usally much larger than is normally needed.
584%
anthony501c2f92010-06-02 10:55:14 +0000585% LoG:{radius},{sigma}
586% "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
587% The supposed ideal edge detection, zero-summing kernel.
588%
589% An alturnative to this kernel is to use a "DoG" with a sigma ratio of
590% approx 1.6 (according to wikipedia).
591%
592% DoG:{radius},{sigma1},{sigma2}
anthonyc1061722010-05-14 06:23:49 +0000593% "Difference of Gaussians" Kernel.
594% As "Gaussian" but with a gaussian produced by 'sigma2' subtracted
595% from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1.
596% The result is a zero-summing kernel.
anthony602ab9b2010-01-05 08:06:50 +0000597%
anthonyc1061722010-05-14 06:23:49 +0000598% Blur:{radius},{sigma}[,{angle}]
599% Generates a 1 dimensional or linear gaussian blur, at the angle given
600% (current restricted to orthogonal angles). If a 'radius' is given the
601% kernel is clipped to a width of 2*radius+1. Kernel can be rotated
602% by a 90 degree angle.
603%
604% If 'sigma' is zero, you get a single pixel on a field of zeros.
605%
606% Note that two convolutions with two "Blur" kernels perpendicular to
607% each other, is equivelent to a far larger "Gaussian" kernel with the
608% same sigma value, However it is much faster to apply. This is how the
609% "-blur" operator actually works.
610%
anthony3c10fc82010-05-13 02:40:51 +0000611% Comet:{width},{sigma},{angle}
612% Blur in one direction only, much like how a bright object leaves
anthony602ab9b2010-01-05 08:06:50 +0000613% a comet like trail. The Kernel is actually half a gaussian curve,
anthony3c10fc82010-05-13 02:40:51 +0000614% Adding two such blurs in opposite directions produces a Blur Kernel.
615% Angle can be rotated in multiples of 90 degrees.
anthony602ab9b2010-01-05 08:06:50 +0000616%
anthony3c10fc82010-05-13 02:40:51 +0000617% Note that the first argument is the width of the kernel and not the
anthony602ab9b2010-01-05 08:06:50 +0000618% radius of the kernel.
619%
620% # Still to be implemented...
621% #
anthony4fd27e22010-02-07 08:17:18 +0000622% # Filter2D
623% # Filter1D
624% # Set kernel values using a resize filter, and given scale (sigma)
625% # Cylindrical or Linear. Is this posible with an image?
626% #
anthony602ab9b2010-01-05 08:06:50 +0000627%
anthony3c10fc82010-05-13 02:40:51 +0000628% Named Constant Convolution Kernels
629%
anthonyc1061722010-05-14 06:23:49 +0000630% All these are unscaled, zero-summing kernels by default. As such for
631% non-HDRI version of ImageMagick some form of normalization, user scaling,
632% and biasing the results is recommended, to prevent the resulting image
633% being 'clipped'.
634%
635% The 3x3 kernels (most of these) can be circularly rotated in multiples of
636% 45 degrees to generate the 8 angled varients of each of the kernels.
anthony3c10fc82010-05-13 02:40:51 +0000637%
638% Laplacian:{type}
anthony43c49252010-05-18 10:59:50 +0000639% Discrete Lapacian Kernels, (without normalization)
anthonyc1061722010-05-14 06:23:49 +0000640% Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood)
641% Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood)
anthony9eb4f742010-05-18 02:45:54 +0000642% Type 2 : 3x3 with center:4 edge:1 corner:-2
643% Type 3 : 3x3 with center:4 edge:-2 corner:1
644% Type 5 : 5x5 laplacian
645% Type 7 : 7x7 laplacian
anthony501c2f92010-06-02 10:55:14 +0000646% Type 15 : 5x5 LoG (sigma approx 1.4)
647% Type 19 : 9x9 LoG (sigma approx 1.4)
anthonyc1061722010-05-14 06:23:49 +0000648%
649% Sobel:{angle}
anthony46a369d2010-05-19 02:41:48 +0000650% Sobel 'Edge' convolution kernel (3x3)
anthonyc1061722010-05-14 06:23:49 +0000651% -1, 0, 1
652% -2, 0,-2
653% -1, 0, 1
anthonye2a60ce2010-05-19 12:30:40 +0000654%
anthonyc1061722010-05-14 06:23:49 +0000655% Roberts:{angle}
anthony46a369d2010-05-19 02:41:48 +0000656% Roberts convolution kernel (3x3)
anthonyc1061722010-05-14 06:23:49 +0000657% 0, 0, 0
658% -1, 1, 0
659% 0, 0, 0
anthonyc1061722010-05-14 06:23:49 +0000660% Prewitt:{angle}
661% Prewitt Edge convolution kernel (3x3)
662% -1, 0, 1
663% -1, 0, 1
664% -1, 0, 1
anthony9eb4f742010-05-18 02:45:54 +0000665% Compass:{angle}
666% Prewitt's "Compass" convolution kernel (3x3)
667% -1, 1, 1
668% -1,-2, 1
669% -1, 1, 1
670% Kirsch:{angle}
671% Kirsch's "Compass" convolution kernel (3x3)
672% -3,-3, 5
673% -3, 0, 5
674% -3,-3, 5
anthony3c10fc82010-05-13 02:40:51 +0000675%
anthonye2a60ce2010-05-19 12:30:40 +0000676% FreiChen:{type},{angle}
anthony1d5e6702010-05-31 10:19:12 +0000677% Frei-Chen Edge Detector is based on a kernel that is similar to
678% the Sobel Kernel, but is designed to be isotropic. That is it takes
679% into account the distance of the diagonal in the kernel.
anthonyc3cd15b2010-05-27 06:05:40 +0000680%
anthony501c2f92010-06-02 10:55:14 +0000681% Type 0: | 1, 0, -1 |
682% | sqrt(2), 0, -sqrt(2) |
683% | 1, 0, -1 |
anthonyc3cd15b2010-05-27 06:05:40 +0000684%
anthony1d5e6702010-05-31 10:19:12 +0000685% However this kernel is als at the heart of the FreiChen Edge Detection
686% Process which uses a set of 9 specially weighted kernel. These 9
687% kernels not be normalized, but directly applied to the image. The
688% results is then added together, to produce the intensity of an edge in
689% a specific direction. The square root of the pixel value can then be
690% taken as the cosine of the edge, and at least 2 such runs at 90 degrees
691% from each other, both the direction and the strength of the edge can be
692% determined.
anthonyc3cd15b2010-05-27 06:05:40 +0000693%
anthony501c2f92010-06-02 10:55:14 +0000694% Type 1: | 1, 0, -1 |
695% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
696% | 1, 0, -1 |
anthonye2a60ce2010-05-19 12:30:40 +0000697%
anthony501c2f92010-06-02 10:55:14 +0000698% Type 2: | 1, sqrt(2), 1 |
699% | 0, 0, 0 | / 2*sqrt(2)
700% | 1, sqrt(2), 1 |
anthonye2a60ce2010-05-19 12:30:40 +0000701%
anthony501c2f92010-06-02 10:55:14 +0000702% Type 3: | sqrt(2), -1, 0 |
703% | -1, 0, 1 | / 2*sqrt(2)
704% | 0, 1, -sqrt(2) |
anthonye2a60ce2010-05-19 12:30:40 +0000705%
anthony1d5e6702010-05-31 10:19:12 +0000706% Type 4: | 0, 1, -sqrt(2) |
anthonye2a60ce2010-05-19 12:30:40 +0000707% | -1, 0, 1 | / 2*sqrt(2)
anthony1d5e6702010-05-31 10:19:12 +0000708% | sqrt(2), -1, 0 |
anthonye2a60ce2010-05-19 12:30:40 +0000709%
anthony501c2f92010-06-02 10:55:14 +0000710% Type 5: | 0, -1, 0 |
711% | 1, 0, 1 | / 2
712% | 0, -1, 0 |
anthonye2a60ce2010-05-19 12:30:40 +0000713%
anthony1d5e6702010-05-31 10:19:12 +0000714% Type 6: | 1, 0, -1 |
anthonye2a60ce2010-05-19 12:30:40 +0000715% | 0, 0, 0 | / 2
anthony1d5e6702010-05-31 10:19:12 +0000716% | -1, 0, 1 |
anthonye2a60ce2010-05-19 12:30:40 +0000717%
anthony501c2f92010-06-02 10:55:14 +0000718% Type 7: | 1, -2, 1 |
719% | -2, 4, -2 | / 6
720% | -1, -2, 1 |
721%
722% Type 8: | -2, 1, -2 |
anthonyf4e00312010-05-20 12:06:35 +0000723% | 1, 4, 1 | / 6
724% | -2, 1, -2 |
anthonye2a60ce2010-05-19 12:30:40 +0000725%
anthonyf4e00312010-05-20 12:06:35 +0000726% Type 9: | 1, 1, 1 |
727% | 1, 1, 1 | / 3
728% | 1, 1, 1 |
anthonye2a60ce2010-05-19 12:30:40 +0000729%
730% The first 4 are for edge detection, the next 4 are for line detection
731% and the last is to add a average component to the results.
732%
anthonyc3cd15b2010-05-27 06:05:40 +0000733% Using a special type of '-1' will return all 9 pre-weighted kernels
734% as a multi-kernel list, so that you can use them directly (without
735% normalization) with the special "-set option:morphology:compose Plus"
736% setting to apply the full FreiChen Edge Detection Technique.
737%
anthony1dd091a2010-05-27 06:31:15 +0000738% If 'type' is large it will be taken to be an actual rotation angle for
739% the default FreiChen (type 0) kernel. As such FreiChen:45 will look
740% like a Sobel:45 but with 'sqrt(2)' instead of '2' values.
741%
anthony501c2f92010-06-02 10:55:14 +0000742% WARNING: The above was layed out as per
743% http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf
744% But rotated 90 degrees so direction is from left rather than the top.
745% I have yet to find any secondary confirmation of the above. The only
746% other source found was actual source code at
747% http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf
748% Neigher paper defineds the kernels in a way that looks locical or
749% correct when taken as a whole.
anthonye2a60ce2010-05-19 12:30:40 +0000750%
anthony602ab9b2010-01-05 08:06:50 +0000751% Boolean Kernels
752%
anthony3c10fc82010-05-13 02:40:51 +0000753% Diamond:[{radius}[,{scale}]]
anthony1b2bc0a2010-05-12 05:25:22 +0000754% Generate a diamond shaped kernel with given radius to the points.
anthony602ab9b2010-01-05 08:06:50 +0000755% Kernel size will again be radius*2+1 square and defaults to radius 1,
756% generating a 3x3 kernel that is slightly larger than a square.
757%
anthony3c10fc82010-05-13 02:40:51 +0000758% Square:[{radius}[,{scale}]]
anthony602ab9b2010-01-05 08:06:50 +0000759% Generate a square shaped kernel of size radius*2+1, and defaulting
760% to a 3x3 (radius 1).
761%
anthonyc1061722010-05-14 06:23:49 +0000762% Note that using a larger radius for the "Square" or the "Diamond" is
763% also equivelent to iterating the basic morphological method that many
764% times. However iterating with the smaller radius is actually faster
765% than using a larger kernel radius.
766%
767% Rectangle:{geometry}
768% Simply generate a rectangle of 1's with the size given. You can also
769% specify the location of the 'control point', otherwise the closest
770% pixel to the center of the rectangle is selected.
771%
772% Properly centered and odd sized rectangles work the best.
anthony602ab9b2010-01-05 08:06:50 +0000773%
anthony3c10fc82010-05-13 02:40:51 +0000774% Disk:[{radius}[,{scale}]]
anthony602ab9b2010-01-05 08:06:50 +0000775% Generate a binary disk of the radius given, radius may be a float.
776% Kernel size will be ceil(radius)*2+1 square.
777% NOTE: Here are some disk shapes of specific interest
anthonyc1061722010-05-14 06:23:49 +0000778% "Disk:1" => "diamond" or "cross:1"
779% "Disk:1.5" => "square"
780% "Disk:2" => "diamond:2"
781% "Disk:2.5" => a general disk shape of radius 2
782% "Disk:2.9" => "square:2"
783% "Disk:3.5" => default - octagonal/disk shape of radius 3
784% "Disk:4.2" => roughly octagonal shape of radius 4
785% "Disk:4.3" => a general disk shape of radius 4
anthony602ab9b2010-01-05 08:06:50 +0000786% After this all the kernel shape becomes more and more circular.
787%
788% Because a "disk" is more circular when using a larger radius, using a
789% larger radius is preferred over iterating the morphological operation.
790%
anthonyc1061722010-05-14 06:23:49 +0000791% Symbol Dilation Kernels
792%
793% These kernel is not a good general morphological kernel, but is used
794% more for highlighting and marking any single pixels in an image using,
795% a "Dilate" method as appropriate.
796%
797% For the same reasons iterating these kernels does not produce the
798% same result as using a larger radius for the symbol.
799%
anthony3c10fc82010-05-13 02:40:51 +0000800% Plus:[{radius}[,{scale}]]
anthony3dd0f622010-05-13 12:57:32 +0000801% Cross:[{radius}[,{scale}]]
anthonyc1061722010-05-14 06:23:49 +0000802% Generate a kernel in the shape of a 'plus' or a 'cross' with
803% a each arm the length of the given radius (default 2).
anthony3dd0f622010-05-13 12:57:32 +0000804%
805% NOTE: "plus:1" is equivelent to a "Diamond" kernel.
anthony602ab9b2010-01-05 08:06:50 +0000806%
anthonyc1061722010-05-14 06:23:49 +0000807% Ring:{radius1},{radius2}[,{scale}]
808% A ring of the values given that falls between the two radii.
809% Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
810% This is the 'edge' pixels of the default "Disk" kernel,
811% More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
anthony602ab9b2010-01-05 08:06:50 +0000812%
anthony3dd0f622010-05-13 12:57:32 +0000813% Hit and Miss Kernels
814%
815% Peak:radius1,radius2
anthonyc1061722010-05-14 06:23:49 +0000816% Find any peak larger than the pixels the fall between the two radii.
817% The default ring of pixels is as per "Ring".
anthony43c49252010-05-18 10:59:50 +0000818% Edges
anthony1d45eb92010-05-25 11:13:23 +0000819% Find edges of a binary shape
anthony3dd0f622010-05-13 12:57:32 +0000820% Corners
821% Find corners of a binary shape
anthony47f5d062010-05-23 07:47:50 +0000822% Ridges
anthony1d45eb92010-05-25 11:13:23 +0000823% Find single pixel ridges or thin lines
824% Ridges2
825% Find 2 pixel thick ridges or lines
anthonya648a302010-05-27 02:14:36 +0000826% Ridges3
827% Find 2 pixel thick diagonal ridges (experimental)
anthony3dd0f622010-05-13 12:57:32 +0000828% LineEnds
829% Find end points of lines (for pruning a skeletion)
830% LineJunctions
anthony43c49252010-05-18 10:59:50 +0000831% Find three line junctions (within a skeletion)
anthony3dd0f622010-05-13 12:57:32 +0000832% ConvexHull
833% Octagonal thicken kernel, to generate convex hulls of 45 degrees
834% Skeleton
835% Thinning kernel, which leaves behind a skeletion of a shape
anthony602ab9b2010-01-05 08:06:50 +0000836%
837% Distance Measuring Kernels
838%
anthonyc1061722010-05-14 06:23:49 +0000839% Different types of distance measuring methods, which are used with the
840% a 'Distance' morphology method for generating a gradient based on
841% distance from an edge of a binary shape, though there is a technique
842% for handling a anti-aliased shape.
843%
844% See the 'Distance' Morphological Method, for information of how it is
845% applied.
846%
anthony3dd0f622010-05-13 12:57:32 +0000847% Chebyshev:[{radius}][x{scale}[%!]]
anthonyc94cdb02010-01-06 08:15:29 +0000848% Chebyshev Distance (also known as Tchebychev Distance) is a value of
849% one to any neighbour, orthogonal or diagonal. One why of thinking of
850% it is the number of squares a 'King' or 'Queen' in chess needs to
851% traverse reach any other position on a chess board. It results in a
852% 'square' like distance function, but one where diagonals are closer
853% than expected.
anthony602ab9b2010-01-05 08:06:50 +0000854%
anthonybee715c2010-06-04 01:25:57 +0000855% Manhattan:[{radius}][x{scale}[%!]]
856% Manhattan Distance (also known as Rectilinear Distance, or the Taxi
anthonyc94cdb02010-01-06 08:15:29 +0000857% Cab metric), is the distance needed when you can only travel in
858% orthogonal (horizontal or vertical) only. It is the distance a 'Rook'
859% in chess would travel. It results in a diamond like distances, where
860% diagonals are further than expected.
anthony602ab9b2010-01-05 08:06:50 +0000861%
anthonyc1061722010-05-14 06:23:49 +0000862% Euclidean:[{radius}][x{scale}[%!]]
anthonyc94cdb02010-01-06 08:15:29 +0000863% Euclidean Distance is the 'direct' or 'as the crow flys distance.
864% However by default the kernel size only has a radius of 1, which
865% limits the distance to 'Knight' like moves, with only orthogonal and
866% diagonal measurements being correct. As such for the default kernel
867% you will get octagonal like distance function, which is reasonally
868% accurate.
869%
870% However if you use a larger radius such as "Euclidean:4" you will
871% get a much smoother distance gradient from the edge of the shape.
872% Of course a larger kernel is slower to use, and generally not needed.
873%
874% To allow the use of fractional distances that you get with diagonals
875% the actual distance is scaled by a fixed value which the user can
876% provide. This is not actually nessary for either ""Chebyshev" or
anthonybee715c2010-06-04 01:25:57 +0000877% "Manhattan" distance kernels, but is done for all three distance
anthonyc94cdb02010-01-06 08:15:29 +0000878% kernels. If no scale is provided it is set to a value of 100,
879% allowing for a maximum distance measurement of 655 pixels using a Q16
880% version of IM, from any edge. However for small images this can
881% result in quite a dark gradient.
882%
anthony602ab9b2010-01-05 08:06:50 +0000883*/
884
cristy2be15382010-01-21 02:38:03 +0000885MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
anthony602ab9b2010-01-05 08:06:50 +0000886 const GeometryInfo *args)
887{
cristy2be15382010-01-21 02:38:03 +0000888 KernelInfo
anthony602ab9b2010-01-05 08:06:50 +0000889 *kernel;
890
cristybb503372010-05-27 20:51:26 +0000891 register ssize_t
anthony602ab9b2010-01-05 08:06:50 +0000892 i;
893
cristybb503372010-05-27 20:51:26 +0000894 register ssize_t
anthony602ab9b2010-01-05 08:06:50 +0000895 u,
896 v;
897
898 double
899 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
900
anthonyc1061722010-05-14 06:23:49 +0000901 /* Generate a new empty kernel if needed */
cristye96405a2010-05-19 02:24:31 +0000902 kernel=(KernelInfo *) NULL;
anthonyc1061722010-05-14 06:23:49 +0000903 switch(type) {
anthony1dd091a2010-05-27 06:31:15 +0000904 case UndefinedKernel: /* These should not call this function */
anthony9eb4f742010-05-18 02:45:54 +0000905 case UserDefinedKernel:
anthony1dd091a2010-05-27 06:31:15 +0000906 case TestKernel:
anthony9eb4f742010-05-18 02:45:54 +0000907 break;
anthony1dd091a2010-05-27 06:31:15 +0000908 case UnityKernel: /* Named Descrete Convolution Kernels */
909 case LaplacianKernel:
anthony9eb4f742010-05-18 02:45:54 +0000910 case SobelKernel:
911 case RobertsKernel:
912 case PrewittKernel:
913 case CompassKernel:
914 case KirschKernel:
anthony1dd091a2010-05-27 06:31:15 +0000915 case FreiChenKernel:
anthony9eb4f742010-05-18 02:45:54 +0000916 case CornersKernel: /* Hit and Miss kernels */
917 case LineEndsKernel:
918 case LineJunctionsKernel:
anthony1dd091a2010-05-27 06:31:15 +0000919 case EdgesKernel:
920 case RidgesKernel:
921 case Ridges2Kernel:
anthony9eb4f742010-05-18 02:45:54 +0000922 case ConvexHullKernel:
923 case SkeletonKernel:
anthony1dd091a2010-05-27 06:31:15 +0000924 case MatKernel:
anthony9eb4f742010-05-18 02:45:54 +0000925 /* A pre-generated kernel is not needed */
926 break;
anthony1dd091a2010-05-27 06:31:15 +0000927#if 0 /* set to 1 to do a compile-time check that we haven't missed anything */
anthonyc1061722010-05-14 06:23:49 +0000928 case GaussianKernel:
anthony501c2f92010-06-02 10:55:14 +0000929 case DoGKernel:
930 case LoGKernel:
anthonyc1061722010-05-14 06:23:49 +0000931 case BlurKernel:
anthonyc1061722010-05-14 06:23:49 +0000932 case CometKernel:
933 case DiamondKernel:
934 case SquareKernel:
935 case RectangleKernel:
936 case DiskKernel:
937 case PlusKernel:
938 case CrossKernel:
939 case RingKernel:
940 case PeaksKernel:
941 case ChebyshevKernel:
anthonybee715c2010-06-04 01:25:57 +0000942 case ManhattanKernel:
anthonyc1061722010-05-14 06:23:49 +0000943 case EuclideanKernel:
anthony1dd091a2010-05-27 06:31:15 +0000944#else
anthony9eb4f742010-05-18 02:45:54 +0000945 default:
anthony1dd091a2010-05-27 06:31:15 +0000946#endif
anthony9eb4f742010-05-18 02:45:54 +0000947 /* Generate the base Kernel Structure */
anthonyc1061722010-05-14 06:23:49 +0000948 kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
949 if (kernel == (KernelInfo *) NULL)
950 return(kernel);
951 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
anthony43c49252010-05-18 10:59:50 +0000952 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
anthonyc1061722010-05-14 06:23:49 +0000953 kernel->negative_range = kernel->positive_range = 0.0;
954 kernel->type = type;
955 kernel->next = (KernelInfo *) NULL;
956 kernel->signature = MagickSignature;
anthonyc1061722010-05-14 06:23:49 +0000957 break;
958 }
anthony602ab9b2010-01-05 08:06:50 +0000959
960 switch(type) {
961 /* Convolution Kernels */
962 case GaussianKernel:
anthony501c2f92010-06-02 10:55:14 +0000963 case DoGKernel:
964 case LoGKernel:
anthony602ab9b2010-01-05 08:06:50 +0000965 { double
anthonyc1061722010-05-14 06:23:49 +0000966 sigma = fabs(args->sigma),
967 sigma2 = fabs(args->xi),
anthony9eb4f742010-05-18 02:45:54 +0000968 A, B, R;
anthony602ab9b2010-01-05 08:06:50 +0000969
anthonyc1061722010-05-14 06:23:49 +0000970 if ( args->rho >= 1.0 )
cristybb503372010-05-27 20:51:26 +0000971 kernel->width = (size_t)args->rho*2+1;
anthony501c2f92010-06-02 10:55:14 +0000972 else if ( (type != DoGKernel) || (sigma >= sigma2) )
anthonyc1061722010-05-14 06:23:49 +0000973 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
974 else
975 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
976 kernel->height = kernel->width;
cristybb503372010-05-27 20:51:26 +0000977 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +0000978 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
979 kernel->height*sizeof(double));
980 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +0000981 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000982
anthony46a369d2010-05-19 02:41:48 +0000983 /* WARNING: The following generates a 'sampled gaussian' kernel.
anthony9eb4f742010-05-18 02:45:54 +0000984 * What we really want is a 'discrete gaussian' kernel.
anthony46a369d2010-05-19 02:41:48 +0000985 *
986 * How to do this is currently not known, but appears to be
987 * basied on the Error Function 'erf()' (intergral of a gaussian)
anthony9eb4f742010-05-18 02:45:54 +0000988 */
989
anthony501c2f92010-06-02 10:55:14 +0000990 if ( type == GaussianKernel || type == DoGKernel )
991 { /* Calculate a Gaussian, OR positive half of a DoG */
anthony9eb4f742010-05-18 02:45:54 +0000992 if ( sigma > MagickEpsilon )
993 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
994 B = 1.0/(Magick2PI*sigma*sigma);
cristybb503372010-05-27 20:51:26 +0000995 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
996 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony9eb4f742010-05-18 02:45:54 +0000997 kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
998 }
999 else /* limiting case - a unity (normalized Dirac) kernel */
1000 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1001 kernel->width*kernel->height*sizeof(double));
1002 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1003 }
anthonyc1061722010-05-14 06:23:49 +00001004 }
anthony9eb4f742010-05-18 02:45:54 +00001005
anthony501c2f92010-06-02 10:55:14 +00001006 if ( type == DoGKernel )
anthonyc1061722010-05-14 06:23:49 +00001007 { /* Subtract a Negative Gaussian for "Difference of Gaussian" */
1008 if ( sigma2 > MagickEpsilon )
1009 { sigma = sigma2; /* simplify loop expressions */
anthony9eb4f742010-05-18 02:45:54 +00001010 A = 1.0/(2.0*sigma*sigma);
1011 B = 1.0/(Magick2PI*sigma*sigma);
cristybb503372010-05-27 20:51:26 +00001012 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1013 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony9eb4f742010-05-18 02:45:54 +00001014 kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
anthonyc1061722010-05-14 06:23:49 +00001015 }
anthony9eb4f742010-05-18 02:45:54 +00001016 else /* limiting case - a unity (normalized Dirac) kernel */
anthonyc1061722010-05-14 06:23:49 +00001017 kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1018 }
anthony9eb4f742010-05-18 02:45:54 +00001019
anthony501c2f92010-06-02 10:55:14 +00001020 if ( type == LoGKernel )
anthony9eb4f742010-05-18 02:45:54 +00001021 { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
1022 if ( sigma > MagickEpsilon )
1023 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1024 B = 1.0/(MagickPI*sigma*sigma*sigma*sigma);
cristybb503372010-05-27 20:51:26 +00001025 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1026 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony9eb4f742010-05-18 02:45:54 +00001027 { R = ((double)(u*u+v*v))*A;
1028 kernel->values[i] = (1-R)*exp(-R)*B;
1029 }
1030 }
1031 else /* special case - generate a unity kernel */
1032 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1033 kernel->width*kernel->height*sizeof(double));
1034 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1035 }
1036 }
1037
1038 /* Note the above kernels may have been 'clipped' by a user defined
anthonyc1061722010-05-14 06:23:49 +00001039 ** radius, producing a smaller (darker) kernel. Also for very small
1040 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1041 ** producing a very bright kernel.
1042 **
1043 ** Normalization will still be needed.
1044 */
anthony602ab9b2010-01-05 08:06:50 +00001045
anthony3dd0f622010-05-13 12:57:32 +00001046 /* Normalize the 2D Gaussian Kernel
1047 **
anthonyc1061722010-05-14 06:23:49 +00001048 ** NB: a CorrelateNormalize performs a normal Normalize if
1049 ** there are no negative values.
anthony3dd0f622010-05-13 12:57:32 +00001050 */
anthony46a369d2010-05-19 02:41:48 +00001051 CalcKernelMetaData(kernel); /* the other kernel meta-data */
anthonyc1061722010-05-14 06:23:49 +00001052 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
anthony602ab9b2010-01-05 08:06:50 +00001053
1054 break;
1055 }
1056 case BlurKernel:
1057 { double
anthonyc1061722010-05-14 06:23:49 +00001058 sigma = fabs(args->sigma),
anthony501c2f92010-06-02 10:55:14 +00001059 alpha, beta;
anthony602ab9b2010-01-05 08:06:50 +00001060
anthonyc1061722010-05-14 06:23:49 +00001061 if ( args->rho >= 1.0 )
cristybb503372010-05-27 20:51:26 +00001062 kernel->width = (size_t)args->rho*2+1;
anthonyc1061722010-05-14 06:23:49 +00001063 else
anthony501c2f92010-06-02 10:55:14 +00001064 kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
anthony602ab9b2010-01-05 08:06:50 +00001065 kernel->height = 1;
cristybb503372010-05-27 20:51:26 +00001066 kernel->x = (ssize_t) (kernel->width-1)/2;
cristyc99304f2010-02-01 15:26:27 +00001067 kernel->y = 0;
1068 kernel->negative_range = kernel->positive_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +00001069 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1070 kernel->height*sizeof(double));
1071 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001072 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001073
1074#if 1
1075#define KernelRank 3
1076 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix).
1077 ** It generates a gaussian 3 times the width, and compresses it into
1078 ** the expected range. This produces a closer normalization of the
1079 ** resulting kernel, especially for very low sigma values.
1080 ** As such while wierd it is prefered.
1081 **
1082 ** I am told this method originally came from Photoshop.
anthony9eb4f742010-05-18 02:45:54 +00001083 **
1084 ** A properly normalized curve is generated (apart from edge clipping)
1085 ** even though we later normalize the result (for edge clipping)
1086 ** to allow the correct generation of a "Difference of Blurs".
anthony602ab9b2010-01-05 08:06:50 +00001087 */
anthonyc1061722010-05-14 06:23:49 +00001088
1089 /* initialize */
cristybb503372010-05-27 20:51:26 +00001090 v = (ssize_t) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */
anthony9eb4f742010-05-18 02:45:54 +00001091 (void) ResetMagickMemory(kernel->values,0, (size_t)
1092 kernel->width*kernel->height*sizeof(double));
anthonyc1061722010-05-14 06:23:49 +00001093 /* Calculate a Positive 1D Gaussian */
1094 if ( sigma > MagickEpsilon )
1095 { sigma *= KernelRank; /* simplify loop expressions */
anthony501c2f92010-06-02 10:55:14 +00001096 alpha = 1.0/(2.0*sigma*sigma);
1097 beta= 1.0/(MagickSQ2PI*sigma );
anthonyc1061722010-05-14 06:23:49 +00001098 for ( u=-v; u <= v; u++) {
anthony501c2f92010-06-02 10:55:14 +00001099 kernel->values[(u+v)/KernelRank] +=
1100 exp(-((double)(u*u))*alpha)*beta;
anthonyc1061722010-05-14 06:23:49 +00001101 }
1102 }
1103 else /* special case - generate a unity kernel */
1104 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
anthony602ab9b2010-01-05 08:06:50 +00001105#else
anthonyc1061722010-05-14 06:23:49 +00001106 /* Direct calculation without curve averaging */
1107
1108 /* Calculate a Positive Gaussian */
1109 if ( sigma > MagickEpsilon )
anthony501c2f92010-06-02 10:55:14 +00001110 { alpha = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1111 beta = 1.0/(MagickSQ2PI*sigma);
cristybb503372010-05-27 20:51:26 +00001112 for ( i=0, u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony501c2f92010-06-02 10:55:14 +00001113 kernel->values[i] = exp(-((double)(u*u))*alpha)*beta;
anthonyc1061722010-05-14 06:23:49 +00001114 }
1115 else /* special case - generate a unity kernel */
1116 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1117 kernel->width*kernel->height*sizeof(double));
1118 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1119 }
anthony602ab9b2010-01-05 08:06:50 +00001120#endif
anthonyc1061722010-05-14 06:23:49 +00001121 /* Note the above kernel may have been 'clipped' by a user defined
anthonycc6c8362010-01-25 04:14:01 +00001122 ** radius, producing a smaller (darker) kernel. Also for very small
1123 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1124 ** producing a very bright kernel.
anthonyc1061722010-05-14 06:23:49 +00001125 **
1126 ** Normalization will still be needed.
anthony602ab9b2010-01-05 08:06:50 +00001127 */
anthonycc6c8362010-01-25 04:14:01 +00001128
anthony602ab9b2010-01-05 08:06:50 +00001129 /* Normalize the 1D Gaussian Kernel
1130 **
anthonyc1061722010-05-14 06:23:49 +00001131 ** NB: a CorrelateNormalize performs a normal Normalize if
1132 ** there are no negative values.
anthony602ab9b2010-01-05 08:06:50 +00001133 */
anthony46a369d2010-05-19 02:41:48 +00001134 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1135 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
anthonycc6c8362010-01-25 04:14:01 +00001136
anthonyc1061722010-05-14 06:23:49 +00001137 /* rotate the 1D kernel by given angle */
anthony501c2f92010-06-02 10:55:14 +00001138 RotateKernelInfo(kernel, args->xi );
anthony602ab9b2010-01-05 08:06:50 +00001139 break;
1140 }
1141 case CometKernel:
1142 { double
anthony9eb4f742010-05-18 02:45:54 +00001143 sigma = fabs(args->sigma),
1144 A;
anthony602ab9b2010-01-05 08:06:50 +00001145
anthony602ab9b2010-01-05 08:06:50 +00001146 if ( args->rho < 1.0 )
anthonye1cf9462010-05-19 03:50:26 +00001147 kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
anthony602ab9b2010-01-05 08:06:50 +00001148 else
cristybb503372010-05-27 20:51:26 +00001149 kernel->width = (size_t)args->rho;
cristyc99304f2010-02-01 15:26:27 +00001150 kernel->x = kernel->y = 0;
anthony602ab9b2010-01-05 08:06:50 +00001151 kernel->height = 1;
cristyc99304f2010-02-01 15:26:27 +00001152 kernel->negative_range = kernel->positive_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +00001153 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1154 kernel->height*sizeof(double));
1155 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001156 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001157
anthonyc1061722010-05-14 06:23:49 +00001158 /* A comet blur is half a 1D gaussian curve, so that the object is
anthony602ab9b2010-01-05 08:06:50 +00001159 ** blurred in one direction only. This may not be quite the right
anthony3dd0f622010-05-13 12:57:32 +00001160 ** curve to use so may change in the future. The function must be
1161 ** normalised after generation, which also resolves any clipping.
anthonyc1061722010-05-14 06:23:49 +00001162 **
1163 ** As we are normalizing and not subtracting gaussians,
1164 ** there is no need for a divisor in the gaussian formula
1165 **
anthony43c49252010-05-18 10:59:50 +00001166 ** It is less comples
anthony602ab9b2010-01-05 08:06:50 +00001167 */
anthony9eb4f742010-05-18 02:45:54 +00001168 if ( sigma > MagickEpsilon )
1169 {
anthony602ab9b2010-01-05 08:06:50 +00001170#if 1
1171#define KernelRank 3
cristybb503372010-05-27 20:51:26 +00001172 v = (ssize_t) kernel->width*KernelRank; /* start/end points */
anthony9eb4f742010-05-18 02:45:54 +00001173 (void) ResetMagickMemory(kernel->values,0, (size_t)
1174 kernel->width*sizeof(double));
1175 sigma *= KernelRank; /* simplify the loop expression */
1176 A = 1.0/(2.0*sigma*sigma);
1177 /* B = 1.0/(MagickSQ2PI*sigma); */
1178 for ( u=0; u < v; u++) {
1179 kernel->values[u/KernelRank] +=
1180 exp(-((double)(u*u))*A);
1181 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1182 }
cristybb503372010-05-27 20:51:26 +00001183 for (i=0; i < (ssize_t) kernel->width; i++)
anthony9eb4f742010-05-18 02:45:54 +00001184 kernel->positive_range += kernel->values[i];
anthony602ab9b2010-01-05 08:06:50 +00001185#else
anthony9eb4f742010-05-18 02:45:54 +00001186 A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
1187 /* B = 1.0/(MagickSQ2PI*sigma); */
cristybb503372010-05-27 20:51:26 +00001188 for ( i=0; i < (ssize_t) kernel->width; i++)
anthony9eb4f742010-05-18 02:45:54 +00001189 kernel->positive_range +=
1190 kernel->values[i] =
1191 exp(-((double)(i*i))*A);
1192 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
anthony602ab9b2010-01-05 08:06:50 +00001193#endif
anthony9eb4f742010-05-18 02:45:54 +00001194 }
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;
1199 kernel->positive_range = 1.0;
1200 }
anthony46a369d2010-05-19 02:41:48 +00001201
1202 kernel->minimum = 0.0;
cristyc99304f2010-02-01 15:26:27 +00001203 kernel->maximum = kernel->values[0];
anthony46a369d2010-05-19 02:41:48 +00001204 kernel->negative_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +00001205
anthony999bb2c2010-02-18 12:38:01 +00001206 ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1207 RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
anthony602ab9b2010-01-05 08:06:50 +00001208 break;
1209 }
anthonyc1061722010-05-14 06:23:49 +00001210
anthony3c10fc82010-05-13 02:40:51 +00001211 /* Convolution Kernels - Well Known Constants */
anthony3c10fc82010-05-13 02:40:51 +00001212 case LaplacianKernel:
anthonye2a60ce2010-05-19 12:30:40 +00001213 { switch ( (int) args->rho ) {
anthony3dd0f622010-05-13 12:57:32 +00001214 case 0:
anthony9eb4f742010-05-18 02:45:54 +00001215 default: /* laplacian square filter -- default */
anthonyc1061722010-05-14 06:23:49 +00001216 kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
anthony3dd0f622010-05-13 12:57:32 +00001217 break;
anthony9eb4f742010-05-18 02:45:54 +00001218 case 1: /* laplacian diamond filter */
anthonyc1061722010-05-14 06:23:49 +00001219 kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
anthony3c10fc82010-05-13 02:40:51 +00001220 break;
1221 case 2:
anthony9eb4f742010-05-18 02:45:54 +00001222 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1223 break;
1224 case 3:
anthonyc1061722010-05-14 06:23:49 +00001225 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
anthony3c10fc82010-05-13 02:40:51 +00001226 break;
anthony9eb4f742010-05-18 02:45:54 +00001227 case 5: /* a 5x5 laplacian */
anthony3c10fc82010-05-13 02:40:51 +00001228 kernel=ParseKernelArray(
anthony9eb4f742010-05-18 02:45:54 +00001229 "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");
anthony3c10fc82010-05-13 02:40:51 +00001230 break;
anthony9eb4f742010-05-18 02:45:54 +00001231 case 7: /* a 7x7 laplacian */
anthony3c10fc82010-05-13 02:40:51 +00001232 kernel=ParseKernelArray(
anthonyc1061722010-05-14 06:23:49 +00001233 "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" );
anthony3c10fc82010-05-13 02:40:51 +00001234 break;
anthony501c2f92010-06-02 10:55:14 +00001235 case 15: /* a 5x5 LoG (sigma approx 1.4) */
anthony9eb4f742010-05-18 02:45:54 +00001236 kernel=ParseKernelArray(
1237 "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");
1238 break;
anthony501c2f92010-06-02 10:55:14 +00001239 case 19: /* a 9x9 LoG (sigma approx 1.4) */
anthony43c49252010-05-18 10:59:50 +00001240 /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1241 kernel=ParseKernelArray(
anthonybfb635a2010-06-04 00:18:04 +00001242 "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");
anthony43c49252010-05-18 10:59:50 +00001243 break;
anthony3c10fc82010-05-13 02:40:51 +00001244 }
1245 if (kernel == (KernelInfo *) NULL)
1246 return(kernel);
1247 kernel->type = type;
1248 break;
1249 }
anthonyc1061722010-05-14 06:23:49 +00001250 case SobelKernel:
anthony602ab9b2010-01-05 08:06:50 +00001251 {
anthony501c2f92010-06-02 10:55:14 +00001252 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
anthonyc1061722010-05-14 06:23:49 +00001253 if (kernel == (KernelInfo *) NULL)
1254 return(kernel);
1255 kernel->type = type;
1256 RotateKernelInfo(kernel, args->rho); /* Rotate by angle */
1257 break;
1258 }
1259 case RobertsKernel:
1260 {
anthony501c2f92010-06-02 10:55:14 +00001261 kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0");
anthonyc1061722010-05-14 06:23:49 +00001262 if (kernel == (KernelInfo *) NULL)
1263 return(kernel);
1264 kernel->type = type;
anthony46a369d2010-05-19 02:41:48 +00001265 RotateKernelInfo(kernel, args->rho);
anthonyc1061722010-05-14 06:23:49 +00001266 break;
1267 }
1268 case PrewittKernel:
1269 {
anthony501c2f92010-06-02 10:55:14 +00001270 kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1");
anthonyc1061722010-05-14 06:23:49 +00001271 if (kernel == (KernelInfo *) NULL)
1272 return(kernel);
1273 kernel->type = type;
anthony46a369d2010-05-19 02:41:48 +00001274 RotateKernelInfo(kernel, args->rho);
anthonyc1061722010-05-14 06:23:49 +00001275 break;
1276 }
1277 case CompassKernel:
1278 {
anthony501c2f92010-06-02 10:55:14 +00001279 kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1");
anthonyc1061722010-05-14 06:23:49 +00001280 if (kernel == (KernelInfo *) NULL)
1281 return(kernel);
1282 kernel->type = type;
anthony46a369d2010-05-19 02:41:48 +00001283 RotateKernelInfo(kernel, args->rho);
anthonyc1061722010-05-14 06:23:49 +00001284 break;
1285 }
anthony9eb4f742010-05-18 02:45:54 +00001286 case KirschKernel:
1287 {
anthony501c2f92010-06-02 10:55:14 +00001288 kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3");
anthony9eb4f742010-05-18 02:45:54 +00001289 if (kernel == (KernelInfo *) NULL)
1290 return(kernel);
1291 kernel->type = type;
anthony46a369d2010-05-19 02:41:48 +00001292 RotateKernelInfo(kernel, args->rho);
anthony9eb4f742010-05-18 02:45:54 +00001293 break;
1294 }
anthonye2a60ce2010-05-19 12:30:40 +00001295 case FreiChenKernel:
anthony501c2f92010-06-02 10:55:14 +00001296 /* Direction is set to be left to right positive */
1297 /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
1298 /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
anthony1dd091a2010-05-27 06:31:15 +00001299 { switch ( (int) args->rho ) {
anthonye2a60ce2010-05-19 12:30:40 +00001300 default:
anthonyc3cd15b2010-05-27 06:05:40 +00001301 case 0:
anthony501c2f92010-06-02 10:55:14 +00001302 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
anthonyc3cd15b2010-05-27 06:05:40 +00001303 if (kernel == (KernelInfo *) NULL)
1304 return(kernel);
anthonyef33d9f2010-06-02 12:27:01 +00001305 kernel->type = type;
anthony501c2f92010-06-02 10:55:14 +00001306 kernel->values[3] = +MagickSQ2;
1307 kernel->values[5] = -MagickSQ2;
anthonyc3cd15b2010-05-27 06:05:40 +00001308 CalcKernelMetaData(kernel); /* recalculate meta-data */
anthonyc3cd15b2010-05-27 06:05:40 +00001309 break;
anthonye2a60ce2010-05-19 12:30:40 +00001310 case 1:
anthony501c2f92010-06-02 10:55:14 +00001311 kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
anthonye2a60ce2010-05-19 12:30:40 +00001312 if (kernel == (KernelInfo *) NULL)
1313 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001314 kernel->type = type;
anthony501c2f92010-06-02 10:55:14 +00001315 kernel->values[3] = +MagickSQ2;
1316 kernel->values[5] = -MagickSQ2;
anthonye2a60ce2010-05-19 12:30:40 +00001317 CalcKernelMetaData(kernel); /* recalculate meta-data */
1318 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1319 break;
1320 case 2:
anthony501c2f92010-06-02 10:55:14 +00001321 kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1");
anthonye2a60ce2010-05-19 12:30:40 +00001322 if (kernel == (KernelInfo *) NULL)
1323 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001324 kernel->type = type;
anthony1d5e6702010-05-31 10:19:12 +00001325 kernel->values[1] = +MagickSQ2;
1326 kernel->values[7] = +MagickSQ2;
anthonye2a60ce2010-05-19 12:30:40 +00001327 CalcKernelMetaData(kernel);
1328 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1329 break;
1330 case 3:
anthony501c2f92010-06-02 10:55:14 +00001331 kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
anthonye2a60ce2010-05-19 12:30:40 +00001332 if (kernel == (KernelInfo *) NULL)
1333 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001334 kernel->type = type;
anthony501c2f92010-06-02 10:55:14 +00001335 kernel->values[0] = +MagickSQ2;
1336 kernel->values[8] = -MagickSQ2;
anthonye2a60ce2010-05-19 12:30:40 +00001337 CalcKernelMetaData(kernel);
1338 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1339 break;
1340 case 4:
anthony1d5e6702010-05-31 10:19:12 +00001341 kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0");
anthonye2a60ce2010-05-19 12:30:40 +00001342 if (kernel == (KernelInfo *) NULL)
1343 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001344 kernel->type = type;
anthony1d5e6702010-05-31 10:19:12 +00001345 kernel->values[2] = -MagickSQ2;
1346 kernel->values[6] = +MagickSQ2;
anthonye2a60ce2010-05-19 12:30:40 +00001347 CalcKernelMetaData(kernel);
1348 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1349 break;
1350 case 5:
anthony501c2f92010-06-02 10:55:14 +00001351 kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0");
anthonye2a60ce2010-05-19 12:30:40 +00001352 if (kernel == (KernelInfo *) NULL)
1353 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001354 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001355 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1356 break;
1357 case 6:
anthony1d5e6702010-05-31 10:19:12 +00001358 kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1");
anthonye2a60ce2010-05-19 12:30:40 +00001359 if (kernel == (KernelInfo *) NULL)
1360 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001361 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001362 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1363 break;
1364 case 7:
anthony501c2f92010-06-02 10:55:14 +00001365 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1");
anthonye2a60ce2010-05-19 12:30:40 +00001366 if (kernel == (KernelInfo *) NULL)
1367 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001368 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001369 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1370 break;
1371 case 8:
anthony501c2f92010-06-02 10:55:14 +00001372 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
anthonye2a60ce2010-05-19 12:30:40 +00001373 if (kernel == (KernelInfo *) NULL)
1374 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001375 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001376 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1377 break;
1378 case 9:
anthonyc3cd15b2010-05-27 06:05:40 +00001379 kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
anthonye2a60ce2010-05-19 12:30:40 +00001380 if (kernel == (KernelInfo *) NULL)
1381 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001382 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001383 ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1384 break;
anthonyc3cd15b2010-05-27 06:05:40 +00001385 case -1:
anthony1dd091a2010-05-27 06:31:15 +00001386 kernel=AcquireKernelInfo("FreiChen:1;FreiChen:2;FreiChen:3;FreiChen:4;FreiChen:5;FreiChen:6;FreiChen:7;FreiChen:8;FreiChen:9");
1387 if (kernel == (KernelInfo *) NULL)
1388 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001389 break;
anthonye2a60ce2010-05-19 12:30:40 +00001390 }
anthonyc3cd15b2010-05-27 06:05:40 +00001391 if ( fabs(args->sigma) > MagickEpsilon )
1392 /* Rotate by correctly supplied 'angle' */
1393 RotateKernelInfo(kernel, args->sigma);
1394 else if ( args->rho > 30.0 || args->rho < -30.0 )
1395 /* Rotate by out of bounds 'type' */
1396 RotateKernelInfo(kernel, args->rho);
anthonye2a60ce2010-05-19 12:30:40 +00001397 break;
1398 }
1399
anthonyc1061722010-05-14 06:23:49 +00001400 /* Boolean Kernels */
1401 case DiamondKernel:
1402 {
1403 if (args->rho < 1.0)
1404 kernel->width = kernel->height = 3; /* default radius = 1 */
1405 else
cristybb503372010-05-27 20:51:26 +00001406 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1407 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthonyc1061722010-05-14 06:23:49 +00001408
1409 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1410 kernel->height*sizeof(double));
1411 if (kernel->values == (double *) NULL)
1412 return(DestroyKernelInfo(kernel));
1413
1414 /* set all kernel values within diamond area to scale given */
cristybb503372010-05-27 20:51:26 +00001415 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1416 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony1d5e6702010-05-31 10:19:12 +00001417 if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
anthonyc1061722010-05-14 06:23:49 +00001418 kernel->positive_range += kernel->values[i] = args->sigma;
1419 else
1420 kernel->values[i] = nan;
1421 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1422 break;
1423 }
1424 case SquareKernel:
1425 case RectangleKernel:
1426 { double
1427 scale;
anthony602ab9b2010-01-05 08:06:50 +00001428 if ( type == SquareKernel )
1429 {
1430 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001431 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001432 else
cristybb503372010-05-27 20:51:26 +00001433 kernel->width = kernel->height = (size_t) (2*args->rho+1);
1434 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony4fd27e22010-02-07 08:17:18 +00001435 scale = args->sigma;
anthony602ab9b2010-01-05 08:06:50 +00001436 }
1437 else {
cristy2be15382010-01-21 02:38:03 +00001438 /* NOTE: user defaults set in "AcquireKernelInfo()" */
anthony602ab9b2010-01-05 08:06:50 +00001439 if ( args->rho < 1.0 || args->sigma < 1.0 )
anthony83ba99b2010-01-24 08:48:15 +00001440 return(DestroyKernelInfo(kernel)); /* invalid args given */
cristybb503372010-05-27 20:51:26 +00001441 kernel->width = (size_t)args->rho;
1442 kernel->height = (size_t)args->sigma;
anthony602ab9b2010-01-05 08:06:50 +00001443 if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
1444 args->psi < 0.0 || args->psi > (double)kernel->height )
anthony83ba99b2010-01-24 08:48:15 +00001445 return(DestroyKernelInfo(kernel)); /* invalid args given */
cristybb503372010-05-27 20:51:26 +00001446 kernel->x = (ssize_t) args->xi;
1447 kernel->y = (ssize_t) args->psi;
anthony4fd27e22010-02-07 08:17:18 +00001448 scale = 1.0;
anthony602ab9b2010-01-05 08:06:50 +00001449 }
1450 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1451 kernel->height*sizeof(double));
1452 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001453 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001454
anthony3dd0f622010-05-13 12:57:32 +00001455 /* set all kernel values to scale given */
cristyeaedf062010-05-29 22:36:02 +00001456 u=(ssize_t) (kernel->width*kernel->height);
cristy150989e2010-02-01 14:59:39 +00001457 for ( i=0; i < u; i++)
anthony4fd27e22010-02-07 08:17:18 +00001458 kernel->values[i] = scale;
1459 kernel->minimum = kernel->maximum = scale; /* a flat shape */
1460 kernel->positive_range = scale*u;
anthonycc6c8362010-01-25 04:14:01 +00001461 break;
anthony602ab9b2010-01-05 08:06:50 +00001462 }
anthony602ab9b2010-01-05 08:06:50 +00001463 case DiskKernel:
1464 {
anthonye4d89962010-05-29 10:53:11 +00001465 ssize_t
1466 limit = (ssize_t)(args->rho*args->rho);
1467
1468 if (args->rho < 0.4) /* default radius approx 3.5 */
anthony83ba99b2010-01-24 08:48:15 +00001469 kernel->width = kernel->height = 7L, limit = 10L;
anthony602ab9b2010-01-05 08:06:50 +00001470 else
anthonye4d89962010-05-29 10:53:11 +00001471 kernel->width = kernel->height = (size_t)fabs(args->rho)*2+1;
cristybb503372010-05-27 20:51:26 +00001472 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001473
1474 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1475 kernel->height*sizeof(double));
1476 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001477 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001478
anthony3dd0f622010-05-13 12:57:32 +00001479 /* set all kernel values within disk area to scale given */
cristybb503372010-05-27 20:51:26 +00001480 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1481 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony602ab9b2010-01-05 08:06:50 +00001482 if ((u*u+v*v) <= limit)
anthony4fd27e22010-02-07 08:17:18 +00001483 kernel->positive_range += kernel->values[i] = args->sigma;
anthony602ab9b2010-01-05 08:06:50 +00001484 else
1485 kernel->values[i] = nan;
anthony4fd27e22010-02-07 08:17:18 +00001486 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
anthony602ab9b2010-01-05 08:06:50 +00001487 break;
1488 }
1489 case PlusKernel:
1490 {
1491 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001492 kernel->width = kernel->height = 5; /* default radius 2 */
anthony602ab9b2010-01-05 08:06:50 +00001493 else
cristybb503372010-05-27 20:51:26 +00001494 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1495 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001496
1497 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1498 kernel->height*sizeof(double));
1499 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001500 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001501
cristycee97112010-05-28 00:44:52 +00001502 /* set all kernel values along axises to given scale */
cristybb503372010-05-27 20:51:26 +00001503 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1504 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony4fd27e22010-02-07 08:17:18 +00001505 kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1506 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1507 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
anthony602ab9b2010-01-05 08:06:50 +00001508 break;
1509 }
anthony3dd0f622010-05-13 12:57:32 +00001510 case CrossKernel:
1511 {
1512 if (args->rho < 1.0)
1513 kernel->width = kernel->height = 5; /* default radius 2 */
1514 else
cristybb503372010-05-27 20:51:26 +00001515 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1516 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony3dd0f622010-05-13 12:57:32 +00001517
1518 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1519 kernel->height*sizeof(double));
1520 if (kernel->values == (double *) NULL)
1521 return(DestroyKernelInfo(kernel));
1522
cristycee97112010-05-28 00:44:52 +00001523 /* set all kernel values along axises to given scale */
cristybb503372010-05-27 20:51:26 +00001524 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1525 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
anthony3dd0f622010-05-13 12:57:32 +00001526 kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1527 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1528 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1529 break;
1530 }
1531 /* HitAndMiss Kernels */
anthonyc1061722010-05-14 06:23:49 +00001532 case RingKernel:
anthony3dd0f622010-05-13 12:57:32 +00001533 case PeaksKernel:
1534 {
cristybb503372010-05-27 20:51:26 +00001535 ssize_t
anthony3dd0f622010-05-13 12:57:32 +00001536 limit1,
anthonyc1061722010-05-14 06:23:49 +00001537 limit2,
1538 scale;
anthony3dd0f622010-05-13 12:57:32 +00001539
1540 if (args->rho < args->sigma)
1541 {
cristybb503372010-05-27 20:51:26 +00001542 kernel->width = ((size_t)args->sigma)*2+1;
anthonye4d89962010-05-29 10:53:11 +00001543 limit1 = (ssize_t)(args->rho*args->rho);
1544 limit2 = (ssize_t)(args->sigma*args->sigma);
anthony3dd0f622010-05-13 12:57:32 +00001545 }
1546 else
1547 {
cristybb503372010-05-27 20:51:26 +00001548 kernel->width = ((size_t)args->rho)*2+1;
anthonye4d89962010-05-29 10:53:11 +00001549 limit1 = (ssize_t)(args->sigma*args->sigma);
1550 limit2 = (ssize_t)(args->rho*args->rho);
anthony3dd0f622010-05-13 12:57:32 +00001551 }
anthonyc1061722010-05-14 06:23:49 +00001552 if ( limit2 <= 0 )
1553 kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1554
anthony3dd0f622010-05-13 12:57:32 +00001555 kernel->height = kernel->width;
cristybb503372010-05-27 20:51:26 +00001556 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony3dd0f622010-05-13 12:57:32 +00001557 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1558 kernel->height*sizeof(double));
1559 if (kernel->values == (double *) NULL)
1560 return(DestroyKernelInfo(kernel));
1561
anthonyc1061722010-05-14 06:23:49 +00001562 /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
cristybb503372010-05-27 20:51:26 +00001563 scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
1564 for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
1565 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1566 { ssize_t radius=u*u+v*v;
anthonyc1061722010-05-14 06:23:49 +00001567 if (limit1 < radius && radius <= limit2)
cristye96405a2010-05-19 02:24:31 +00001568 kernel->positive_range += kernel->values[i] = (double) scale;
anthony3dd0f622010-05-13 12:57:32 +00001569 else
1570 kernel->values[i] = nan;
1571 }
cristye96405a2010-05-19 02:24:31 +00001572 kernel->minimum = kernel->minimum = (double) scale;
anthonyc1061722010-05-14 06:23:49 +00001573 if ( type == PeaksKernel ) {
1574 /* set the central point in the middle */
1575 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1576 kernel->positive_range = 1.0;
1577 kernel->maximum = 1.0;
1578 }
anthony3dd0f622010-05-13 12:57:32 +00001579 break;
1580 }
anthony43c49252010-05-18 10:59:50 +00001581 case EdgesKernel:
1582 {
1583 kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1584 if (kernel == (KernelInfo *) NULL)
1585 return(kernel);
1586 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001587 ExpandMirrorKernelInfo(kernel); /* mirror expansion of other kernels */
anthony43c49252010-05-18 10:59:50 +00001588 break;
1589 }
anthony3dd0f622010-05-13 12:57:32 +00001590 case CornersKernel:
1591 {
anthony4f1dcb72010-05-14 08:43:10 +00001592 kernel=ParseKernelArray("3: 0,0,- 0,1,1 -,1,-");
anthony3dd0f622010-05-13 12:57:32 +00001593 if (kernel == (KernelInfo *) NULL)
1594 return(kernel);
1595 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001596 ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
anthony3dd0f622010-05-13 12:57:32 +00001597 break;
1598 }
anthony47f5d062010-05-23 07:47:50 +00001599 case RidgesKernel:
1600 {
anthony24a19842010-05-27 12:18:34 +00001601 kernel=ParseKernelArray("3x1:0,1,0");
anthony47f5d062010-05-23 07:47:50 +00001602 if (kernel == (KernelInfo *) NULL)
1603 return(kernel);
1604 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001605 ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
anthony47f5d062010-05-23 07:47:50 +00001606 break;
1607 }
anthony1d45eb92010-05-25 11:13:23 +00001608 case Ridges2Kernel:
1609 {
1610 KernelInfo
1611 *new_kernel;
anthony24a19842010-05-27 12:18:34 +00001612 kernel=ParseKernelArray("4x1:0,1,1,0");
anthony1d45eb92010-05-25 11:13:23 +00001613 if (kernel == (KernelInfo *) NULL)
1614 return(kernel);
1615 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001616 ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
anthonya648a302010-05-27 02:14:36 +00001617#if 0
1618 /* 2 pixel diagonaly thick - 4 rotates - not needed? */
anthonybfb635a2010-06-04 00:18:04 +00001619 new_kernel=ParseKernelArray("4x4>:0,-,-,- -,1,-,- -,-,1,- -,-,-,0'");
anthony1d45eb92010-05-25 11:13:23 +00001620 if (new_kernel == (KernelInfo *) NULL)
1621 return(DestroyKernelInfo(kernel));
1622 new_kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001623 ExpandRotateKernelInfo(new_kernel, 90.0); /* 4 rotated kernels */
anthony1d45eb92010-05-25 11:13:23 +00001624 LastKernelInfo(kernel)->next = new_kernel;
anthonya648a302010-05-27 02:14:36 +00001625#endif
anthonybfb635a2010-06-04 00:18:04 +00001626 /* kernels to find a stepped 'thick' line, 4 rotates * mirror */
anthonya648a302010-05-27 02:14:36 +00001627 /* Unfortunatally we can not yet rotate a non-square kernel */
1628 /* But then we can't flip a non-symetrical kernel either */
1629 new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1630 if (new_kernel == (KernelInfo *) NULL)
1631 return(DestroyKernelInfo(kernel));
1632 new_kernel->type = type;
1633 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001634 new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
anthonya648a302010-05-27 02:14:36 +00001635 if (new_kernel == (KernelInfo *) NULL)
1636 return(DestroyKernelInfo(kernel));
1637 new_kernel->type = type;
1638 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001639 new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
anthonya648a302010-05-27 02:14:36 +00001640 if (new_kernel == (KernelInfo *) NULL)
1641 return(DestroyKernelInfo(kernel));
1642 new_kernel->type = type;
1643 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001644 new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
anthonya648a302010-05-27 02:14:36 +00001645 if (new_kernel == (KernelInfo *) NULL)
1646 return(DestroyKernelInfo(kernel));
1647 new_kernel->type = type;
1648 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001649 new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
anthonya648a302010-05-27 02:14:36 +00001650 if (new_kernel == (KernelInfo *) NULL)
1651 return(DestroyKernelInfo(kernel));
1652 new_kernel->type = type;
1653 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001654 new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
anthonya648a302010-05-27 02:14:36 +00001655 if (new_kernel == (KernelInfo *) NULL)
1656 return(DestroyKernelInfo(kernel));
1657 new_kernel->type = type;
1658 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001659 new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
anthonya648a302010-05-27 02:14:36 +00001660 if (new_kernel == (KernelInfo *) NULL)
1661 return(DestroyKernelInfo(kernel));
1662 new_kernel->type = type;
1663 LastKernelInfo(kernel)->next = new_kernel;
anthony24a19842010-05-27 12:18:34 +00001664 new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
anthonya648a302010-05-27 02:14:36 +00001665 if (new_kernel == (KernelInfo *) NULL)
1666 return(DestroyKernelInfo(kernel));
1667 new_kernel->type = type;
1668 LastKernelInfo(kernel)->next = new_kernel;
anthony1d45eb92010-05-25 11:13:23 +00001669 break;
1670 }
anthony3dd0f622010-05-13 12:57:32 +00001671 case LineEndsKernel:
1672 {
anthony43c49252010-05-18 10:59:50 +00001673 KernelInfo
1674 *new_kernel;
1675 kernel=ParseKernelArray("3: 0,0,0 0,1,0 -,1,-");
anthony3dd0f622010-05-13 12:57:32 +00001676 if (kernel == (KernelInfo *) NULL)
1677 return(kernel);
1678 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001679 ExpandRotateKernelInfo(kernel, 90.0);
anthony43c49252010-05-18 10:59:50 +00001680 /* append second set of 4 kernels */
1681 new_kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
1682 if (new_kernel == (KernelInfo *) NULL)
1683 return(DestroyKernelInfo(kernel));
1684 new_kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001685 ExpandRotateKernelInfo(new_kernel, 90.0);
anthony43c49252010-05-18 10:59:50 +00001686 LastKernelInfo(kernel)->next = new_kernel;
anthony3dd0f622010-05-13 12:57:32 +00001687 break;
1688 }
1689 case LineJunctionsKernel:
1690 {
1691 KernelInfo
1692 *new_kernel;
anthony3dd0f622010-05-13 12:57:32 +00001693 /* first set of 4 kernels */
anthony4f1dcb72010-05-14 08:43:10 +00001694 kernel=ParseKernelArray("3: -,1,- -,1,- 1,-,1");
anthony3dd0f622010-05-13 12:57:32 +00001695 if (kernel == (KernelInfo *) NULL)
1696 return(kernel);
1697 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001698 ExpandRotateKernelInfo(kernel, 45.0);
anthony3dd0f622010-05-13 12:57:32 +00001699 /* append second set of 4 kernels */
anthony4f1dcb72010-05-14 08:43:10 +00001700 new_kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
anthony3dd0f622010-05-13 12:57:32 +00001701 if (new_kernel == (KernelInfo *) NULL)
1702 return(DestroyKernelInfo(kernel));
anthony43c49252010-05-18 10:59:50 +00001703 new_kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001704 ExpandRotateKernelInfo(new_kernel, 90.0);
anthony3dd0f622010-05-13 12:57:32 +00001705 LastKernelInfo(kernel)->next = new_kernel;
anthony4f1dcb72010-05-14 08:43:10 +00001706 break;
1707 }
anthony3dd0f622010-05-13 12:57:32 +00001708 case ConvexHullKernel:
1709 {
anthony3928ec62010-05-27 14:03:29 +00001710 KernelInfo
1711 *new_kernel;
1712 /* first set of 8 kernels */
anthony4f1dcb72010-05-14 08:43:10 +00001713 kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
anthony3dd0f622010-05-13 12:57:32 +00001714 if (kernel == (KernelInfo *) NULL)
1715 return(kernel);
1716 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001717 ExpandRotateKernelInfo(kernel, 45.0);
anthony5b93cbe2010-05-27 13:54:14 +00001718 /* append the mirror versions too */
1719 new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0");
1720 if (new_kernel == (KernelInfo *) NULL)
1721 return(DestroyKernelInfo(kernel));
1722 new_kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001723 ExpandRotateKernelInfo(new_kernel, 45.0);
anthony5b93cbe2010-05-27 13:54:14 +00001724 LastKernelInfo(kernel)->next = new_kernel;
anthony3dd0f622010-05-13 12:57:32 +00001725 break;
1726 }
anthony47f5d062010-05-23 07:47:50 +00001727 case SkeletonKernel:
anthonya648a302010-05-27 02:14:36 +00001728 { /* what is the best form for skeletonization by thinning? */
anthonybfb635a2010-06-04 00:18:04 +00001729#if 0
1730 /* Use a edge/corner pruning method to generate a skeleton.
1731 ** This actually works, but tends to generate slightly thick
1732 ** diagonals. Later thinning of those diagonals results in
1733 ** asymetrically thining.
1734 */
1735 kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
anthony3dd0f622010-05-13 12:57:32 +00001736 if (kernel == (KernelInfo *) NULL)
1737 return(kernel);
1738 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001739 ExpandRotateKernelInfo(kernel, 45);
1740 break;
1741 }
anthonye4d89962010-05-29 10:53:11 +00001742#endif
anthonybfb635a2010-06-04 00:18:04 +00001743#if 1
1744 /* This is like simple 'Edge' thinning, but with a extra two
1745 ** kernels (3 x 4 rotates => 12) to finish off the pruning
1746 ** of the diagonal lines.
1747 */
anthonye4d89962010-05-29 10:53:11 +00001748 KernelInfo
1749 *new_kernel;
1750 kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1751 if (kernel == (KernelInfo *) NULL)
1752 return(kernel);
1753 kernel->type = type;
anthonybfb635a2010-06-04 00:18:04 +00001754 new_kernel=ParseKernelArray("3: 0,0,0 0,1,1 1,1,-");
anthonye4d89962010-05-29 10:53:11 +00001755 if (new_kernel == (KernelInfo *) NULL)
1756 return(DestroyKernelInfo(kernel));
1757 new_kernel->type = type;
anthonye4d89962010-05-29 10:53:11 +00001758 LastKernelInfo(kernel)->next = new_kernel;
anthonybfb635a2010-06-04 00:18:04 +00001759 new_kernel=ParseKernelArray("3: 0,0,0 1,1,0 -,1,1");
1760 if (new_kernel == (KernelInfo *) NULL)
1761 return(DestroyKernelInfo(kernel));
1762 new_kernel->type = type;
1763 LastKernelInfo(kernel)->next = new_kernel;
1764 ExpandMirrorKernelInfo(kernel);
anthony3dd0f622010-05-13 12:57:32 +00001765 break;
anthonybfb635a2010-06-04 00:18:04 +00001766#endif
anthony3dd0f622010-05-13 12:57:32 +00001767 }
anthonya648a302010-05-27 02:14:36 +00001768 case MatKernel: /* experimental - MAT from a Distance Gradient */
1769 {
1770 KernelInfo
1771 *new_kernel;
1772 /* Ridge Kernel but without the diagonal */
1773 kernel=ParseKernelArray("3x1: 0,1,0");
1774 if (kernel == (KernelInfo *) NULL)
1775 return(kernel);
1776 kernel->type = RidgesKernel;
anthonybfb635a2010-06-04 00:18:04 +00001777 ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
anthonya648a302010-05-27 02:14:36 +00001778 /* Plus the 2 pixel ridges kernel - no diagonal */
1779 new_kernel=AcquireKernelBuiltIn(Ridges2Kernel,args);
1780 if (new_kernel == (KernelInfo *) NULL)
1781 return(kernel);
1782 LastKernelInfo(kernel)->next = new_kernel;
1783 break;
1784 }
anthony602ab9b2010-01-05 08:06:50 +00001785 /* Distance Measuring Kernels */
1786 case ChebyshevKernel:
1787 {
anthony602ab9b2010-01-05 08:06:50 +00001788 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001789 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001790 else
cristybb503372010-05-27 20:51:26 +00001791 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1792 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001793
1794 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1795 kernel->height*sizeof(double));
1796 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001797 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001798
cristybb503372010-05-27 20:51:26 +00001799 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1800 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
cristyc99304f2010-02-01 15:26:27 +00001801 kernel->positive_range += ( kernel->values[i] =
cristyecd0ab52010-05-30 14:59:20 +00001802 args->sigma*((labs((long) u)>labs((long) v)) ? labs((long) u) : labs((long) v)) );
cristyc99304f2010-02-01 15:26:27 +00001803 kernel->maximum = kernel->values[0];
anthony602ab9b2010-01-05 08:06:50 +00001804 break;
1805 }
anthonybee715c2010-06-04 01:25:57 +00001806 case ManhattanKernel:
anthony602ab9b2010-01-05 08:06:50 +00001807 {
anthony602ab9b2010-01-05 08:06:50 +00001808 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001809 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001810 else
cristybb503372010-05-27 20:51:26 +00001811 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1812 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001813
1814 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1815 kernel->height*sizeof(double));
1816 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001817 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001818
cristybb503372010-05-27 20:51:26 +00001819 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1820 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
cristyc99304f2010-02-01 15:26:27 +00001821 kernel->positive_range += ( kernel->values[i] =
cristyecd0ab52010-05-30 14:59:20 +00001822 args->sigma*(labs((long) u)+labs((long) v)) );
cristyc99304f2010-02-01 15:26:27 +00001823 kernel->maximum = kernel->values[0];
anthony602ab9b2010-01-05 08:06:50 +00001824 break;
1825 }
1826 case EuclideanKernel:
1827 {
anthony602ab9b2010-01-05 08:06:50 +00001828 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001829 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001830 else
cristybb503372010-05-27 20:51:26 +00001831 kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1832 kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001833
1834 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1835 kernel->height*sizeof(double));
1836 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001837 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001838
cristybb503372010-05-27 20:51:26 +00001839 for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1840 for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
cristyc99304f2010-02-01 15:26:27 +00001841 kernel->positive_range += ( kernel->values[i] =
anthonyc84dce52010-05-07 05:42:23 +00001842 args->sigma*sqrt((double)(u*u+v*v)) );
cristyc99304f2010-02-01 15:26:27 +00001843 kernel->maximum = kernel->values[0];
anthony602ab9b2010-01-05 08:06:50 +00001844 break;
1845 }
anthony46a369d2010-05-19 02:41:48 +00001846 case UnityKernel:
anthony602ab9b2010-01-05 08:06:50 +00001847 default:
anthonyc1061722010-05-14 06:23:49 +00001848 {
anthony46a369d2010-05-19 02:41:48 +00001849 /* Unity or No-Op Kernel - 3x3 with 1 in center */
1850 kernel=ParseKernelArray("3:0,0,0,0,1,0,0,0,0");
anthonyc1061722010-05-14 06:23:49 +00001851 if (kernel == (KernelInfo *) NULL)
1852 return(kernel);
anthony46a369d2010-05-19 02:41:48 +00001853 kernel->type = ( type == UnityKernel ) ? UnityKernel : UndefinedKernel;
anthonyc1061722010-05-14 06:23:49 +00001854 break;
1855 }
anthony602ab9b2010-01-05 08:06:50 +00001856 break;
1857 }
1858
1859 return(kernel);
1860}
anthonyc94cdb02010-01-06 08:15:29 +00001861
anthony602ab9b2010-01-05 08:06:50 +00001862/*
1863%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1864% %
1865% %
1866% %
cristy6771f1e2010-03-05 19:43:39 +00001867% C l o n e K e r n e l I n f o %
anthony4fd27e22010-02-07 08:17:18 +00001868% %
1869% %
1870% %
1871%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1872%
anthony1b2bc0a2010-05-12 05:25:22 +00001873% CloneKernelInfo() creates a new clone of the given Kernel List so that its
1874% can be modified without effecting the original. The cloned kernel should
cristybb503372010-05-27 20:51:26 +00001875% be destroyed using DestoryKernelInfo() when no ssize_ter needed.
anthony7a01dcf2010-05-11 12:25:52 +00001876%
cristye6365592010-04-02 17:31:23 +00001877% The format of the CloneKernelInfo method is:
anthony4fd27e22010-02-07 08:17:18 +00001878%
anthony930be612010-02-08 04:26:15 +00001879% KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
anthony4fd27e22010-02-07 08:17:18 +00001880%
1881% A description of each parameter follows:
1882%
1883% o kernel: the Morphology/Convolution kernel to be cloned
1884%
1885*/
cristyef656912010-03-05 19:54:59 +00001886MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
anthony4fd27e22010-02-07 08:17:18 +00001887{
cristybb503372010-05-27 20:51:26 +00001888 register ssize_t
anthony4fd27e22010-02-07 08:17:18 +00001889 i;
1890
cristy19eb6412010-04-23 14:42:29 +00001891 KernelInfo
anthony7a01dcf2010-05-11 12:25:52 +00001892 *new_kernel;
anthony4fd27e22010-02-07 08:17:18 +00001893
1894 assert(kernel != (KernelInfo *) NULL);
anthony7a01dcf2010-05-11 12:25:52 +00001895 new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
1896 if (new_kernel == (KernelInfo *) NULL)
1897 return(new_kernel);
1898 *new_kernel=(*kernel); /* copy values in structure */
anthony7a01dcf2010-05-11 12:25:52 +00001899
1900 /* replace the values with a copy of the values */
1901 new_kernel->values=(double *) AcquireQuantumMemory(kernel->width,
cristy19eb6412010-04-23 14:42:29 +00001902 kernel->height*sizeof(double));
anthony7a01dcf2010-05-11 12:25:52 +00001903 if (new_kernel->values == (double *) NULL)
1904 return(DestroyKernelInfo(new_kernel));
cristybb503372010-05-27 20:51:26 +00001905 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
anthony7a01dcf2010-05-11 12:25:52 +00001906 new_kernel->values[i]=kernel->values[i];
anthony1b2bc0a2010-05-12 05:25:22 +00001907
1908 /* Also clone the next kernel in the kernel list */
1909 if ( kernel->next != (KernelInfo *) NULL ) {
1910 new_kernel->next = CloneKernelInfo(kernel->next);
1911 if ( new_kernel->next == (KernelInfo *) NULL )
1912 return(DestroyKernelInfo(new_kernel));
1913 }
1914
anthony7a01dcf2010-05-11 12:25:52 +00001915 return(new_kernel);
anthony4fd27e22010-02-07 08:17:18 +00001916}
1917
1918/*
1919%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1920% %
1921% %
1922% %
anthony83ba99b2010-01-24 08:48:15 +00001923% D e s t r o y K e r n e l I n f o %
anthony602ab9b2010-01-05 08:06:50 +00001924% %
1925% %
1926% %
1927%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1928%
anthony83ba99b2010-01-24 08:48:15 +00001929% DestroyKernelInfo() frees the memory used by a Convolution/Morphology
1930% kernel.
anthony602ab9b2010-01-05 08:06:50 +00001931%
anthony83ba99b2010-01-24 08:48:15 +00001932% The format of the DestroyKernelInfo method is:
anthony602ab9b2010-01-05 08:06:50 +00001933%
anthony83ba99b2010-01-24 08:48:15 +00001934% KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
anthony602ab9b2010-01-05 08:06:50 +00001935%
1936% A description of each parameter follows:
1937%
1938% o kernel: the Morphology/Convolution kernel to be destroyed
1939%
1940*/
anthony83ba99b2010-01-24 08:48:15 +00001941MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
anthony602ab9b2010-01-05 08:06:50 +00001942{
cristy2be15382010-01-21 02:38:03 +00001943 assert(kernel != (KernelInfo *) NULL);
anthony4fd27e22010-02-07 08:17:18 +00001944
anthony7a01dcf2010-05-11 12:25:52 +00001945 if ( kernel->next != (KernelInfo *) NULL )
1946 kernel->next = DestroyKernelInfo(kernel->next);
1947
1948 kernel->values = (double *)RelinquishMagickMemory(kernel->values);
1949 kernel = (KernelInfo *) RelinquishMagickMemory(kernel);
anthony602ab9b2010-01-05 08:06:50 +00001950 return(kernel);
1951}
anthonyc94cdb02010-01-06 08:15:29 +00001952
1953/*
1954%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1955% %
1956% %
1957% %
anthonybfb635a2010-06-04 00:18:04 +00001958% E x p a n d M i r r o r K e r n e l I n f o %
anthony3c10fc82010-05-13 02:40:51 +00001959% %
1960% %
1961% %
1962%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1963%
anthonybfb635a2010-06-04 00:18:04 +00001964% ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
1965% sequence of 90-degree rotated kernels but providing a reflected 180
1966% rotatation, before the -/+ 90-degree rotations.
1967%
1968% This special rotation order produces a better, more symetrical thinning of
1969% objects.
1970%
1971% The format of the ExpandMirrorKernelInfo method is:
1972%
1973% void ExpandMirrorKernelInfo(KernelInfo *kernel)
1974%
1975% A description of each parameter follows:
1976%
1977% o kernel: the Morphology/Convolution kernel
1978%
1979% This function is only internel to this module, as it is not finalized,
1980% especially with regard to non-orthogonal angles, and rotation of larger
1981% 2D kernels.
1982*/
1983
1984#if 0
1985static void FlopKernelInfo(KernelInfo *kernel)
1986 { /* Do a Flop by reversing each row. */
1987 size_t
1988 y;
1989 register ssize_t
1990 x,r;
1991 register double
1992 *k,t;
1993
1994 for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
1995 for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
1996 t=k[x], k[x]=k[r], k[r]=t;
1997
1998 kernel->x = kernel->width - kernel->x - 1;
1999 angle = fmod(angle+180.0, 360.0);
2000 }
2001#endif
2002
2003static void ExpandMirrorKernelInfo(KernelInfo *kernel)
2004{
2005 KernelInfo
2006 *clone,
2007 *last;
2008
2009 last = kernel;
2010
2011 clone = CloneKernelInfo(last);
2012 RotateKernelInfo(clone, 180); /* flip */
2013 LastKernelInfo(last)->next = clone;
2014 last = clone;
2015
2016 clone = CloneKernelInfo(last);
2017 RotateKernelInfo(clone, 90); /* transpose */
2018 LastKernelInfo(last)->next = clone;
2019 last = clone;
2020
2021 clone = CloneKernelInfo(last);
2022 RotateKernelInfo(clone, 180); /* flop */
2023 LastKernelInfo(last)->next = clone;
2024
2025 return;
2026}
2027
2028/*
2029%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2030% %
2031% %
2032% %
2033% E x p a n d R o t a t e K e r n e l I n f o %
2034% %
2035% %
2036% %
2037%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2038%
2039% ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
2040% incrementally by the angle given, until the first kernel repeats.
anthony3c10fc82010-05-13 02:40:51 +00002041%
2042% WARNING: 45 degree rotations only works for 3x3 kernels.
2043% While 90 degree roatations only works for linear and square kernels
2044%
anthonybfb635a2010-06-04 00:18:04 +00002045% The format of the ExpandRotateKernelInfo method is:
anthony3c10fc82010-05-13 02:40:51 +00002046%
anthonybfb635a2010-06-04 00:18:04 +00002047% void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
anthony3c10fc82010-05-13 02:40:51 +00002048%
2049% A description of each parameter follows:
2050%
2051% o kernel: the Morphology/Convolution kernel
2052%
2053% o angle: angle to rotate in degrees
2054%
2055% This function is only internel to this module, as it is not finalized,
2056% especially with regard to non-orthogonal angles, and rotation of larger
2057% 2D kernels.
2058*/
anthony47f5d062010-05-23 07:47:50 +00002059
2060/* Internal Routine - Return true if two kernels are the same */
2061static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
2062 const KernelInfo *kernel2)
2063{
cristybb503372010-05-27 20:51:26 +00002064 register size_t
anthony47f5d062010-05-23 07:47:50 +00002065 i;
anthony1d45eb92010-05-25 11:13:23 +00002066
2067 /* check size and origin location */
2068 if ( kernel1->width != kernel2->width
2069 || kernel1->height != kernel2->height
2070 || kernel1->x != kernel2->x
2071 || kernel1->y != kernel2->y )
anthony47f5d062010-05-23 07:47:50 +00002072 return MagickFalse;
anthony1d45eb92010-05-25 11:13:23 +00002073
2074 /* check actual kernel values */
anthony47f5d062010-05-23 07:47:50 +00002075 for (i=0; i < (kernel1->width*kernel1->height); i++) {
anthony1d45eb92010-05-25 11:13:23 +00002076 /* Test for Nan equivelence */
anthony47f5d062010-05-23 07:47:50 +00002077 if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
2078 return MagickFalse;
2079 if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
2080 return MagickFalse;
anthony1d45eb92010-05-25 11:13:23 +00002081 /* Test actual values are equivelent */
anthony47f5d062010-05-23 07:47:50 +00002082 if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
2083 return MagickFalse;
2084 }
anthony1d45eb92010-05-25 11:13:23 +00002085
anthony47f5d062010-05-23 07:47:50 +00002086 return MagickTrue;
2087}
2088
anthonybfb635a2010-06-04 00:18:04 +00002089static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
anthony3c10fc82010-05-13 02:40:51 +00002090{
2091 KernelInfo
cristy84d9b552010-05-24 18:23:54 +00002092 *clone,
anthony3c10fc82010-05-13 02:40:51 +00002093 *last;
cristya9a61ad2010-05-13 12:47:41 +00002094
anthony3c10fc82010-05-13 02:40:51 +00002095 last = kernel;
anthony47f5d062010-05-23 07:47:50 +00002096 while(1) {
cristy84d9b552010-05-24 18:23:54 +00002097 clone = CloneKernelInfo(last);
2098 RotateKernelInfo(clone, angle);
2099 if ( SameKernelInfo(kernel, clone) == MagickTrue )
anthony47f5d062010-05-23 07:47:50 +00002100 break;
anthonybfb635a2010-06-04 00:18:04 +00002101 LastKernelInfo(last)->next = clone;
cristy84d9b552010-05-24 18:23:54 +00002102 last = clone;
anthony3c10fc82010-05-13 02:40:51 +00002103 }
anthonybfb635a2010-06-04 00:18:04 +00002104 clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
anthony47f5d062010-05-23 07:47:50 +00002105 return;
anthony3c10fc82010-05-13 02:40:51 +00002106}
2107
2108/*
2109%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2110% %
2111% %
2112% %
anthony46a369d2010-05-19 02:41:48 +00002113+ C a l c M e t a K e r n a l I n f o %
2114% %
2115% %
2116% %
2117%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2118%
2119% CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2120% using the kernel values. This should only ne used if it is not posible to
2121% calculate that meta-data in some easier way.
2122%
2123% It is important that the meta-data is correct before ScaleKernelInfo() is
2124% used to perform kernel normalization.
2125%
2126% The format of the CalcKernelMetaData method is:
2127%
2128% void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2129%
2130% A description of each parameter follows:
2131%
2132% o kernel: the Morphology/Convolution kernel to modify
2133%
2134% WARNING: Minimum and Maximum values are assumed to include zero, even if
2135% zero is not part of the kernel (as in Gaussian Derived kernels). This
2136% however is not true for flat-shaped morphological kernels.
2137%
2138% WARNING: Only the specific kernel pointed to is modified, not a list of
2139% multiple kernels.
2140%
2141% This is an internal function and not expected to be useful outside this
2142% module. This could change however.
2143*/
2144static void CalcKernelMetaData(KernelInfo *kernel)
2145{
cristybb503372010-05-27 20:51:26 +00002146 register size_t
anthony46a369d2010-05-19 02:41:48 +00002147 i;
2148
2149 kernel->minimum = kernel->maximum = 0.0;
2150 kernel->negative_range = kernel->positive_range = 0.0;
2151 for (i=0; i < (kernel->width*kernel->height); i++)
2152 {
2153 if ( fabs(kernel->values[i]) < MagickEpsilon )
2154 kernel->values[i] = 0.0;
2155 ( kernel->values[i] < 0)
2156 ? ( kernel->negative_range += kernel->values[i] )
2157 : ( kernel->positive_range += kernel->values[i] );
2158 Minimize(kernel->minimum, kernel->values[i]);
2159 Maximize(kernel->maximum, kernel->values[i]);
2160 }
2161
2162 return;
2163}
2164
2165/*
2166%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2167% %
2168% %
2169% %
anthony9eb4f742010-05-18 02:45:54 +00002170% M o r p h o l o g y A p p l y %
anthony602ab9b2010-01-05 08:06:50 +00002171% %
2172% %
2173% %
2174%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2175%
anthony9eb4f742010-05-18 02:45:54 +00002176% MorphologyApply() applies a morphological method, multiple times using
2177% a list of multiple kernels.
anthony602ab9b2010-01-05 08:06:50 +00002178%
anthony9eb4f742010-05-18 02:45:54 +00002179% It is basically equivelent to as MorphologyImageChannel() (see below) but
anthonye8d2f552010-06-05 10:43:25 +00002180% without any user controls. This allows internel programs to use this
2181% function, to actually perform a specific task without posible interference
2182% by any API user supplied settings.
2183%
2184% It is MorphologyImageChannel() task to extract any such user controls, and
2185% pass them to this function for processing.
anthony9eb4f742010-05-18 02:45:54 +00002186%
2187% More specifically kernels are not normalized/scaled/blended by the
anthonye8d2f552010-06-05 10:43:25 +00002188% 'convolve:scale' Image Artifact (setting), nor is the convolve bias
2189% (-bias setting or image->bias) loooked at, but must be supplied from the
2190% function arguments.
anthony602ab9b2010-01-05 08:06:50 +00002191%
anthony47f5d062010-05-23 07:47:50 +00002192% The format of the MorphologyApply method is:
anthony602ab9b2010-01-05 08:06:50 +00002193%
anthony9eb4f742010-05-18 02:45:54 +00002194% Image *MorphologyApply(const Image *image,MorphologyMethod method,
cristybb503372010-05-27 20:51:26 +00002195% const ssize_t iterations,const KernelInfo *kernel,
anthony47f5d062010-05-23 07:47:50 +00002196% const CompositeMethod compose, const double bias,
anthony9eb4f742010-05-18 02:45:54 +00002197% ExceptionInfo *exception)
anthony602ab9b2010-01-05 08:06:50 +00002198%
2199% A description of each parameter follows:
2200%
2201% o image: the image.
2202%
2203% o method: the morphology method to be applied.
2204%
2205% o iterations: apply the operation this many times (or no change).
2206% A value of -1 means loop until no change found.
2207% How this is applied may depend on the morphology method.
2208% Typically this is a value of 1.
2209%
2210% o channel: the channel type.
2211%
2212% o kernel: An array of double representing the morphology kernel.
anthony29188a82010-01-22 10:12:34 +00002213% Warning: kernel may be normalized for the Convolve method.
anthony602ab9b2010-01-05 08:06:50 +00002214%
anthony47f5d062010-05-23 07:47:50 +00002215% o compose: How to handle or merge multi-kernel results.
2216% If 'Undefined' use default of the Morphology method.
2217% If 'No' force image to be re-iterated by each kernel.
2218% Otherwise merge the results using the mathematical compose
2219% method given.
2220%
2221% o bias: Convolution Output Bias.
anthony9eb4f742010-05-18 02:45:54 +00002222%
anthony602ab9b2010-01-05 08:06:50 +00002223% o exception: return any errors or warnings in this structure.
2224%
anthony602ab9b2010-01-05 08:06:50 +00002225*/
2226
anthony930be612010-02-08 04:26:15 +00002227
anthony9eb4f742010-05-18 02:45:54 +00002228/* Apply a Morphology Primative to an image using the given kernel.
2229** Two pre-created images must be provided, no image is created.
2230** Returning the number of pixels that changed.
2231*/
cristybb503372010-05-27 20:51:26 +00002232static size_t MorphologyPrimitive(const Image *image, Image
anthony602ab9b2010-01-05 08:06:50 +00002233 *result_image, const MorphologyMethod method, const ChannelType channel,
anthony9eb4f742010-05-18 02:45:54 +00002234 const KernelInfo *kernel,const double bias,ExceptionInfo *exception)
anthony602ab9b2010-01-05 08:06:50 +00002235{
cristy2be15382010-01-21 02:38:03 +00002236#define MorphologyTag "Morphology/Image"
anthony602ab9b2010-01-05 08:06:50 +00002237
cristy5f959472010-05-27 22:19:46 +00002238 CacheView
2239 *p_view,
2240 *q_view;
2241
cristybb503372010-05-27 20:51:26 +00002242 ssize_t
anthony29188a82010-01-22 10:12:34 +00002243 y, offx, offy,
anthony602ab9b2010-01-05 08:06:50 +00002244 changed;
2245
2246 MagickBooleanType
2247 status;
2248
cristy5f959472010-05-27 22:19:46 +00002249 MagickOffsetType
2250 progress;
anthony602ab9b2010-01-05 08:06:50 +00002251
anthonye4d89962010-05-29 10:53:11 +00002252 assert(image != (Image *) NULL);
2253 assert(image->signature == MagickSignature);
2254 assert(result_image != (Image *) NULL);
2255 assert(result_image->signature == MagickSignature);
2256 assert(kernel != (KernelInfo *) NULL);
2257 assert(kernel->signature == MagickSignature);
2258 assert(exception != (ExceptionInfo *) NULL);
2259 assert(exception->signature == MagickSignature);
2260
anthony602ab9b2010-01-05 08:06:50 +00002261 status=MagickTrue;
2262 changed=0;
2263 progress=0;
2264
anthony602ab9b2010-01-05 08:06:50 +00002265 p_view=AcquireCacheView(image);
2266 q_view=AcquireCacheView(result_image);
anthony29188a82010-01-22 10:12:34 +00002267
anthonycc6c8362010-01-25 04:14:01 +00002268 /* Some methods (including convolve) needs use a reflected kernel.
anthony9eb4f742010-05-18 02:45:54 +00002269 * Adjust 'origin' offsets to loop though kernel as a reflection.
anthony29188a82010-01-22 10:12:34 +00002270 */
cristyc99304f2010-02-01 15:26:27 +00002271 offx = kernel->x;
2272 offy = kernel->y;
anthony29188a82010-01-22 10:12:34 +00002273 switch(method) {
anthony930be612010-02-08 04:26:15 +00002274 case ConvolveMorphology:
2275 case DilateMorphology:
2276 case DilateIntensityMorphology:
2277 case DistanceMorphology:
anthony5ef8e942010-05-11 06:51:12 +00002278 /* kernel needs to used with reflection about origin */
cristybb503372010-05-27 20:51:26 +00002279 offx = (ssize_t) kernel->width-offx-1;
2280 offy = (ssize_t) kernel->height-offy-1;
anthony29188a82010-01-22 10:12:34 +00002281 break;
anthony5ef8e942010-05-11 06:51:12 +00002282 case ErodeMorphology:
2283 case ErodeIntensityMorphology:
2284 case HitAndMissMorphology:
2285 case ThinningMorphology:
2286 case ThickenMorphology:
2287 /* kernel is user as is, without reflection */
2288 break;
anthony930be612010-02-08 04:26:15 +00002289 default:
anthony9eb4f742010-05-18 02:45:54 +00002290 assert("Not a Primitive Morphology Method" != (char *) NULL);
anthony930be612010-02-08 04:26:15 +00002291 break;
anthony29188a82010-01-22 10:12:34 +00002292 }
2293
anthony602ab9b2010-01-05 08:06:50 +00002294#if defined(MAGICKCORE_OPENMP_SUPPORT)
2295 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2296#endif
cristybb503372010-05-27 20:51:26 +00002297 for (y=0; y < (ssize_t) image->rows; y++)
anthony602ab9b2010-01-05 08:06:50 +00002298 {
2299 MagickBooleanType
2300 sync;
2301
2302 register const PixelPacket
2303 *restrict p;
2304
2305 register const IndexPacket
2306 *restrict p_indexes;
2307
2308 register PixelPacket
2309 *restrict q;
2310
2311 register IndexPacket
2312 *restrict q_indexes;
2313
cristybb503372010-05-27 20:51:26 +00002314 register ssize_t
anthony602ab9b2010-01-05 08:06:50 +00002315 x;
2316
cristybb503372010-05-27 20:51:26 +00002317 size_t
anthony602ab9b2010-01-05 08:06:50 +00002318 r;
2319
2320 if (status == MagickFalse)
2321 continue;
anthony29188a82010-01-22 10:12:34 +00002322 p=GetCacheViewVirtualPixels(p_view, -offx, y-offy,
2323 image->columns+kernel->width, kernel->height, exception);
anthony602ab9b2010-01-05 08:06:50 +00002324 q=GetCacheViewAuthenticPixels(q_view,0,y,result_image->columns,1,
2325 exception);
2326 if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
2327 {
2328 status=MagickFalse;
2329 continue;
2330 }
2331 p_indexes=GetCacheViewVirtualIndexQueue(p_view);
2332 q_indexes=GetCacheViewAuthenticIndexQueue(q_view);
anthony29188a82010-01-22 10:12:34 +00002333 r = (image->columns+kernel->width)*offy+offx; /* constant */
2334
cristybb503372010-05-27 20:51:26 +00002335 for (x=0; x < (ssize_t) image->columns; x++)
anthony602ab9b2010-01-05 08:06:50 +00002336 {
cristybb503372010-05-27 20:51:26 +00002337 ssize_t
anthony602ab9b2010-01-05 08:06:50 +00002338 v;
2339
cristybb503372010-05-27 20:51:26 +00002340 register ssize_t
anthony602ab9b2010-01-05 08:06:50 +00002341 u;
2342
2343 register const double
2344 *restrict k;
2345
2346 register const PixelPacket
2347 *restrict k_pixels;
2348
2349 register const IndexPacket
2350 *restrict k_indexes;
2351
2352 MagickPixelPacket
anthony5ef8e942010-05-11 06:51:12 +00002353 result,
2354 min,
2355 max;
anthony602ab9b2010-01-05 08:06:50 +00002356
anthony29188a82010-01-22 10:12:34 +00002357 /* Copy input to ouput image for unused channels
anthony83ba99b2010-01-24 08:48:15 +00002358 * This removes need for 'cloning' a new image every iteration
anthony29188a82010-01-22 10:12:34 +00002359 */
anthony602ab9b2010-01-05 08:06:50 +00002360 *q = p[r];
2361 if (image->colorspace == CMYKColorspace)
2362 q_indexes[x] = p_indexes[r];
2363
anthony5ef8e942010-05-11 06:51:12 +00002364 /* Defaults */
2365 min.red =
2366 min.green =
2367 min.blue =
2368 min.opacity =
2369 min.index = (MagickRealType) QuantumRange;
2370 max.red =
2371 max.green =
2372 max.blue =
2373 max.opacity =
2374 max.index = (MagickRealType) 0;
anthony9eb4f742010-05-18 02:45:54 +00002375 /* default result is the original pixel value */
anthony5ef8e942010-05-11 06:51:12 +00002376 result.red = (MagickRealType) p[r].red;
2377 result.green = (MagickRealType) p[r].green;
2378 result.blue = (MagickRealType) p[r].blue;
2379 result.opacity = QuantumRange - (MagickRealType) p[r].opacity;
cristye96405a2010-05-19 02:24:31 +00002380 result.index = 0.0;
anthony5ef8e942010-05-11 06:51:12 +00002381 if ( image->colorspace == CMYKColorspace)
2382 result.index = (MagickRealType) p_indexes[r];
2383
anthony602ab9b2010-01-05 08:06:50 +00002384 switch (method) {
2385 case ConvolveMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002386 /* Set the user defined bias of the weighted average output */
2387 result.red =
2388 result.green =
2389 result.blue =
2390 result.opacity =
2391 result.index = bias;
anthony930be612010-02-08 04:26:15 +00002392 break;
anthony4fd27e22010-02-07 08:17:18 +00002393 case DilateIntensityMorphology:
2394 case ErodeIntensityMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002395 /* use a boolean flag indicating when first match found */
2396 result.red = 0.0; /* result is not used otherwise */
anthony4fd27e22010-02-07 08:17:18 +00002397 break;
anthony602ab9b2010-01-05 08:06:50 +00002398 default:
anthony602ab9b2010-01-05 08:06:50 +00002399 break;
2400 }
2401
2402 switch ( method ) {
2403 case ConvolveMorphology:
anthony930be612010-02-08 04:26:15 +00002404 /* Weighted Average of pixels using reflected kernel
2405 **
2406 ** NOTE for correct working of this operation for asymetrical
2407 ** kernels, the kernel needs to be applied in its reflected form.
2408 ** That is its values needs to be reversed.
2409 **
2410 ** Correlation is actually the same as this but without reflecting
2411 ** the kernel, and thus 'lower-level' that Convolution. However
2412 ** as Convolution is the more common method used, and it does not
2413 ** really cost us much in terms of processing to use a reflected
anthony5ef8e942010-05-11 06:51:12 +00002414 ** kernel, so it is Convolution that is implemented.
anthony930be612010-02-08 04:26:15 +00002415 **
2416 ** Correlation will have its kernel reflected before calling
2417 ** this function to do a Convolve.
2418 **
2419 ** For more details of Correlation vs Convolution see
2420 ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
2421 */
anthony5ef8e942010-05-11 06:51:12 +00002422 if (((channel & SyncChannels) != 0 ) &&
2423 (image->matte == MagickTrue))
2424 { /* Channel has a 'Sync' Flag, and Alpha Channel enabled.
2425 ** Weight the color channels with Alpha Channel so that
2426 ** transparent pixels are not part of the results.
2427 */
anthony602ab9b2010-01-05 08:06:50 +00002428 MagickRealType
anthony5ef8e942010-05-11 06:51:12 +00002429 alpha, /* color channel weighting : kernel*alpha */
2430 gamma; /* divisor, sum of weighting values */
anthony602ab9b2010-01-05 08:06:50 +00002431
2432 gamma=0.0;
anthony29188a82010-01-22 10:12:34 +00002433 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002434 k_pixels = p;
2435 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002436 for (v=0; v < (ssize_t) kernel->height; v++) {
2437 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
anthony602ab9b2010-01-05 08:06:50 +00002438 if ( IsNan(*k) ) continue;
2439 alpha=(*k)*(QuantumScale*(QuantumRange-
2440 k_pixels[u].opacity));
2441 gamma += alpha;
2442 result.red += alpha*k_pixels[u].red;
2443 result.green += alpha*k_pixels[u].green;
2444 result.blue += alpha*k_pixels[u].blue;
anthony83ba99b2010-01-24 08:48:15 +00002445 result.opacity += (*k)*(QuantumRange-k_pixels[u].opacity);
anthony602ab9b2010-01-05 08:06:50 +00002446 if ( image->colorspace == CMYKColorspace)
2447 result.index += alpha*k_indexes[u];
2448 }
2449 k_pixels += image->columns+kernel->width;
2450 k_indexes += image->columns+kernel->width;
2451 }
2452 gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
anthony83ba99b2010-01-24 08:48:15 +00002453 result.red *= gamma;
2454 result.green *= gamma;
2455 result.blue *= gamma;
2456 result.opacity *= gamma;
2457 result.index *= gamma;
anthony602ab9b2010-01-05 08:06:50 +00002458 }
anthony5ef8e942010-05-11 06:51:12 +00002459 else
2460 {
2461 /* No 'Sync' flag, or no Alpha involved.
2462 ** Convolution is simple individual channel weigthed sum.
2463 */
2464 k = &kernel->values[ kernel->width*kernel->height-1 ];
2465 k_pixels = p;
2466 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002467 for (v=0; v < (ssize_t) kernel->height; v++) {
2468 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
anthony5ef8e942010-05-11 06:51:12 +00002469 if ( IsNan(*k) ) continue;
2470 result.red += (*k)*k_pixels[u].red;
2471 result.green += (*k)*k_pixels[u].green;
2472 result.blue += (*k)*k_pixels[u].blue;
2473 result.opacity += (*k)*(QuantumRange-k_pixels[u].opacity);
2474 if ( image->colorspace == CMYKColorspace)
2475 result.index += (*k)*k_indexes[u];
2476 }
2477 k_pixels += image->columns+kernel->width;
2478 k_indexes += image->columns+kernel->width;
2479 }
2480 }
anthony602ab9b2010-01-05 08:06:50 +00002481 break;
2482
anthony4fd27e22010-02-07 08:17:18 +00002483 case ErodeMorphology:
anthony5ef8e942010-05-11 06:51:12 +00002484 /* Minimum Value within kernel neighbourhood
anthony930be612010-02-08 04:26:15 +00002485 **
2486 ** NOTE that the kernel is not reflected for this operation!
2487 **
2488 ** NOTE: in normal Greyscale Morphology, the kernel value should
2489 ** be added to the real value, this is currently not done, due to
2490 ** the nature of the boolean kernels being used.
2491 */
anthony4fd27e22010-02-07 08:17:18 +00002492 k = kernel->values;
2493 k_pixels = p;
2494 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002495 for (v=0; v < (ssize_t) kernel->height; v++) {
2496 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
anthony4fd27e22010-02-07 08:17:18 +00002497 if ( IsNan(*k) || (*k) < 0.5 ) continue;
anthony5ef8e942010-05-11 06:51:12 +00002498 Minimize(min.red, (double) k_pixels[u].red);
2499 Minimize(min.green, (double) k_pixels[u].green);
2500 Minimize(min.blue, (double) k_pixels[u].blue);
2501 Minimize(min.opacity,
anthonyd37a5cb2010-05-07 06:37:03 +00002502 QuantumRange-(double) k_pixels[u].opacity);
anthony4fd27e22010-02-07 08:17:18 +00002503 if ( image->colorspace == CMYKColorspace)
anthony5ef8e942010-05-11 06:51:12 +00002504 Minimize(min.index, (double) k_indexes[u]);
anthony4fd27e22010-02-07 08:17:18 +00002505 }
2506 k_pixels += image->columns+kernel->width;
2507 k_indexes += image->columns+kernel->width;
2508 }
2509 break;
2510
anthony5ef8e942010-05-11 06:51:12 +00002511
anthony83ba99b2010-01-24 08:48:15 +00002512 case DilateMorphology:
anthony5ef8e942010-05-11 06:51:12 +00002513 /* Maximum Value within kernel neighbourhood
anthony930be612010-02-08 04:26:15 +00002514 **
2515 ** NOTE for correct working of this operation for asymetrical
2516 ** kernels, the kernel needs to be applied in its reflected form.
2517 ** That is its values needs to be reversed.
2518 **
2519 ** NOTE: in normal Greyscale Morphology, the kernel value should
2520 ** be added to the real value, this is currently not done, due to
2521 ** the nature of the boolean kernels being used.
2522 **
2523 */
anthony29188a82010-01-22 10:12:34 +00002524 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002525 k_pixels = p;
2526 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002527 for (v=0; v < (ssize_t) kernel->height; v++) {
2528 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
anthony602ab9b2010-01-05 08:06:50 +00002529 if ( IsNan(*k) || (*k) < 0.5 ) continue;
anthony5ef8e942010-05-11 06:51:12 +00002530 Maximize(max.red, (double) k_pixels[u].red);
2531 Maximize(max.green, (double) k_pixels[u].green);
2532 Maximize(max.blue, (double) k_pixels[u].blue);
2533 Maximize(max.opacity,
anthonyd37a5cb2010-05-07 06:37:03 +00002534 QuantumRange-(double) k_pixels[u].opacity);
anthony602ab9b2010-01-05 08:06:50 +00002535 if ( image->colorspace == CMYKColorspace)
anthony5ef8e942010-05-11 06:51:12 +00002536 Maximize(max.index, (double) k_indexes[u]);
anthony602ab9b2010-01-05 08:06:50 +00002537 }
2538 k_pixels += image->columns+kernel->width;
2539 k_indexes += image->columns+kernel->width;
2540 }
anthony602ab9b2010-01-05 08:06:50 +00002541 break;
2542
anthony5ef8e942010-05-11 06:51:12 +00002543 case HitAndMissMorphology:
2544 case ThinningMorphology:
2545 case ThickenMorphology:
2546 /* Minimum of Foreground Pixel minus Maxumum of Background Pixels
2547 **
2548 ** NOTE that the kernel is not reflected for this operation,
2549 ** and consists of both foreground and background pixel
2550 ** neighbourhoods, 0.0 for background, and 1.0 for foreground
2551 ** with either Nan or 0.5 values for don't care.
2552 **
anthony4c827ef2010-06-05 23:56:10 +00002553 ** Note that this will never produce a meaningless negative
2554 ** result. Such results can cause Thinning/Thicken to not work
2555 ** correctly when used against a greyscale image.
anthony5ef8e942010-05-11 06:51:12 +00002556 */
2557 k = kernel->values;
2558 k_pixels = p;
2559 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002560 for (v=0; v < (ssize_t) kernel->height; v++) {
2561 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
anthony5ef8e942010-05-11 06:51:12 +00002562 if ( IsNan(*k) ) continue;
2563 if ( (*k) > 0.7 )
2564 { /* minimim of foreground pixels */
2565 Minimize(min.red, (double) k_pixels[u].red);
2566 Minimize(min.green, (double) k_pixels[u].green);
2567 Minimize(min.blue, (double) k_pixels[u].blue);
2568 Minimize(min.opacity,
2569 QuantumRange-(double) k_pixels[u].opacity);
2570 if ( image->colorspace == CMYKColorspace)
2571 Minimize(min.index, (double) k_indexes[u]);
2572 }
2573 else if ( (*k) < 0.3 )
2574 { /* maximum of background pixels */
2575 Maximize(max.red, (double) k_pixels[u].red);
2576 Maximize(max.green, (double) k_pixels[u].green);
2577 Maximize(max.blue, (double) k_pixels[u].blue);
2578 Maximize(max.opacity,
2579 QuantumRange-(double) k_pixels[u].opacity);
2580 if ( image->colorspace == CMYKColorspace)
2581 Maximize(max.index, (double) k_indexes[u]);
2582 }
2583 }
2584 k_pixels += image->columns+kernel->width;
2585 k_indexes += image->columns+kernel->width;
2586 }
anthony4c827ef2010-06-05 23:56:10 +00002587 /* Pattern Match if difference is positive */
anthony5ef8e942010-05-11 06:51:12 +00002588 min.red -= max.red; Maximize( min.red, 0.0 );
2589 min.green -= max.green; Maximize( min.green, 0.0 );
2590 min.blue -= max.blue; Maximize( min.blue, 0.0 );
2591 min.opacity -= max.opacity; Maximize( min.opacity, 0.0 );
2592 min.index -= max.index; Maximize( min.index, 0.0 );
2593 break;
2594
anthony4fd27e22010-02-07 08:17:18 +00002595 case ErodeIntensityMorphology:
anthony930be612010-02-08 04:26:15 +00002596 /* Select Pixel with Minimum Intensity within kernel neighbourhood
2597 **
2598 ** WARNING: the intensity test fails for CMYK and does not
2599 ** take into account the moderating effect of teh alpha channel
2600 ** on the intensity.
2601 **
2602 ** NOTE that the kernel is not reflected for this operation!
2603 */
anthony602ab9b2010-01-05 08:06:50 +00002604 k = kernel->values;
2605 k_pixels = p;
2606 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002607 for (v=0; v < (ssize_t) kernel->height; v++) {
2608 for (u=0; u < (ssize_t) kernel->width; u++, k++) {
anthony602ab9b2010-01-05 08:06:50 +00002609 if ( IsNan(*k) || (*k) < 0.5 ) continue;
anthony4fd27e22010-02-07 08:17:18 +00002610 if ( result.red == 0.0 ||
2611 PixelIntensity(&(k_pixels[u])) < PixelIntensity(q) ) {
2612 /* copy the whole pixel - no channel selection */
2613 *q = k_pixels[u];
2614 if ( result.red > 0.0 ) changed++;
2615 result.red = 1.0;
2616 }
anthony602ab9b2010-01-05 08:06:50 +00002617 }
2618 k_pixels += image->columns+kernel->width;
2619 k_indexes += image->columns+kernel->width;
2620 }
anthony602ab9b2010-01-05 08:06:50 +00002621 break;
2622
anthony83ba99b2010-01-24 08:48:15 +00002623 case DilateIntensityMorphology:
anthony930be612010-02-08 04:26:15 +00002624 /* Select Pixel with Maximum Intensity within kernel neighbourhood
2625 **
2626 ** WARNING: the intensity test fails for CMYK and does not
anthony9eb4f742010-05-18 02:45:54 +00002627 ** take into account the moderating effect of the alpha channel
2628 ** on the intensity (yet).
anthony930be612010-02-08 04:26:15 +00002629 **
2630 ** NOTE for correct working of this operation for asymetrical
2631 ** kernels, the kernel needs to be applied in its reflected form.
2632 ** That is its values needs to be reversed.
2633 */
anthony29188a82010-01-22 10:12:34 +00002634 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002635 k_pixels = p;
2636 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002637 for (v=0; v < (ssize_t) kernel->height; v++) {
2638 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
anthony29188a82010-01-22 10:12:34 +00002639 if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */
2640 if ( result.red == 0.0 ||
2641 PixelIntensity(&(k_pixels[u])) > PixelIntensity(q) ) {
2642 /* copy the whole pixel - no channel selection */
2643 *q = k_pixels[u];
2644 if ( result.red > 0.0 ) changed++;
2645 result.red = 1.0;
2646 }
anthony602ab9b2010-01-05 08:06:50 +00002647 }
2648 k_pixels += image->columns+kernel->width;
2649 k_indexes += image->columns+kernel->width;
2650 }
anthony602ab9b2010-01-05 08:06:50 +00002651 break;
2652
anthony5ef8e942010-05-11 06:51:12 +00002653
anthony602ab9b2010-01-05 08:06:50 +00002654 case DistanceMorphology:
anthony930be612010-02-08 04:26:15 +00002655 /* Add kernel Value and select the minimum value found.
2656 ** The result is a iterative distance from edge of image shape.
2657 **
2658 ** All Distance Kernels are symetrical, but that may not always
2659 ** be the case. For example how about a distance from left edges?
2660 ** To work correctly with asymetrical kernels the reflected kernel
2661 ** needs to be applied.
anthony5ef8e942010-05-11 06:51:12 +00002662 **
2663 ** Actually this is really a GreyErode with a negative kernel!
2664 **
anthony930be612010-02-08 04:26:15 +00002665 */
anthony29188a82010-01-22 10:12:34 +00002666 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002667 k_pixels = p;
2668 k_indexes = p_indexes;
cristybb503372010-05-27 20:51:26 +00002669 for (v=0; v < (ssize_t) kernel->height; v++) {
2670 for (u=0; u < (ssize_t) kernel->width; u++, k--) {
anthony602ab9b2010-01-05 08:06:50 +00002671 if ( IsNan(*k) ) continue;
2672 Minimize(result.red, (*k)+k_pixels[u].red);
2673 Minimize(result.green, (*k)+k_pixels[u].green);
2674 Minimize(result.blue, (*k)+k_pixels[u].blue);
2675 Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity);
2676 if ( image->colorspace == CMYKColorspace)
2677 Minimize(result.index, (*k)+k_indexes[u]);
2678 }
2679 k_pixels += image->columns+kernel->width;
2680 k_indexes += image->columns+kernel->width;
2681 }
anthony602ab9b2010-01-05 08:06:50 +00002682 break;
2683
2684 case UndefinedMorphology:
2685 default:
2686 break; /* Do nothing */
anthony83ba99b2010-01-24 08:48:15 +00002687 }
anthony5ef8e942010-05-11 06:51:12 +00002688 /* Final mathematics of results (combine with original image?)
2689 **
2690 ** NOTE: Difference Morphology operators Edge* and *Hat could also
2691 ** be done here but works better with iteration as a image difference
2692 ** in the controling function (below). Thicken and Thinning however
2693 ** should be done here so thay can be iterated correctly.
2694 */
2695 switch ( method ) {
2696 case HitAndMissMorphology:
2697 case ErodeMorphology:
2698 result = min; /* minimum of neighbourhood */
2699 break;
2700 case DilateMorphology:
2701 result = max; /* maximum of neighbourhood */
2702 break;
2703 case ThinningMorphology:
2704 /* subtract pattern match from original */
2705 result.red -= min.red;
2706 result.green -= min.green;
2707 result.blue -= min.blue;
2708 result.opacity -= min.opacity;
2709 result.index -= min.index;
2710 break;
2711 case ThickenMorphology:
anthony4c827ef2010-06-05 23:56:10 +00002712 /* Add the pattern matchs to the original */
2713 result.red += min.red;
2714 result.green += min.green;
2715 result.blue += min.blue;
2716 result.opacity += min.opacity;
2717 result.index += min.index;
anthony5ef8e942010-05-11 06:51:12 +00002718 break;
2719 default:
2720 /* result directly calculated or assigned */
2721 break;
2722 }
2723 /* Assign the resulting pixel values - Clamping Result */
anthony83ba99b2010-01-24 08:48:15 +00002724 switch ( method ) {
2725 case UndefinedMorphology:
2726 case DilateIntensityMorphology:
2727 case ErodeIntensityMorphology:
anthony930be612010-02-08 04:26:15 +00002728 break; /* full pixel was directly assigned - not a channel method */
anthony83ba99b2010-01-24 08:48:15 +00002729 default:
anthony83ba99b2010-01-24 08:48:15 +00002730 if ((channel & RedChannel) != 0)
2731 q->red = ClampToQuantum(result.red);
2732 if ((channel & GreenChannel) != 0)
2733 q->green = ClampToQuantum(result.green);
2734 if ((channel & BlueChannel) != 0)
2735 q->blue = ClampToQuantum(result.blue);
2736 if ((channel & OpacityChannel) != 0
2737 && image->matte == MagickTrue )
2738 q->opacity = ClampToQuantum(QuantumRange-result.opacity);
2739 if ((channel & IndexChannel) != 0
2740 && image->colorspace == CMYKColorspace)
2741 q_indexes[x] = ClampToQuantum(result.index);
2742 break;
2743 }
anthony5ef8e942010-05-11 06:51:12 +00002744 /* Count up changed pixels */
anthony83ba99b2010-01-24 08:48:15 +00002745 if ( ( p[r].red != q->red )
2746 || ( p[r].green != q->green )
2747 || ( p[r].blue != q->blue )
2748 || ( p[r].opacity != q->opacity )
2749 || ( image->colorspace == CMYKColorspace &&
2750 p_indexes[r] != q_indexes[x] ) )
2751 changed++; /* The pixel had some value changed! */
anthony602ab9b2010-01-05 08:06:50 +00002752 p++;
2753 q++;
anthony83ba99b2010-01-24 08:48:15 +00002754 } /* x */
anthony602ab9b2010-01-05 08:06:50 +00002755 sync=SyncCacheViewAuthenticPixels(q_view,exception);
2756 if (sync == MagickFalse)
2757 status=MagickFalse;
2758 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2759 {
2760 MagickBooleanType
2761 proceed;
2762
2763#if defined(MAGICKCORE_OPENMP_SUPPORT)
2764 #pragma omp critical (MagickCore_MorphologyImage)
2765#endif
2766 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
2767 if (proceed == MagickFalse)
2768 status=MagickFalse;
2769 }
anthony83ba99b2010-01-24 08:48:15 +00002770 } /* y */
anthony602ab9b2010-01-05 08:06:50 +00002771 result_image->type=image->type;
2772 q_view=DestroyCacheView(q_view);
2773 p_view=DestroyCacheView(p_view);
cristybb503372010-05-27 20:51:26 +00002774 return(status ? (size_t) changed : 0);
anthony602ab9b2010-01-05 08:06:50 +00002775}
2776
anthony4fd27e22010-02-07 08:17:18 +00002777
anthony9eb4f742010-05-18 02:45:54 +00002778MagickExport Image *MorphologyApply(const Image *image, const ChannelType
cristybb503372010-05-27 20:51:26 +00002779 channel,const MorphologyMethod method, const ssize_t iterations,
anthony47f5d062010-05-23 07:47:50 +00002780 const KernelInfo *kernel, const CompositeOperator compose,
2781 const double bias, ExceptionInfo *exception)
cristy2be15382010-01-21 02:38:03 +00002782{
2783 Image
anthony47f5d062010-05-23 07:47:50 +00002784 *curr_image, /* Image we are working with or iterating */
2785 *work_image, /* secondary image for primative iteration */
2786 *save_image, /* saved image - for 'edge' method only */
2787 *rslt_image; /* resultant image - after multi-kernel handling */
anthony602ab9b2010-01-05 08:06:50 +00002788
anthony4fd27e22010-02-07 08:17:18 +00002789 KernelInfo
anthony47f5d062010-05-23 07:47:50 +00002790 *reflected_kernel, /* A reflected copy of the kernel (if needed) */
2791 *norm_kernel, /* the current normal un-reflected kernel */
2792 *rflt_kernel, /* the current reflected kernel (if needed) */
2793 *this_kernel; /* the kernel being applied */
anthony4fd27e22010-02-07 08:17:18 +00002794
2795 MorphologyMethod
anthony47f5d062010-05-23 07:47:50 +00002796 primative; /* the current morphology primative being applied */
anthony9eb4f742010-05-18 02:45:54 +00002797
2798 CompositeOperator
anthony47f5d062010-05-23 07:47:50 +00002799 rslt_compose; /* multi-kernel compose method for results to use */
2800
2801 MagickBooleanType
2802 verbose; /* verbose output of results */
anthony4fd27e22010-02-07 08:17:18 +00002803
cristybb503372010-05-27 20:51:26 +00002804 size_t
anthony47f5d062010-05-23 07:47:50 +00002805 method_loop, /* Loop 1: number of compound method iterations */
2806 method_limit, /* maximum number of compound method iterations */
2807 kernel_number, /* Loop 2: the kernel number being applied */
2808 stage_loop, /* Loop 3: primative loop for compound morphology */
2809 stage_limit, /* how many primatives in this compound */
2810 kernel_loop, /* Loop 4: iterate the kernel (basic morphology) */
2811 kernel_limit, /* number of times to iterate kernel */
2812 count, /* total count of primative steps applied */
2813 changed, /* number pixels changed by last primative operation */
2814 kernel_changed, /* total count of changed using iterated kernel */
2815 method_changed; /* total count of changed over method iteration */
2816
2817 char
2818 v_info[80];
anthony1b2bc0a2010-05-12 05:25:22 +00002819
anthony602ab9b2010-01-05 08:06:50 +00002820 assert(image != (Image *) NULL);
2821 assert(image->signature == MagickSignature);
anthony4fd27e22010-02-07 08:17:18 +00002822 assert(kernel != (KernelInfo *) NULL);
2823 assert(kernel->signature == MagickSignature);
anthony602ab9b2010-01-05 08:06:50 +00002824 assert(exception != (ExceptionInfo *) NULL);
2825 assert(exception->signature == MagickSignature);
2826
anthonyc3e48252010-05-24 12:43:11 +00002827 count = 0; /* number of low-level morphology primatives performed */
anthony602ab9b2010-01-05 08:06:50 +00002828 if ( iterations == 0 )
anthony47f5d062010-05-23 07:47:50 +00002829 return((Image *)NULL); /* null operation - nothing to do! */
anthony602ab9b2010-01-05 08:06:50 +00002830
cristybb503372010-05-27 20:51:26 +00002831 kernel_limit = (size_t) iterations;
anthony47f5d062010-05-23 07:47:50 +00002832 if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
2833 kernel_limit = image->columns > image->rows ? image->columns : image->rows;
anthony602ab9b2010-01-05 08:06:50 +00002834
cristye96405a2010-05-19 02:24:31 +00002835 verbose = ( GetImageArtifact(image,"verbose") != (const char *) NULL ) ?
2836 MagickTrue : MagickFalse;
anthony4f1dcb72010-05-14 08:43:10 +00002837
anthony9eb4f742010-05-18 02:45:54 +00002838 /* initialise for cleanup */
anthony47f5d062010-05-23 07:47:50 +00002839 curr_image = (Image *) image;
2840 work_image = save_image = rslt_image = (Image *) NULL;
2841 reflected_kernel = (KernelInfo *) NULL;
anthony4fd27e22010-02-07 08:17:18 +00002842
anthony47f5d062010-05-23 07:47:50 +00002843 /* Initialize specific methods
2844 * + which loop should use the given iteratations
2845 * + how many primatives make up the compound morphology
2846 * + multi-kernel compose method to use (by default)
2847 */
2848 method_limit = 1; /* just do method once, unless otherwise set */
2849 stage_limit = 1; /* assume method is not a compount */
2850 rslt_compose = compose; /* and we are composing multi-kernels as given */
anthony9eb4f742010-05-18 02:45:54 +00002851 switch( method ) {
anthony47f5d062010-05-23 07:47:50 +00002852 case SmoothMorphology: /* 4 primative compound morphology */
2853 stage_limit = 4;
anthony9eb4f742010-05-18 02:45:54 +00002854 break;
anthony47f5d062010-05-23 07:47:50 +00002855 case OpenMorphology: /* 2 primative compound morphology */
anthony9eb4f742010-05-18 02:45:54 +00002856 case OpenIntensityMorphology:
anthony47f5d062010-05-23 07:47:50 +00002857 case TopHatMorphology:
2858 case CloseMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002859 case CloseIntensityMorphology:
anthony47f5d062010-05-23 07:47:50 +00002860 case BottomHatMorphology:
2861 case EdgeMorphology:
2862 stage_limit = 2;
anthony9eb4f742010-05-18 02:45:54 +00002863 break;
2864 case HitAndMissMorphology:
anthonyc3e48252010-05-24 12:43:11 +00002865 kernel_limit = 1; /* no method or kernel iteration */
anthony47f5d062010-05-23 07:47:50 +00002866 rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
anthony9eb4f742010-05-18 02:45:54 +00002867 break;
anthonyc3e48252010-05-24 12:43:11 +00002868 case ThinningMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002869 case ThickenMorphology:
anthonyc3e48252010-05-24 12:43:11 +00002870 method_limit = kernel_limit; /* iterate method with each kernel */
2871 kernel_limit = 1; /* do not do kernel iteration */
anthonye4d89962010-05-29 10:53:11 +00002872 case DistanceMorphology:
anthonyc3e48252010-05-24 12:43:11 +00002873 rslt_compose = NoCompositeOp; /* Re-iterate with multiple kernels */
anthony47f5d062010-05-23 07:47:50 +00002874 break;
2875 default:
anthony930be612010-02-08 04:26:15 +00002876 break;
anthony602ab9b2010-01-05 08:06:50 +00002877 }
2878
anthonyc3e48252010-05-24 12:43:11 +00002879 /* Handle user (caller) specified multi-kernel composition method */
anthony47f5d062010-05-23 07:47:50 +00002880 if ( compose != UndefinedCompositeOp )
2881 rslt_compose = compose; /* override default composition for method */
2882 if ( rslt_compose == UndefinedCompositeOp )
2883 rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
2884
anthonyc3e48252010-05-24 12:43:11 +00002885 /* Some methods require a reflected kernel to use with primatives.
2886 * Create the reflected kernel for those methods. */
anthony47f5d062010-05-23 07:47:50 +00002887 switch ( method ) {
2888 case CorrelateMorphology:
2889 case CloseMorphology:
2890 case CloseIntensityMorphology:
2891 case BottomHatMorphology:
2892 case SmoothMorphology:
2893 reflected_kernel = CloneKernelInfo(kernel);
2894 if (reflected_kernel == (KernelInfo *) NULL)
2895 goto error_cleanup;
2896 RotateKernelInfo(reflected_kernel,180);
2897 break;
2898 default:
2899 break;
anthony9eb4f742010-05-18 02:45:54 +00002900 }
anthony7a01dcf2010-05-11 12:25:52 +00002901
anthony47f5d062010-05-23 07:47:50 +00002902 /* Loop 1: iterate the compound method */
2903 method_loop = 0;
2904 method_changed = 1;
2905 while ( method_loop < method_limit && method_changed > 0 ) {
2906 method_loop++;
2907 method_changed = 0;
anthony9eb4f742010-05-18 02:45:54 +00002908
anthony47f5d062010-05-23 07:47:50 +00002909 /* Loop 2: iterate over each kernel in a multi-kernel list */
2910 norm_kernel = (KernelInfo *) kernel;
cristyf2faecf2010-05-28 19:19:36 +00002911 this_kernel = (KernelInfo *) kernel;
anthony47f5d062010-05-23 07:47:50 +00002912 rflt_kernel = reflected_kernel;
anthonye4d89962010-05-29 10:53:11 +00002913
anthony47f5d062010-05-23 07:47:50 +00002914 kernel_number = 0;
2915 while ( norm_kernel != NULL ) {
anthony9eb4f742010-05-18 02:45:54 +00002916
anthony47f5d062010-05-23 07:47:50 +00002917 /* Loop 3: Compound Morphology Staging - Select Primative to apply */
2918 stage_loop = 0; /* the compound morphology stage number */
2919 while ( stage_loop < stage_limit ) {
2920 stage_loop++; /* The stage of the compound morphology */
anthony9eb4f742010-05-18 02:45:54 +00002921
anthony47f5d062010-05-23 07:47:50 +00002922 /* Select primative morphology for this stage of compound method */
2923 this_kernel = norm_kernel; /* default use unreflected kernel */
anthonybd0f5562010-05-24 13:05:02 +00002924 primative = method; /* Assume method is a primative */
anthony47f5d062010-05-23 07:47:50 +00002925 switch( method ) {
2926 case ErodeMorphology: /* just erode */
2927 case EdgeInMorphology: /* erode and image difference */
2928 primative = ErodeMorphology;
2929 break;
2930 case DilateMorphology: /* just dilate */
2931 case EdgeOutMorphology: /* dilate and image difference */
2932 primative = DilateMorphology;
2933 break;
2934 case OpenMorphology: /* erode then dialate */
2935 case TopHatMorphology: /* open and image difference */
2936 primative = ErodeMorphology;
2937 if ( stage_loop == 2 )
2938 primative = DilateMorphology;
2939 break;
2940 case OpenIntensityMorphology:
2941 primative = ErodeIntensityMorphology;
2942 if ( stage_loop == 2 )
2943 primative = DilateIntensityMorphology;
anthonye4d89962010-05-29 10:53:11 +00002944 break;
anthony47f5d062010-05-23 07:47:50 +00002945 case CloseMorphology: /* dilate, then erode */
2946 case BottomHatMorphology: /* close and image difference */
2947 this_kernel = rflt_kernel; /* use the reflected kernel */
2948 primative = DilateMorphology;
2949 if ( stage_loop == 2 )
2950 primative = ErodeMorphology;
2951 break;
2952 case CloseIntensityMorphology:
2953 this_kernel = rflt_kernel; /* use the reflected kernel */
2954 primative = DilateIntensityMorphology;
2955 if ( stage_loop == 2 )
2956 primative = ErodeIntensityMorphology;
2957 break;
2958 case SmoothMorphology: /* open, close */
2959 switch ( stage_loop ) {
2960 case 1: /* start an open method, which starts with Erode */
2961 primative = ErodeMorphology;
2962 break;
2963 case 2: /* now Dilate the Erode */
2964 primative = DilateMorphology;
2965 break;
2966 case 3: /* Reflect kernel a close */
2967 this_kernel = rflt_kernel; /* use the reflected kernel */
2968 primative = DilateMorphology;
2969 break;
2970 case 4: /* Finish the Close */
2971 this_kernel = rflt_kernel; /* use the reflected kernel */
2972 primative = ErodeMorphology;
2973 break;
2974 }
2975 break;
2976 case EdgeMorphology: /* dilate and erode difference */
2977 primative = DilateMorphology;
2978 if ( stage_loop == 2 ) {
2979 save_image = curr_image; /* save the image difference */
2980 curr_image = (Image *) image;
2981 primative = ErodeMorphology;
2982 }
2983 break;
2984 case CorrelateMorphology:
2985 /* A Correlation is a Convolution with a reflected kernel.
2986 ** However a Convolution is a weighted sum using a reflected
2987 ** kernel. It may seem stange to convert a Correlation into a
2988 ** Convolution as the Correlation is the simplier method, but
2989 ** Convolution is much more commonly used, and it makes sense to
2990 ** implement it directly so as to avoid the need to duplicate the
2991 ** kernel when it is not required (which is typically the
2992 ** default).
2993 */
2994 this_kernel = rflt_kernel; /* use the reflected kernel */
2995 primative = ConvolveMorphology;
2996 break;
2997 default:
anthony47f5d062010-05-23 07:47:50 +00002998 break;
2999 }
anthonye4d89962010-05-29 10:53:11 +00003000 assert( this_kernel != (KernelInfo *) NULL );
anthony9eb4f742010-05-18 02:45:54 +00003001
anthony47f5d062010-05-23 07:47:50 +00003002 /* Extra information for debugging compound operations */
3003 if ( verbose == MagickTrue ) {
3004 if ( stage_limit > 1 )
cristye8c25f92010-06-03 00:53:06 +00003005 (void) FormatMagickString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ",
3006 MagickOptionToMnemonic(MagickMorphologyOptions,method),(double)
3007 method_loop,(double) stage_loop);
anthony47f5d062010-05-23 07:47:50 +00003008 else if ( primative != method )
cristye8c25f92010-06-03 00:53:06 +00003009 (void) FormatMagickString(v_info, MaxTextExtent, "%s:%.20g -> ",
3010 MagickOptionToMnemonic(MagickMorphologyOptions, method),(double)
3011 method_loop);
anthony47f5d062010-05-23 07:47:50 +00003012 else
3013 v_info[0] = '\0';
3014 }
3015
3016 /* Loop 4: Iterate the kernel with primative */
3017 kernel_loop = 0;
3018 kernel_changed = 0;
3019 changed = 1;
3020 while ( kernel_loop < kernel_limit && changed > 0 ) {
3021 kernel_loop++; /* the iteration of this kernel */
anthony9eb4f742010-05-18 02:45:54 +00003022
3023 /* Create a destination image, if not yet defined */
3024 if ( work_image == (Image *) NULL )
3025 {
3026 work_image=CloneImage(image,0,0,MagickTrue,exception);
3027 if (work_image == (Image *) NULL)
3028 goto error_cleanup;
3029 if (SetImageStorageClass(work_image,DirectClass) == MagickFalse)
3030 {
3031 InheritException(exception,&work_image->exception);
3032 goto error_cleanup;
3033 }
3034 }
3035
anthony501c2f92010-06-02 10:55:14 +00003036 /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
anthony9eb4f742010-05-18 02:45:54 +00003037 count++;
anthony47f5d062010-05-23 07:47:50 +00003038 changed = MorphologyPrimitive(curr_image, work_image, primative,
anthony9eb4f742010-05-18 02:45:54 +00003039 channel, this_kernel, bias, exception);
anthony47f5d062010-05-23 07:47:50 +00003040 kernel_changed += changed;
3041 method_changed += changed;
anthony9eb4f742010-05-18 02:45:54 +00003042
anthony47f5d062010-05-23 07:47:50 +00003043 if ( verbose == MagickTrue ) {
3044 if ( kernel_loop > 1 )
3045 fprintf(stderr, "\n"); /* add end-of-line from previous */
cristye8c25f92010-06-03 00:53:06 +00003046 (void) fprintf(stderr, "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
3047 v_info,MagickOptionToMnemonic(MagickMorphologyOptions,
3048 primative),(this_kernel == rflt_kernel ) ? "*" : "",
3049 (double) (method_loop+kernel_loop-1),(double) kernel_number,
3050 (double) count,(double) changed);
anthony47f5d062010-05-23 07:47:50 +00003051 }
anthony9eb4f742010-05-18 02:45:54 +00003052 /* prepare next loop */
3053 { Image *tmp = work_image; /* swap images for iteration */
3054 work_image = curr_image;
3055 curr_image = tmp;
3056 }
3057 if ( work_image == image )
anthony47f5d062010-05-23 07:47:50 +00003058 work_image = (Image *) NULL; /* replace input 'image' */
anthony7a01dcf2010-05-11 12:25:52 +00003059
anthony47f5d062010-05-23 07:47:50 +00003060 } /* End Loop 4: Iterate the kernel with primative */
anthony1b2bc0a2010-05-12 05:25:22 +00003061
anthony47f5d062010-05-23 07:47:50 +00003062 if ( verbose == MagickTrue && kernel_changed != changed )
cristye8c25f92010-06-03 00:53:06 +00003063 fprintf(stderr, " Total %.20g",(double) kernel_changed);
anthony47f5d062010-05-23 07:47:50 +00003064 if ( verbose == MagickTrue && stage_loop < stage_limit )
3065 fprintf(stderr, "\n"); /* add end-of-line before looping */
anthony9eb4f742010-05-18 02:45:54 +00003066
3067#if 0
anthonye4d89962010-05-29 10:53:11 +00003068 fprintf(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
3069 fprintf(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
3070 fprintf(stderr, " work =0x%lx\n", (unsigned long)work_image);
3071 fprintf(stderr, " save =0x%lx\n", (unsigned long)save_image);
3072 fprintf(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
anthony9eb4f742010-05-18 02:45:54 +00003073#endif
3074
anthony47f5d062010-05-23 07:47:50 +00003075 } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
anthony9eb4f742010-05-18 02:45:54 +00003076
anthony47f5d062010-05-23 07:47:50 +00003077 /* Final Post-processing for some Compound Methods
3078 **
3079 ** The removal of any 'Sync' channel flag in the Image Compositon
3080 ** below ensures the methematical compose method is applied in a
3081 ** purely mathematical way, and only to the selected channels.
3082 ** Turn off SVG composition 'alpha blending'.
3083 */
3084 switch( method ) {
3085 case EdgeOutMorphology:
3086 case EdgeInMorphology:
3087 case TopHatMorphology:
3088 case BottomHatMorphology:
3089 if ( verbose == MagickTrue )
3090 fprintf(stderr, "\n%s: Difference with original image",
3091 MagickOptionToMnemonic(MagickMorphologyOptions, method) );
3092 (void) CompositeImageChannel(curr_image,
3093 (ChannelType) (channel & ~SyncChannels),
3094 DifferenceCompositeOp, image, 0, 0);
3095 break;
3096 case EdgeMorphology:
3097 if ( verbose == MagickTrue )
3098 fprintf(stderr, "\n%s: Difference of Dilate and Erode",
3099 MagickOptionToMnemonic(MagickMorphologyOptions, method) );
3100 (void) CompositeImageChannel(curr_image,
3101 (ChannelType) (channel & ~SyncChannels),
3102 DifferenceCompositeOp, save_image, 0, 0);
3103 save_image = DestroyImage(save_image); /* finished with save image */
3104 break;
3105 default:
3106 break;
3107 }
3108
3109 /* multi-kernel handling: re-iterate, or compose results */
3110 if ( kernel->next == (KernelInfo *) NULL )
anthonyc3e48252010-05-24 12:43:11 +00003111 rslt_image = curr_image; /* just return the resulting image */
anthony47f5d062010-05-23 07:47:50 +00003112 else if ( rslt_compose == NoCompositeOp )
anthonyc3e48252010-05-24 12:43:11 +00003113 { if ( verbose == MagickTrue ) {
3114 if ( this_kernel->next != (KernelInfo *) NULL )
3115 fprintf(stderr, " (re-iterate)");
3116 else
3117 fprintf(stderr, " (done)");
3118 }
3119 rslt_image = curr_image; /* return result, and re-iterate */
anthony9eb4f742010-05-18 02:45:54 +00003120 }
anthony47f5d062010-05-23 07:47:50 +00003121 else if ( rslt_image == (Image *) NULL)
3122 { if ( verbose == MagickTrue )
3123 fprintf(stderr, " (save for compose)");
3124 rslt_image = curr_image;
3125 curr_image = (Image *) image; /* continue with original image */
anthony9eb4f742010-05-18 02:45:54 +00003126 }
anthony47f5d062010-05-23 07:47:50 +00003127 else
3128 { /* add the new 'current' result to the composition
3129 **
3130 ** The removal of any 'Sync' channel flag in the Image Compositon
3131 ** below ensures the methematical compose method is applied in a
3132 ** purely mathematical way, and only to the selected channels.
3133 ** Turn off SVG composition 'alpha blending'.
3134 */
3135 if ( verbose == MagickTrue )
3136 fprintf(stderr, " (compose \"%s\")",
3137 MagickOptionToMnemonic(MagickComposeOptions, rslt_compose) );
3138 (void) CompositeImageChannel(rslt_image,
3139 (ChannelType) (channel & ~SyncChannels), rslt_compose,
3140 curr_image, 0, 0);
3141 curr_image = (Image *) image; /* continue with original image */
3142 }
3143 if ( verbose == MagickTrue )
3144 fprintf(stderr, "\n");
anthony9eb4f742010-05-18 02:45:54 +00003145
anthony47f5d062010-05-23 07:47:50 +00003146 /* loop to the next kernel in a multi-kernel list */
3147 norm_kernel = norm_kernel->next;
3148 if ( rflt_kernel != (KernelInfo *) NULL )
3149 rflt_kernel = rflt_kernel->next;
3150 kernel_number++;
3151 } /* End Loop 2: Loop over each kernel */
anthony9eb4f742010-05-18 02:45:54 +00003152
anthony47f5d062010-05-23 07:47:50 +00003153 } /* End Loop 1: compound method interation */
anthony602ab9b2010-01-05 08:06:50 +00003154
anthony9eb4f742010-05-18 02:45:54 +00003155 goto exit_cleanup;
anthony1b2bc0a2010-05-12 05:25:22 +00003156
anthony47f5d062010-05-23 07:47:50 +00003157 /* Yes goto's are bad, but it makes cleanup lot more efficient */
anthony1b2bc0a2010-05-12 05:25:22 +00003158error_cleanup:
anthony47f5d062010-05-23 07:47:50 +00003159 if ( curr_image != (Image *) NULL &&
3160 curr_image != rslt_image &&
3161 curr_image != image )
3162 curr_image = DestroyImage(curr_image);
3163 if ( rslt_image != (Image *) NULL )
3164 rslt_image = DestroyImage(rslt_image);
anthony1b2bc0a2010-05-12 05:25:22 +00003165exit_cleanup:
anthony47f5d062010-05-23 07:47:50 +00003166 if ( curr_image != (Image *) NULL &&
3167 curr_image != rslt_image &&
3168 curr_image != image )
3169 curr_image = DestroyImage(curr_image);
anthony9eb4f742010-05-18 02:45:54 +00003170 if ( work_image != (Image *) NULL )
anthony47f5d062010-05-23 07:47:50 +00003171 work_image = DestroyImage(work_image);
anthony9eb4f742010-05-18 02:45:54 +00003172 if ( save_image != (Image *) NULL )
anthony47f5d062010-05-23 07:47:50 +00003173 save_image = DestroyImage(save_image);
3174 if ( reflected_kernel != (KernelInfo *) NULL )
3175 reflected_kernel = DestroyKernelInfo(reflected_kernel);
3176 return(rslt_image);
anthony9eb4f742010-05-18 02:45:54 +00003177}
3178
3179/*
3180%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3181% %
3182% %
3183% %
3184% M o r p h o l o g y I m a g e C h a n n e l %
3185% %
3186% %
3187% %
3188%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3189%
3190% MorphologyImageChannel() applies a user supplied kernel to the image
3191% according to the given mophology method.
3192%
3193% This function applies any and all user defined settings before calling
3194% the above internal function MorphologyApply().
3195%
3196% User defined settings include...
anthony46a369d2010-05-19 02:41:48 +00003197% * Output Bias for Convolution and correlation ("-bias")
3198% * Kernel Scale/normalize settings ("-set 'option:convolve:scale'")
3199% This can also includes the addition of a scaled unity kernel.
3200% * Show Kernel being applied ("-set option:showkernel 1")
anthony9eb4f742010-05-18 02:45:54 +00003201%
3202% The format of the MorphologyImage method is:
3203%
3204% Image *MorphologyImage(const Image *image,MorphologyMethod method,
cristybb503372010-05-27 20:51:26 +00003205% const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
anthony9eb4f742010-05-18 02:45:54 +00003206%
3207% Image *MorphologyImageChannel(const Image *image, const ChannelType
cristybb503372010-05-27 20:51:26 +00003208% channel,MorphologyMethod method,const ssize_t iterations,
anthony9eb4f742010-05-18 02:45:54 +00003209% KernelInfo *kernel,ExceptionInfo *exception)
3210%
3211% A description of each parameter follows:
3212%
3213% o image: the image.
3214%
3215% o method: the morphology method to be applied.
3216%
3217% o iterations: apply the operation this many times (or no change).
3218% A value of -1 means loop until no change found.
3219% How this is applied may depend on the morphology method.
3220% Typically this is a value of 1.
3221%
3222% o channel: the channel type.
3223%
3224% o kernel: An array of double representing the morphology kernel.
3225% Warning: kernel may be normalized for the Convolve method.
3226%
3227% o exception: return any errors or warnings in this structure.
3228%
3229*/
3230
3231MagickExport Image *MorphologyImageChannel(const Image *image,
3232 const ChannelType channel,const MorphologyMethod method,
cristybb503372010-05-27 20:51:26 +00003233 const ssize_t iterations,const KernelInfo *kernel,ExceptionInfo *exception)
anthony9eb4f742010-05-18 02:45:54 +00003234{
3235 const char
3236 *artifact;
3237
3238 KernelInfo
3239 *curr_kernel;
3240
anthony47f5d062010-05-23 07:47:50 +00003241 CompositeOperator
3242 compose;
3243
anthony9eb4f742010-05-18 02:45:54 +00003244 Image
3245 *morphology_image;
3246
3247
anthony46a369d2010-05-19 02:41:48 +00003248 /* Apply Convolve/Correlate Normalization and Scaling Factors.
3249 * This is done BEFORE the ShowKernelInfo() function is called so that
3250 * users can see the results of the 'option:convolve:scale' option.
anthony9eb4f742010-05-18 02:45:54 +00003251 */
3252 curr_kernel = (KernelInfo *) kernel;
anthonyf71ca292010-05-19 04:08:43 +00003253 if ( method == ConvolveMorphology || method == CorrelateMorphology )
anthony9eb4f742010-05-18 02:45:54 +00003254 {
3255 artifact = GetImageArtifact(image,"convolve:scale");
anthonye8d2f552010-06-05 10:43:25 +00003256 if ( artifact != (const char *)NULL ) {
anthony9eb4f742010-05-18 02:45:54 +00003257 if ( curr_kernel == kernel )
3258 curr_kernel = CloneKernelInfo(kernel);
3259 if (curr_kernel == (KernelInfo *) NULL) {
3260 curr_kernel=DestroyKernelInfo(curr_kernel);
3261 return((Image *) NULL);
3262 }
anthony46a369d2010-05-19 02:41:48 +00003263 ScaleGeometryKernelInfo(curr_kernel, artifact);
anthony9eb4f742010-05-18 02:45:54 +00003264 }
3265 }
3266
3267 /* display the (normalized) kernel via stderr */
3268 artifact = GetImageArtifact(image,"showkernel");
anthony47f5d062010-05-23 07:47:50 +00003269 if ( artifact == (const char *) NULL)
3270 artifact = GetImageArtifact(image,"convolve:showkernel");
3271 if ( artifact == (const char *) NULL)
3272 artifact = GetImageArtifact(image,"morphology:showkernel");
anthony9eb4f742010-05-18 02:45:54 +00003273 if ( artifact != (const char *) NULL)
3274 ShowKernelInfo(curr_kernel);
3275
anthony47f5d062010-05-23 07:47:50 +00003276 /* override the default handling of multi-kernel morphology results
3277 * if 'Undefined' use the default method
3278 * if 'None' (default for 'Convolve') re-iterate previous result
3279 * otherwise merge resulting images using compose method given
3280 */
3281 compose = UndefinedCompositeOp; /* use default for method */
3282 artifact = GetImageArtifact(image,"morphology:compose");
3283 if ( artifact != (const char *) NULL)
3284 compose = (CompositeOperator) ParseMagickOption(
3285 MagickComposeOptions,MagickFalse,artifact);
3286
anthony9eb4f742010-05-18 02:45:54 +00003287 /* Apply the Morphology */
3288 morphology_image = MorphologyApply(image, channel, method, iterations,
anthony47f5d062010-05-23 07:47:50 +00003289 curr_kernel, compose, image->bias, exception);
anthony9eb4f742010-05-18 02:45:54 +00003290
3291 /* Cleanup and Exit */
3292 if ( curr_kernel != kernel )
anthony1b2bc0a2010-05-12 05:25:22 +00003293 curr_kernel=DestroyKernelInfo(curr_kernel);
anthony9eb4f742010-05-18 02:45:54 +00003294 return(morphology_image);
3295}
3296
3297MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod
cristybb503372010-05-27 20:51:26 +00003298 method, const ssize_t iterations,const KernelInfo *kernel, ExceptionInfo
anthony9eb4f742010-05-18 02:45:54 +00003299 *exception)
3300{
3301 Image
3302 *morphology_image;
3303
3304 morphology_image=MorphologyImageChannel(image,DefaultChannels,method,
3305 iterations,kernel,exception);
3306 return(morphology_image);
anthony602ab9b2010-01-05 08:06:50 +00003307}
anthony83ba99b2010-01-24 08:48:15 +00003308
3309/*
3310%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3311% %
3312% %
3313% %
anthony4fd27e22010-02-07 08:17:18 +00003314+ R o t a t e K e r n e l I n f o %
anthony83ba99b2010-01-24 08:48:15 +00003315% %
3316% %
3317% %
3318%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3319%
anthony46a369d2010-05-19 02:41:48 +00003320% RotateKernelInfo() rotates the kernel by the angle given.
3321%
3322% Currently it is restricted to 90 degree angles, of either 1D kernels
3323% or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
3324% It will ignore usless rotations for specific 'named' built-in kernels.
anthony83ba99b2010-01-24 08:48:15 +00003325%
anthony4fd27e22010-02-07 08:17:18 +00003326% The format of the RotateKernelInfo method is:
anthony83ba99b2010-01-24 08:48:15 +00003327%
anthony4fd27e22010-02-07 08:17:18 +00003328% void RotateKernelInfo(KernelInfo *kernel, double angle)
anthony83ba99b2010-01-24 08:48:15 +00003329%
3330% A description of each parameter follows:
3331%
3332% o kernel: the Morphology/Convolution kernel
3333%
3334% o angle: angle to rotate in degrees
3335%
anthony46a369d2010-05-19 02:41:48 +00003336% This function is currently internal to this module only, but can be exported
3337% to other modules if needed.
anthony83ba99b2010-01-24 08:48:15 +00003338*/
anthony4fd27e22010-02-07 08:17:18 +00003339static void RotateKernelInfo(KernelInfo *kernel, double angle)
anthony83ba99b2010-01-24 08:48:15 +00003340{
anthony1b2bc0a2010-05-12 05:25:22 +00003341 /* angle the lower kernels first */
3342 if ( kernel->next != (KernelInfo *) NULL)
3343 RotateKernelInfo(kernel->next, angle);
3344
anthony83ba99b2010-01-24 08:48:15 +00003345 /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
3346 **
3347 ** TODO: expand beyond simple 90 degree rotates, flips and flops
3348 */
3349
3350 /* Modulus the angle */
3351 angle = fmod(angle, 360.0);
3352 if ( angle < 0 )
3353 angle += 360.0;
3354
anthony3c10fc82010-05-13 02:40:51 +00003355 if ( 337.5 < angle || angle <= 22.5 )
anthony43c49252010-05-18 10:59:50 +00003356 return; /* Near zero angle - no change! - At least not at this time */
anthony83ba99b2010-01-24 08:48:15 +00003357
anthony3dd0f622010-05-13 12:57:32 +00003358 /* Handle special cases */
anthony83ba99b2010-01-24 08:48:15 +00003359 switch (kernel->type) {
3360 /* These built-in kernels are cylindrical kernels, rotating is useless */
3361 case GaussianKernel:
anthony501c2f92010-06-02 10:55:14 +00003362 case DoGKernel:
3363 case LoGKernel:
anthony83ba99b2010-01-24 08:48:15 +00003364 case DiskKernel:
anthony3dd0f622010-05-13 12:57:32 +00003365 case PeaksKernel:
3366 case LaplacianKernel:
anthony83ba99b2010-01-24 08:48:15 +00003367 case ChebyshevKernel:
anthonybee715c2010-06-04 01:25:57 +00003368 case ManhattanKernel:
anthony83ba99b2010-01-24 08:48:15 +00003369 case EuclideanKernel:
3370 return;
3371
3372 /* These may be rotatable at non-90 angles in the future */
3373 /* but simply rotating them in multiples of 90 degrees is useless */
3374 case SquareKernel:
3375 case DiamondKernel:
3376 case PlusKernel:
anthony3dd0f622010-05-13 12:57:32 +00003377 case CrossKernel:
anthony83ba99b2010-01-24 08:48:15 +00003378 return;
3379
3380 /* These only allows a +/-90 degree rotation (by transpose) */
3381 /* A 180 degree rotation is useless */
3382 case BlurKernel:
3383 case RectangleKernel:
3384 if ( 135.0 < angle && angle <= 225.0 )
3385 return;
3386 if ( 225.0 < angle && angle <= 315.0 )
3387 angle -= 180;
3388 break;
3389
anthony3dd0f622010-05-13 12:57:32 +00003390 default:
anthony83ba99b2010-01-24 08:48:15 +00003391 break;
3392 }
anthony3c10fc82010-05-13 02:40:51 +00003393 /* Attempt rotations by 45 degrees */
3394 if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
3395 {
3396 if ( kernel->width == 3 && kernel->height == 3 )
3397 { /* Rotate a 3x3 square by 45 degree angle */
3398 MagickRealType t = kernel->values[0];
anthony43c49252010-05-18 10:59:50 +00003399 kernel->values[0] = kernel->values[3];
3400 kernel->values[3] = kernel->values[6];
3401 kernel->values[6] = kernel->values[7];
3402 kernel->values[7] = kernel->values[8];
3403 kernel->values[8] = kernel->values[5];
3404 kernel->values[5] = kernel->values[2];
3405 kernel->values[2] = kernel->values[1];
3406 kernel->values[1] = t;
anthony1d45eb92010-05-25 11:13:23 +00003407 /* rotate non-centered origin */
3408 if ( kernel->x != 1 || kernel->y != 1 ) {
cristybb503372010-05-27 20:51:26 +00003409 ssize_t x,y;
3410 x = (ssize_t) kernel->x-1;
3411 y = (ssize_t) kernel->y-1;
anthony1d45eb92010-05-25 11:13:23 +00003412 if ( x == y ) x = 0;
3413 else if ( x == 0 ) x = -y;
3414 else if ( x == -y ) y = 0;
3415 else if ( y == 0 ) y = x;
cristyecd0ab52010-05-30 14:59:20 +00003416 kernel->x = (ssize_t) x+1;
3417 kernel->y = (ssize_t) y+1;
anthony1d45eb92010-05-25 11:13:23 +00003418 }
anthony43c49252010-05-18 10:59:50 +00003419 angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */
3420 kernel->angle = fmod(kernel->angle+45.0, 360.0);
anthony3c10fc82010-05-13 02:40:51 +00003421 }
3422 else
3423 perror("Unable to rotate non-3x3 kernel by 45 degrees");
3424 }
3425 if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 )
3426 {
3427 if ( kernel->width == 1 || kernel->height == 1 )
anthonybfb635a2010-06-04 00:18:04 +00003428 { /* Do a transpose of a 1 dimentional kernel,
3429 ** which results in a fast 90 degree rotation of some type.
anthony3c10fc82010-05-13 02:40:51 +00003430 */
cristybb503372010-05-27 20:51:26 +00003431 ssize_t
anthony3c10fc82010-05-13 02:40:51 +00003432 t;
cristybb503372010-05-27 20:51:26 +00003433 t = (ssize_t) kernel->width;
anthony3c10fc82010-05-13 02:40:51 +00003434 kernel->width = kernel->height;
cristybb503372010-05-27 20:51:26 +00003435 kernel->height = (size_t) t;
anthony3c10fc82010-05-13 02:40:51 +00003436 t = kernel->x;
3437 kernel->x = kernel->y;
3438 kernel->y = t;
anthony43c49252010-05-18 10:59:50 +00003439 if ( kernel->width == 1 ) {
3440 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
3441 kernel->angle = fmod(kernel->angle+90.0, 360.0);
3442 } else {
3443 angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */
3444 kernel->angle = fmod(kernel->angle+270.0, 360.0);
3445 }
anthony3c10fc82010-05-13 02:40:51 +00003446 }
3447 else if ( kernel->width == kernel->height )
3448 { /* Rotate a square array of values by 90 degrees */
cristybb503372010-05-27 20:51:26 +00003449 { register size_t
anthony1d45eb92010-05-25 11:13:23 +00003450 i,j,x,y;
3451 register MagickRealType
3452 *k,t;
3453 k=kernel->values;
3454 for( i=0, x=kernel->width-1; i<=x; i++, x--)
3455 for( j=0, y=kernel->height-1; j<y; j++, y--)
3456 { t = k[i+j*kernel->width];
3457 k[i+j*kernel->width] = k[j+x*kernel->width];
3458 k[j+x*kernel->width] = k[x+y*kernel->width];
3459 k[x+y*kernel->width] = k[y+i*kernel->width];
3460 k[y+i*kernel->width] = t;
3461 }
3462 }
3463 /* rotate the origin - relative to center of array */
cristybb503372010-05-27 20:51:26 +00003464 { register ssize_t x,y;
cristyeaedf062010-05-29 22:36:02 +00003465 x = (ssize_t) (kernel->x*2-kernel->width+1);
3466 y = (ssize_t) (kernel->y*2-kernel->height+1);
cristyecd0ab52010-05-30 14:59:20 +00003467 kernel->x = (ssize_t) ( -y +(ssize_t) kernel->width-1)/2;
3468 kernel->y = (ssize_t) ( +x +(ssize_t) kernel->height-1)/2;
anthony1d45eb92010-05-25 11:13:23 +00003469 }
anthony43c49252010-05-18 10:59:50 +00003470 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
3471 kernel->angle = fmod(kernel->angle+90.0, 360.0);
anthony3c10fc82010-05-13 02:40:51 +00003472 }
3473 else
3474 perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
3475 }
anthony83ba99b2010-01-24 08:48:15 +00003476 if ( 135.0 < angle && angle <= 225.0 )
3477 {
anthony43c49252010-05-18 10:59:50 +00003478 /* For a 180 degree rotation - also know as a reflection
3479 * This is actually a very very common operation!
3480 * Basically all that is needed is a reversal of the kernel data!
3481 * And a reflection of the origon
3482 */
cristybb503372010-05-27 20:51:26 +00003483 size_t
anthony83ba99b2010-01-24 08:48:15 +00003484 i,j;
3485 register double
3486 *k,t;
3487
3488 k=kernel->values;
3489 for ( i=0, j=kernel->width*kernel->height-1; i<j; i++, j--)
3490 t=k[i], k[i]=k[j], k[j]=t;
3491
cristybb503372010-05-27 20:51:26 +00003492 kernel->x = (ssize_t) kernel->width - kernel->x - 1;
3493 kernel->y = (ssize_t) kernel->height - kernel->y - 1;
anthony43c49252010-05-18 10:59:50 +00003494 angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */
3495 kernel->angle = fmod(kernel->angle+180.0, 360.0);
anthony83ba99b2010-01-24 08:48:15 +00003496 }
anthony3c10fc82010-05-13 02:40:51 +00003497 /* At this point angle should at least between -45 (315) and +45 degrees
anthony83ba99b2010-01-24 08:48:15 +00003498 * In the future some form of non-orthogonal angled rotates could be
3499 * performed here, posibily with a linear kernel restriction.
3500 */
3501
anthony83ba99b2010-01-24 08:48:15 +00003502 return;
3503}
3504
3505/*
3506%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3507% %
3508% %
3509% %
anthony46a369d2010-05-19 02:41:48 +00003510% S c a l e G e o m e t r y K e r n e l I n f o %
3511% %
3512% %
3513% %
3514%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3515%
3516% ScaleGeometryKernelInfo() takes a geometry argument string, typically
3517% provided as a "-set option:convolve:scale {geometry}" user setting,
3518% and modifies the kernel according to the parsed arguments of that setting.
3519%
3520% The first argument (and any normalization flags) are passed to
3521% ScaleKernelInfo() to scale/normalize the kernel. The second argument
3522% is then passed to UnityAddKernelInfo() to add a scled unity kernel
3523% into the scaled/normalized kernel.
3524%
3525% The format of the ScaleKernelInfo method is:
3526%
3527% void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
3528% const MagickStatusType normalize_flags )
3529%
3530% A description of each parameter follows:
3531%
3532% o kernel: the Morphology/Convolution kernel to modify
3533%
3534% o geometry:
3535% The geometry string to parse, typically from the user provided
3536% "-set option:convolve:scale {geometry}" setting.
3537%
3538*/
3539MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
3540 const char *geometry)
3541{
3542 GeometryFlags
3543 flags;
3544 GeometryInfo
3545 args;
3546
3547 SetGeometryInfo(&args);
3548 flags = (GeometryFlags) ParseGeometry(geometry, &args);
3549
3550#if 0
3551 /* For Debugging Geometry Input */
3552 fprintf(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
3553 flags, args.rho, args.sigma, args.xi, args.psi );
3554#endif
3555
3556 if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/
3557 args.rho *= 0.01, args.sigma *= 0.01;
3558
3559 if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */
3560 args.rho = 1.0;
3561 if ( (flags & SigmaValue) == 0 )
3562 args.sigma = 0.0;
3563
3564 /* Scale/Normalize the input kernel */
3565 ScaleKernelInfo(kernel, args.rho, flags);
3566
3567 /* Add Unity Kernel, for blending with original */
3568 if ( (flags & SigmaValue) != 0 )
3569 UnityAddKernelInfo(kernel, args.sigma);
3570
3571 return;
3572}
3573/*
3574%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3575% %
3576% %
3577% %
cristy6771f1e2010-03-05 19:43:39 +00003578% S c a l e K e r n e l I n f o %
anthonycc6c8362010-01-25 04:14:01 +00003579% %
3580% %
3581% %
3582%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3583%
anthony1b2bc0a2010-05-12 05:25:22 +00003584% ScaleKernelInfo() scales the given kernel list by the given amount, with or
3585% without normalization of the sum of the kernel values (as per given flags).
anthonycc6c8362010-01-25 04:14:01 +00003586%
anthony999bb2c2010-02-18 12:38:01 +00003587% By default (no flags given) the values within the kernel is scaled
anthony1b2bc0a2010-05-12 05:25:22 +00003588% directly using given scaling factor without change.
anthonycc6c8362010-01-25 04:14:01 +00003589%
anthony46a369d2010-05-19 02:41:48 +00003590% If either of the two 'normalize_flags' are given the kernel will first be
3591% normalized and then further scaled by the scaling factor value given.
anthony999bb2c2010-02-18 12:38:01 +00003592%
3593% Kernel normalization ('normalize_flags' given) is designed to ensure that
3594% any use of the kernel scaling factor with 'Convolve' or 'Correlate'
anthony1b2bc0a2010-05-12 05:25:22 +00003595% morphology methods will fall into -1.0 to +1.0 range. Note that for
3596% non-HDRI versions of IM this may cause images to have any negative results
3597% clipped, unless some 'bias' is used.
anthony999bb2c2010-02-18 12:38:01 +00003598%
3599% More specifically. Kernels which only contain positive values (such as a
3600% 'Gaussian' kernel) will be scaled so that those values sum to +1.0,
anthony1b2bc0a2010-05-12 05:25:22 +00003601% ensuring a 0.0 to +1.0 output range for non-HDRI images.
anthony999bb2c2010-02-18 12:38:01 +00003602%
3603% For Kernels that contain some negative values, (such as 'Sharpen' kernels)
3604% the kernel will be scaled by the absolute of the sum of kernel values, so
3605% that it will generally fall within the +/- 1.0 range.
3606%
3607% For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
3608% will be scaled by just the sum of the postive values, so that its output
3609% range will again fall into the +/- 1.0 range.
3610%
3611% For special kernels designed for locating shapes using 'Correlate', (often
3612% only containing +1 and -1 values, representing foreground/brackground
3613% matching) a special normalization method is provided to scale the positive
3614% values seperatally to those of the negative values, so the kernel will be
3615% forced to become a zero-sum kernel better suited to such searches.
3616%
anthony1b2bc0a2010-05-12 05:25:22 +00003617% WARNING: Correct normalization of the kernel assumes that the '*_range'
anthony999bb2c2010-02-18 12:38:01 +00003618% attributes within the kernel structure have been correctly set during the
3619% kernels creation.
3620%
3621% NOTE: The values used for 'normalize_flags' have been selected specifically
anthony46a369d2010-05-19 02:41:48 +00003622% to match the use of geometry options, so that '!' means NormalizeValue, '^'
3623% means CorrelateNormalizeValue. All other GeometryFlags values are ignored.
anthonycc6c8362010-01-25 04:14:01 +00003624%
anthony4fd27e22010-02-07 08:17:18 +00003625% The format of the ScaleKernelInfo method is:
anthonycc6c8362010-01-25 04:14:01 +00003626%
anthony999bb2c2010-02-18 12:38:01 +00003627% void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
3628% const MagickStatusType normalize_flags )
anthonycc6c8362010-01-25 04:14:01 +00003629%
3630% A description of each parameter follows:
3631%
3632% o kernel: the Morphology/Convolution kernel
3633%
anthony999bb2c2010-02-18 12:38:01 +00003634% o scaling_factor:
3635% multiply all values (after normalization) by this factor if not
3636% zero. If the kernel is normalized regardless of any flags.
3637%
3638% o normalize_flags:
3639% GeometryFlags defining normalization method to use.
3640% specifically: NormalizeValue, CorrelateNormalizeValue,
3641% and/or PercentValue
anthonycc6c8362010-01-25 04:14:01 +00003642%
3643*/
cristy6771f1e2010-03-05 19:43:39 +00003644MagickExport void ScaleKernelInfo(KernelInfo *kernel,
3645 const double scaling_factor,const GeometryFlags normalize_flags)
anthonycc6c8362010-01-25 04:14:01 +00003646{
cristybb503372010-05-27 20:51:26 +00003647 register ssize_t
anthonycc6c8362010-01-25 04:14:01 +00003648 i;
3649
anthony999bb2c2010-02-18 12:38:01 +00003650 register double
3651 pos_scale,
3652 neg_scale;
3653
anthony46a369d2010-05-19 02:41:48 +00003654 /* do the other kernels in a multi-kernel list first */
anthony1b2bc0a2010-05-12 05:25:22 +00003655 if ( kernel->next != (KernelInfo *) NULL)
3656 ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
3657
anthony46a369d2010-05-19 02:41:48 +00003658 /* Normalization of Kernel */
anthony999bb2c2010-02-18 12:38:01 +00003659 pos_scale = 1.0;
3660 if ( (normalize_flags&NormalizeValue) != 0 ) {
anthony999bb2c2010-02-18 12:38:01 +00003661 if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon )
anthonyf4e00312010-05-20 12:06:35 +00003662 /* non-zero-summing kernel (generally positive) */
anthony999bb2c2010-02-18 12:38:01 +00003663 pos_scale = fabs(kernel->positive_range + kernel->negative_range);
anthonycc6c8362010-01-25 04:14:01 +00003664 else
anthonyf4e00312010-05-20 12:06:35 +00003665 /* zero-summing kernel */
3666 pos_scale = kernel->positive_range;
anthony999bb2c2010-02-18 12:38:01 +00003667 }
anthony46a369d2010-05-19 02:41:48 +00003668 /* Force kernel into a normalized zero-summing kernel */
anthony999bb2c2010-02-18 12:38:01 +00003669 if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
3670 pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon )
3671 ? kernel->positive_range : 1.0;
3672 neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon )
3673 ? -kernel->negative_range : 1.0;
3674 }
3675 else
3676 neg_scale = pos_scale;
3677
3678 /* finialize scaling_factor for positive and negative components */
3679 pos_scale = scaling_factor/pos_scale;
3680 neg_scale = scaling_factor/neg_scale;
anthonycc6c8362010-01-25 04:14:01 +00003681
cristybb503372010-05-27 20:51:26 +00003682 for (i=0; i < (ssize_t) (kernel->width*kernel->height); i++)
anthonycc6c8362010-01-25 04:14:01 +00003683 if ( ! IsNan(kernel->values[i]) )
anthony999bb2c2010-02-18 12:38:01 +00003684 kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
anthonycc6c8362010-01-25 04:14:01 +00003685
anthony999bb2c2010-02-18 12:38:01 +00003686 /* convolution output range */
3687 kernel->positive_range *= pos_scale;
3688 kernel->negative_range *= neg_scale;
3689 /* maximum and minimum values in kernel */
3690 kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
3691 kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
3692
anthony46a369d2010-05-19 02:41:48 +00003693 /* swap kernel settings if user's scaling factor is negative */
anthony999bb2c2010-02-18 12:38:01 +00003694 if ( scaling_factor < MagickEpsilon ) {
3695 double t;
3696 t = kernel->positive_range;
3697 kernel->positive_range = kernel->negative_range;
3698 kernel->negative_range = t;
3699 t = kernel->maximum;
3700 kernel->maximum = kernel->minimum;
3701 kernel->minimum = 1;
3702 }
anthonycc6c8362010-01-25 04:14:01 +00003703
3704 return;
3705}
3706
3707/*
3708%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3709% %
3710% %
3711% %
anthony46a369d2010-05-19 02:41:48 +00003712% S h o w K e r n e l I n f o %
anthony83ba99b2010-01-24 08:48:15 +00003713% %
3714% %
3715% %
3716%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3717%
anthony4fd27e22010-02-07 08:17:18 +00003718% ShowKernelInfo() outputs the details of the given kernel defination to
3719% standard error, generally due to a users 'showkernel' option request.
anthony83ba99b2010-01-24 08:48:15 +00003720%
3721% The format of the ShowKernel method is:
3722%
anthony4fd27e22010-02-07 08:17:18 +00003723% void ShowKernelInfo(KernelInfo *kernel)
anthony83ba99b2010-01-24 08:48:15 +00003724%
3725% A description of each parameter follows:
3726%
3727% o kernel: the Morphology/Convolution kernel
3728%
anthony83ba99b2010-01-24 08:48:15 +00003729*/
anthony4fd27e22010-02-07 08:17:18 +00003730MagickExport void ShowKernelInfo(KernelInfo *kernel)
anthony83ba99b2010-01-24 08:48:15 +00003731{
anthony7a01dcf2010-05-11 12:25:52 +00003732 KernelInfo
3733 *k;
anthony83ba99b2010-01-24 08:48:15 +00003734
cristybb503372010-05-27 20:51:26 +00003735 size_t
anthony7a01dcf2010-05-11 12:25:52 +00003736 c, i, u, v;
3737
3738 for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) {
3739
anthony46a369d2010-05-19 02:41:48 +00003740 fprintf(stderr, "Kernel");
anthony7a01dcf2010-05-11 12:25:52 +00003741 if ( kernel->next != (KernelInfo *) NULL )
cristyf2faecf2010-05-28 19:19:36 +00003742 fprintf(stderr, " #%lu", (unsigned long) c );
anthony43c49252010-05-18 10:59:50 +00003743 fprintf(stderr, " \"%s",
3744 MagickOptionToMnemonic(MagickKernelOptions, k->type) );
3745 if ( fabs(k->angle) > MagickEpsilon )
3746 fprintf(stderr, "@%lg", k->angle);
cristyf2faecf2010-05-28 19:19:36 +00003747 fprintf(stderr, "\" of size %lux%lu%+ld%+ld",(unsigned long) k->width,
3748 (unsigned long) k->height,(long) k->x,(long) k->y);
anthony7a01dcf2010-05-11 12:25:52 +00003749 fprintf(stderr,
3750 " with values from %.*lg to %.*lg\n",
3751 GetMagickPrecision(), k->minimum,
3752 GetMagickPrecision(), k->maximum);
anthony46a369d2010-05-19 02:41:48 +00003753 fprintf(stderr, "Forming a output range from %.*lg to %.*lg",
anthony7a01dcf2010-05-11 12:25:52 +00003754 GetMagickPrecision(), k->negative_range,
anthony46a369d2010-05-19 02:41:48 +00003755 GetMagickPrecision(), k->positive_range);
3756 if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
3757 fprintf(stderr, " (Zero-Summing)\n");
3758 else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
3759 fprintf(stderr, " (Normalized)\n");
3760 else
3761 fprintf(stderr, " (Sum %.*lg)\n",
3762 GetMagickPrecision(), k->positive_range+k->negative_range);
anthony43c49252010-05-18 10:59:50 +00003763 for (i=v=0; v < k->height; v++) {
cristyf2faecf2010-05-28 19:19:36 +00003764 fprintf(stderr, "%2lu:", (unsigned long) v );
anthony43c49252010-05-18 10:59:50 +00003765 for (u=0; u < k->width; u++, i++)
anthony7a01dcf2010-05-11 12:25:52 +00003766 if ( IsNan(k->values[i]) )
anthonyf4e00312010-05-20 12:06:35 +00003767 fprintf(stderr," %*s", GetMagickPrecision()+3, "nan");
anthony7a01dcf2010-05-11 12:25:52 +00003768 else
anthonyf4e00312010-05-20 12:06:35 +00003769 fprintf(stderr," %*.*lg", GetMagickPrecision()+3,
anthony7a01dcf2010-05-11 12:25:52 +00003770 GetMagickPrecision(), k->values[i]);
3771 fprintf(stderr,"\n");
3772 }
anthony83ba99b2010-01-24 08:48:15 +00003773 }
3774}
anthonycc6c8362010-01-25 04:14:01 +00003775
3776/*
3777%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3778% %
3779% %
3780% %
anthony43c49252010-05-18 10:59:50 +00003781% U n i t y A d d K e r n a l I n f o %
3782% %
3783% %
3784% %
3785%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3786%
3787% UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
3788% to the given pre-scaled and normalized Kernel. This in effect adds that
3789% amount of the original image into the resulting convolution kernel. This
3790% value is usually provided by the user as a percentage value in the
3791% 'convolve:scale' setting.
3792%
anthony501c2f92010-06-02 10:55:14 +00003793% The resulting effect is to convert the defined kernels into blended
3794% soft-blurs, unsharp kernels or into sharpening kernels.
anthony43c49252010-05-18 10:59:50 +00003795%
anthony46a369d2010-05-19 02:41:48 +00003796% The format of the UnityAdditionKernelInfo method is:
anthony43c49252010-05-18 10:59:50 +00003797%
3798% void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
3799%
3800% A description of each parameter follows:
3801%
3802% o kernel: the Morphology/Convolution kernel
3803%
3804% o scale:
3805% scaling factor for the unity kernel to be added to
3806% the given kernel.
3807%
anthony43c49252010-05-18 10:59:50 +00003808*/
3809MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
3810 const double scale)
3811{
anthony46a369d2010-05-19 02:41:48 +00003812 /* do the other kernels in a multi-kernel list first */
3813 if ( kernel->next != (KernelInfo *) NULL)
3814 UnityAddKernelInfo(kernel->next, scale);
anthony43c49252010-05-18 10:59:50 +00003815
anthony46a369d2010-05-19 02:41:48 +00003816 /* Add the scaled unity kernel to the existing kernel */
anthony43c49252010-05-18 10:59:50 +00003817 kernel->values[kernel->x+kernel->y*kernel->width] += scale;
anthony46a369d2010-05-19 02:41:48 +00003818 CalcKernelMetaData(kernel); /* recalculate the meta-data */
anthony43c49252010-05-18 10:59:50 +00003819
3820 return;
3821}
3822
3823/*
3824%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3825% %
3826% %
3827% %
3828% Z e r o K e r n e l N a n s %
anthonycc6c8362010-01-25 04:14:01 +00003829% %
3830% %
3831% %
3832%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3833%
3834% ZeroKernelNans() replaces any special 'nan' value that may be present in
3835% the kernel with a zero value. This is typically done when the kernel will
3836% be used in special hardware (GPU) convolution processors, to simply
3837% matters.
3838%
3839% The format of the ZeroKernelNans method is:
3840%
anthony46a369d2010-05-19 02:41:48 +00003841% void ZeroKernelNans (KernelInfo *kernel)
anthonycc6c8362010-01-25 04:14:01 +00003842%
3843% A description of each parameter follows:
3844%
3845% o kernel: the Morphology/Convolution kernel
3846%
anthonycc6c8362010-01-25 04:14:01 +00003847*/
anthonyc4c86e02010-01-27 09:30:32 +00003848MagickExport void ZeroKernelNans(KernelInfo *kernel)
anthonycc6c8362010-01-25 04:14:01 +00003849{
cristybb503372010-05-27 20:51:26 +00003850 register size_t
anthonycc6c8362010-01-25 04:14:01 +00003851 i;
3852
anthony46a369d2010-05-19 02:41:48 +00003853 /* do the other kernels in a multi-kernel list first */
anthony1b2bc0a2010-05-12 05:25:22 +00003854 if ( kernel->next != (KernelInfo *) NULL)
3855 ZeroKernelNans(kernel->next);
3856
anthony43c49252010-05-18 10:59:50 +00003857 for (i=0; i < (kernel->width*kernel->height); i++)
anthonycc6c8362010-01-25 04:14:01 +00003858 if ( IsNan(kernel->values[i]) )
3859 kernel->values[i] = 0.0;
3860
3861 return;
3862}