blob: 9a0607fdc3afbbe399f11b789f64eefd70e78efb [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 *),
cristyeb8db6d2010-05-24 18:34:11 +0000115 ExpandKernelInfo(KernelInfo *, const double),
cristyef656912010-03-05 19:54:59 +0000116 RotateKernelInfo(KernelInfo *, double);
anthony602ab9b2010-01-05 08:06:50 +0000117
anthony3dd0f622010-05-13 12:57:32 +0000118
119/* Quick function to find last kernel in a kernel list */
120static inline KernelInfo *LastKernelInfo(KernelInfo *kernel)
121{
122 while (kernel->next != (KernelInfo *) NULL)
123 kernel = kernel->next;
124 return(kernel);
125}
126
127
anthony602ab9b2010-01-05 08:06:50 +0000128/*
129%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
130% %
131% %
132% %
anthony83ba99b2010-01-24 08:48:15 +0000133% A c q u i r e K e r n e l I n f o %
anthony602ab9b2010-01-05 08:06:50 +0000134% %
135% %
136% %
137%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
138%
cristy2be15382010-01-21 02:38:03 +0000139% AcquireKernelInfo() takes the given string (generally supplied by the
anthony602ab9b2010-01-05 08:06:50 +0000140% user) and converts it into a Morphology/Convolution Kernel. This allows
141% users to specify a kernel from a number of pre-defined kernels, or to fully
142% specify their own kernel for a specific Convolution or Morphology
143% Operation.
144%
145% The kernel so generated can be any rectangular array of floating point
146% values (doubles) with the 'control point' or 'pixel being affected'
147% anywhere within that array of values.
148%
anthony83ba99b2010-01-24 08:48:15 +0000149% Previously IM was restricted to a square of odd size using the exact
150% center as origin, this is no longer the case, and any rectangular kernel
151% with any value being declared the origin. This in turn allows the use of
152% highly asymmetrical kernels.
anthony602ab9b2010-01-05 08:06:50 +0000153%
154% The floating point values in the kernel can also include a special value
anthony83ba99b2010-01-24 08:48:15 +0000155% known as 'nan' or 'not a number' to indicate that this value is not part
156% of the kernel array. This allows you to shaped the kernel within its
157% rectangular area. That is 'nan' values provide a 'mask' for the kernel
158% shape. However at least one non-nan value must be provided for correct
159% working of a kernel.
anthony602ab9b2010-01-05 08:06:50 +0000160%
anthony7a01dcf2010-05-11 12:25:52 +0000161% The returned kernel should be freed using the DestroyKernelInfo() when you
162% are finished with it. Do not free this memory yourself.
anthony602ab9b2010-01-05 08:06:50 +0000163%
164% Input kernel defintion strings can consist of any of three types.
165%
anthony29188a82010-01-22 10:12:34 +0000166% "name:args"
167% Select from one of the built in kernels, using the name and
168% geometry arguments supplied. See AcquireKernelBuiltIn()
anthony602ab9b2010-01-05 08:06:50 +0000169%
anthony43c49252010-05-18 10:59:50 +0000170% "WxH[+X+Y][^@]:num, num, num ..."
anthony1b2bc0a2010-05-12 05:25:22 +0000171% a kernel of size W by H, with W*H floating point numbers following.
anthony602ab9b2010-01-05 08:06:50 +0000172% the 'center' can be optionally be defined at +X+Y (such that +0+0
anthony29188a82010-01-22 10:12:34 +0000173% is top left corner). If not defined the pixel in the center, for
174% odd sizes, or to the immediate top or left of center for even sizes
175% is automatically selected.
anthony602ab9b2010-01-05 08:06:50 +0000176%
anthony43c49252010-05-18 10:59:50 +0000177% If a '^' is included the kernel expanded with 90-degree rotations,
178% While a '@' will allow you to expand a 3x3 kernel using 45-degree
179% circular rotates.
180%
anthony29188a82010-01-22 10:12:34 +0000181% "num, num, num, num, ..."
182% list of floating point numbers defining an 'old style' odd sized
183% square kernel. At least 9 values should be provided for a 3x3
184% square kernel, 25 for a 5x5 square kernel, 49 for 7x7, etc.
185% Values can be space or comma separated. This is not recommended.
anthony602ab9b2010-01-05 08:06:50 +0000186%
anthony7a01dcf2010-05-11 12:25:52 +0000187% You can define a 'list of kernels' which can be used by some morphology
188% operators A list is defined as a semi-colon seperated list kernels.
189%
anthonydbc89892010-05-12 07:05:27 +0000190% " kernel ; kernel ; kernel ; "
anthony7a01dcf2010-05-11 12:25:52 +0000191%
anthony43c49252010-05-18 10:59:50 +0000192% Any extra ';' characters (at start, end or between kernel defintions are
193% simply ignored.
194%
195% Note that 'name' kernels will start with an alphabetic character while the
196% new kernel specification has a ':' character in its specification string.
197% If neither is the case, it is assumed an old style of a simple list of
198% numbers generating a odd-sized square kernel has been given.
anthony7a01dcf2010-05-11 12:25:52 +0000199%
anthony602ab9b2010-01-05 08:06:50 +0000200% The format of the AcquireKernal method is:
201%
cristy2be15382010-01-21 02:38:03 +0000202% KernelInfo *AcquireKernelInfo(const char *kernel_string)
anthony602ab9b2010-01-05 08:06:50 +0000203%
204% A description of each parameter follows:
205%
206% o kernel_string: the Morphology/Convolution kernel wanted.
207%
208*/
209
anthonyc84dce52010-05-07 05:42:23 +0000210/* This was separated so that it could be used as a separate
anthony5ef8e942010-05-11 06:51:12 +0000211** array input handling function, such as for -color-matrix
anthonyc84dce52010-05-07 05:42:23 +0000212*/
anthony5ef8e942010-05-11 06:51:12 +0000213static KernelInfo *ParseKernelArray(const char *kernel_string)
anthony602ab9b2010-01-05 08:06:50 +0000214{
cristy2be15382010-01-21 02:38:03 +0000215 KernelInfo
anthony602ab9b2010-01-05 08:06:50 +0000216 *kernel;
217
218 char
219 token[MaxTextExtent];
220
anthony602ab9b2010-01-05 08:06:50 +0000221 const char
anthony5ef8e942010-05-11 06:51:12 +0000222 *p,
223 *end;
anthony602ab9b2010-01-05 08:06:50 +0000224
anthonyc84dce52010-05-07 05:42:23 +0000225 register long
226 i;
anthony602ab9b2010-01-05 08:06:50 +0000227
anthony29188a82010-01-22 10:12:34 +0000228 double
229 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
230
anthony43c49252010-05-18 10:59:50 +0000231 MagickStatusType
232 flags;
233
234 GeometryInfo
235 args;
236
cristy2be15382010-01-21 02:38:03 +0000237 kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
238 if (kernel == (KernelInfo *)NULL)
anthony602ab9b2010-01-05 08:06:50 +0000239 return(kernel);
240 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
anthony43c49252010-05-18 10:59:50 +0000241 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
anthony7a01dcf2010-05-11 12:25:52 +0000242 kernel->negative_range = kernel->positive_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +0000243 kernel->type = UserDefinedKernel;
anthony7a01dcf2010-05-11 12:25:52 +0000244 kernel->next = (KernelInfo *) NULL;
cristyd43a46b2010-01-21 02:13:41 +0000245 kernel->signature = MagickSignature;
anthony602ab9b2010-01-05 08:06:50 +0000246
anthony5ef8e942010-05-11 06:51:12 +0000247 /* find end of this specific kernel definition string */
248 end = strchr(kernel_string, ';');
249 if ( end == (char *) NULL )
250 end = strchr(kernel_string, '\0');
251
anthony43c49252010-05-18 10:59:50 +0000252 /* clear flags - for Expanding kernal lists thorugh rotations */
253 flags = NoValue;
254
anthony602ab9b2010-01-05 08:06:50 +0000255 /* Has a ':' in argument - New user kernel specification */
256 p = strchr(kernel_string, ':');
anthony5ef8e942010-05-11 06:51:12 +0000257 if ( p != (char *) NULL && p < end)
anthony602ab9b2010-01-05 08:06:50 +0000258 {
anthony602ab9b2010-01-05 08:06:50 +0000259 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
cristy150989e2010-02-01 14:59:39 +0000260 memcpy(token, kernel_string, (size_t) (p-kernel_string));
anthony602ab9b2010-01-05 08:06:50 +0000261 token[p-kernel_string] = '\0';
anthonyc84dce52010-05-07 05:42:23 +0000262 SetGeometryInfo(&args);
anthony602ab9b2010-01-05 08:06:50 +0000263 flags = ParseGeometry(token, &args);
anthony602ab9b2010-01-05 08:06:50 +0000264
anthony29188a82010-01-22 10:12:34 +0000265 /* Size handling and checks of geometry settings */
anthony602ab9b2010-01-05 08:06:50 +0000266 if ( (flags & WidthValue) == 0 ) /* if no width then */
267 args.rho = args.sigma; /* then width = height */
268 if ( args.rho < 1.0 ) /* if width too small */
269 args.rho = 1.0; /* then width = 1 */
270 if ( args.sigma < 1.0 ) /* if height too small */
271 args.sigma = args.rho; /* then height = width */
272 kernel->width = (unsigned long)args.rho;
273 kernel->height = (unsigned long)args.sigma;
274
275 /* Offset Handling and Checks */
276 if ( args.xi < 0.0 || args.psi < 0.0 )
anthony83ba99b2010-01-24 08:48:15 +0000277 return(DestroyKernelInfo(kernel));
cristyc99304f2010-02-01 15:26:27 +0000278 kernel->x = ((flags & XValue)!=0) ? (long)args.xi
cristy150989e2010-02-01 14:59:39 +0000279 : (long) (kernel->width-1)/2;
cristyc99304f2010-02-01 15:26:27 +0000280 kernel->y = ((flags & YValue)!=0) ? (long)args.psi
cristy150989e2010-02-01 14:59:39 +0000281 : (long) (kernel->height-1)/2;
cristyc99304f2010-02-01 15:26:27 +0000282 if ( kernel->x >= (long) kernel->width ||
283 kernel->y >= (long) kernel->height )
anthony83ba99b2010-01-24 08:48:15 +0000284 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000285
286 p++; /* advance beyond the ':' */
287 }
288 else
anthonyc84dce52010-05-07 05:42:23 +0000289 { /* ELSE - Old old specification, forming odd-square kernel */
anthony602ab9b2010-01-05 08:06:50 +0000290 /* count up number of values given */
291 p=(const char *) kernel_string;
cristya699b172010-01-06 16:48:49 +0000292 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
anthony29188a82010-01-22 10:12:34 +0000293 p++; /* ignore "'" chars for convolve filter usage - Cristy */
anthony5ef8e942010-05-11 06:51:12 +0000294 for (i=0; p < end; i++)
anthony602ab9b2010-01-05 08:06:50 +0000295 {
296 GetMagickToken(p,&p,token);
297 if (*token == ',')
298 GetMagickToken(p,&p,token);
299 }
300 /* set the size of the kernel - old sized square */
301 kernel->width = kernel->height= (unsigned long) sqrt((double) i+1.0);
cristyc99304f2010-02-01 15:26:27 +0000302 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +0000303 p=(const char *) kernel_string;
anthony29188a82010-01-22 10:12:34 +0000304 while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == '\''))
305 p++; /* ignore "'" chars for convolve filter usage - Cristy */
anthony602ab9b2010-01-05 08:06:50 +0000306 }
307
308 /* Read in the kernel values from rest of input string argument */
309 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
310 kernel->height*sizeof(double));
311 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +0000312 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000313
cristyc99304f2010-02-01 15:26:27 +0000314 kernel->minimum = +MagickHuge;
315 kernel->maximum = -MagickHuge;
316 kernel->negative_range = kernel->positive_range = 0.0;
anthonyc84dce52010-05-07 05:42:23 +0000317
anthony5ef8e942010-05-11 06:51:12 +0000318 for (i=0; (i < (long) (kernel->width*kernel->height)) && (p < end); i++)
anthony602ab9b2010-01-05 08:06:50 +0000319 {
320 GetMagickToken(p,&p,token);
321 if (*token == ',')
322 GetMagickToken(p,&p,token);
anthony29188a82010-01-22 10:12:34 +0000323 if ( LocaleCompare("nan",token) == 0
anthonyc84dce52010-05-07 05:42:23 +0000324 || LocaleCompare("-",token) == 0 ) {
anthony29188a82010-01-22 10:12:34 +0000325 kernel->values[i] = nan; /* do not include this value in kernel */
326 }
327 else {
328 kernel->values[i] = StringToDouble(token);
329 ( kernel->values[i] < 0)
cristyc99304f2010-02-01 15:26:27 +0000330 ? ( kernel->negative_range += kernel->values[i] )
331 : ( kernel->positive_range += kernel->values[i] );
332 Minimize(kernel->minimum, kernel->values[i]);
333 Maximize(kernel->maximum, kernel->values[i]);
anthony29188a82010-01-22 10:12:34 +0000334 }
anthony602ab9b2010-01-05 08:06:50 +0000335 }
anthony29188a82010-01-22 10:12:34 +0000336
anthony5ef8e942010-05-11 06:51:12 +0000337 /* sanity check -- no more values in kernel definition */
338 GetMagickToken(p,&p,token);
339 if ( *token != '\0' && *token != ';' && *token != '\'' )
340 return(DestroyKernelInfo(kernel));
341
anthonyc84dce52010-05-07 05:42:23 +0000342#if 0
343 /* this was the old method of handling a incomplete kernel */
cristy150989e2010-02-01 14:59:39 +0000344 if ( i < (long) (kernel->width*kernel->height) ) {
cristyc99304f2010-02-01 15:26:27 +0000345 Minimize(kernel->minimum, kernel->values[i]);
346 Maximize(kernel->maximum, kernel->values[i]);
cristy150989e2010-02-01 14:59:39 +0000347 for ( ; i < (long) (kernel->width*kernel->height); i++)
anthony29188a82010-01-22 10:12:34 +0000348 kernel->values[i]=0.0;
349 }
anthonyc84dce52010-05-07 05:42:23 +0000350#else
351 /* Number of values for kernel was not enough - Report Error */
352 if ( i < (long) (kernel->width*kernel->height) )
353 return(DestroyKernelInfo(kernel));
354#endif
355
356 /* check that we recieved at least one real (non-nan) value! */
357 if ( kernel->minimum == MagickHuge )
358 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000359
anthony43c49252010-05-18 10:59:50 +0000360 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */
361 ExpandKernelInfo(kernel, 45.0);
362 else if ( (flags & MinimumValue) != 0 ) /* '^' symbol in kernel size */
363 ExpandKernelInfo(kernel, 90.0);
364
anthony602ab9b2010-01-05 08:06:50 +0000365 return(kernel);
366}
anthonyc84dce52010-05-07 05:42:23 +0000367
anthony43c49252010-05-18 10:59:50 +0000368static KernelInfo *ParseKernelName(const char *kernel_string)
anthonyc84dce52010-05-07 05:42:23 +0000369{
anthonyf0176c32010-05-23 23:08:57 +0000370 KernelInfo
371 *kernel;
372
anthonyc84dce52010-05-07 05:42:23 +0000373 char
374 token[MaxTextExtent];
375
anthony5ef8e942010-05-11 06:51:12 +0000376 long
377 type;
378
anthonyc84dce52010-05-07 05:42:23 +0000379 const char
anthony7a01dcf2010-05-11 12:25:52 +0000380 *p,
381 *end;
anthonyc84dce52010-05-07 05:42:23 +0000382
383 MagickStatusType
384 flags;
385
386 GeometryInfo
387 args;
388
anthonyc84dce52010-05-07 05:42:23 +0000389 /* Parse special 'named' kernel */
anthony5ef8e942010-05-11 06:51:12 +0000390 GetMagickToken(kernel_string,&p,token);
anthonyc84dce52010-05-07 05:42:23 +0000391 type=ParseMagickOption(MagickKernelOptions,MagickFalse,token);
392 if ( type < 0 || type == UserDefinedKernel )
anthony5ef8e942010-05-11 06:51:12 +0000393 return((KernelInfo *)NULL); /* not a valid named kernel */
anthonyc84dce52010-05-07 05:42:23 +0000394
395 while (((isspace((int) ((unsigned char) *p)) != 0) ||
anthony5ef8e942010-05-11 06:51:12 +0000396 (*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
anthonyc84dce52010-05-07 05:42:23 +0000397 p++;
anthony7a01dcf2010-05-11 12:25:52 +0000398
399 end = strchr(p, ';'); /* end of this kernel defintion */
400 if ( end == (char *) NULL )
401 end = strchr(p, '\0');
402
403 /* ParseGeometry() needs the geometry separated! -- Arrgghh */
404 memcpy(token, p, (size_t) (end-p));
405 token[end-p] = '\0';
anthonyc84dce52010-05-07 05:42:23 +0000406 SetGeometryInfo(&args);
anthony7a01dcf2010-05-11 12:25:52 +0000407 flags = ParseGeometry(token, &args);
anthonyc84dce52010-05-07 05:42:23 +0000408
anthony3c10fc82010-05-13 02:40:51 +0000409#if 0
410 /* For Debugging Geometry Input */
anthony46a369d2010-05-19 02:41:48 +0000411 fprintf(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
anthony3c10fc82010-05-13 02:40:51 +0000412 flags, args.rho, args.sigma, args.xi, args.psi );
413#endif
414
anthonyc84dce52010-05-07 05:42:23 +0000415 /* special handling of missing values in input string */
416 switch( type ) {
anthony5ef8e942010-05-11 06:51:12 +0000417 case RectangleKernel:
418 if ( (flags & WidthValue) == 0 ) /* if no width then */
419 args.rho = args.sigma; /* then width = height */
420 if ( args.rho < 1.0 ) /* if width too small */
421 args.rho = 3; /* then width = 3 */
422 if ( args.sigma < 1.0 ) /* if height too small */
423 args.sigma = args.rho; /* then height = width */
424 if ( (flags & XValue) == 0 ) /* center offset if not defined */
425 args.xi = (double)(((long)args.rho-1)/2);
426 if ( (flags & YValue) == 0 )
427 args.psi = (double)(((long)args.sigma-1)/2);
428 break;
429 case SquareKernel:
430 case DiamondKernel:
431 case DiskKernel:
432 case PlusKernel:
anthony3dd0f622010-05-13 12:57:32 +0000433 case CrossKernel:
anthony5ef8e942010-05-11 06:51:12 +0000434 /* If no scale given (a 0 scale is valid! - set it to 1.0 */
435 if ( (flags & HeightValue) == 0 )
436 args.sigma = 1.0;
437 break;
anthonyc1061722010-05-14 06:23:49 +0000438 case RingKernel:
439 if ( (flags & XValue) == 0 )
440 args.xi = 1.0;
441 break;
anthony5ef8e942010-05-11 06:51:12 +0000442 case ChebyshevKernel:
443 case ManhattenKernel:
444 case EuclideanKernel:
anthony43c49252010-05-18 10:59:50 +0000445 if ( (flags & HeightValue) == 0 ) /* no distance scale */
446 args.sigma = 100.0; /* default distance scaling */
447 else if ( (flags & AspectValue ) != 0 ) /* '!' flag */
448 args.sigma = QuantumRange/(args.sigma+1); /* maximum pixel distance */
449 else if ( (flags & PercentValue ) != 0 ) /* '%' flag */
450 args.sigma *= QuantumRange/100.0; /* percentage of color range */
anthony5ef8e942010-05-11 06:51:12 +0000451 break;
452 default:
453 break;
anthonyc84dce52010-05-07 05:42:23 +0000454 }
455
anthonyf0176c32010-05-23 23:08:57 +0000456 kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args);
457
458 /* global expand to rotated kernel list - only for single kernels */
459 if ( kernel->next == (KernelInfo *) NULL ) {
460 if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel args */
461 ExpandKernelInfo(kernel, 45.0);
462 else if ( (flags & MinimumValue) != 0 ) /* '^' symbol in kernel args */
463 ExpandKernelInfo(kernel, 90.0);
464 }
465
466 return(kernel);
anthonyc84dce52010-05-07 05:42:23 +0000467}
468
anthony5ef8e942010-05-11 06:51:12 +0000469MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string)
470{
anthony7a01dcf2010-05-11 12:25:52 +0000471
472 KernelInfo
anthonydbc89892010-05-12 07:05:27 +0000473 *kernel,
anthony43c49252010-05-18 10:59:50 +0000474 *new_kernel;
anthony7a01dcf2010-05-11 12:25:52 +0000475
anthony5ef8e942010-05-11 06:51:12 +0000476 char
477 token[MaxTextExtent];
478
anthony7a01dcf2010-05-11 12:25:52 +0000479 const char
anthonydbc89892010-05-12 07:05:27 +0000480 *p;
anthony7a01dcf2010-05-11 12:25:52 +0000481
anthonye108a3f2010-05-12 07:24:03 +0000482 unsigned long
483 kernel_number;
484
anthonydbc89892010-05-12 07:05:27 +0000485 p = kernel_string;
anthony43c49252010-05-18 10:59:50 +0000486 kernel = NULL;
anthonye108a3f2010-05-12 07:24:03 +0000487 kernel_number = 0;
anthony5ef8e942010-05-11 06:51:12 +0000488
anthonydbc89892010-05-12 07:05:27 +0000489 while ( GetMagickToken(p,NULL,token), *token != '\0' ) {
anthony7a01dcf2010-05-11 12:25:52 +0000490
anthony43c49252010-05-18 10:59:50 +0000491 /* ignore extra or multiple ';' kernel seperators */
anthonydbc89892010-05-12 07:05:27 +0000492 if ( *token != ';' ) {
anthony7a01dcf2010-05-11 12:25:52 +0000493
anthonydbc89892010-05-12 07:05:27 +0000494 /* tokens starting with alpha is a Named kernel */
anthony43c49252010-05-18 10:59:50 +0000495 if (isalpha((int) *token) != 0)
496 new_kernel = ParseKernelName(p);
anthonydbc89892010-05-12 07:05:27 +0000497 else /* otherwise a user defined kernel array */
anthony43c49252010-05-18 10:59:50 +0000498 new_kernel = ParseKernelArray(p);
anthony7a01dcf2010-05-11 12:25:52 +0000499
anthonye108a3f2010-05-12 07:24:03 +0000500 /* Error handling -- this is not proper error handling! */
501 if ( new_kernel == (KernelInfo *) NULL ) {
502 fprintf(stderr, "Failed to parse kernel number #%lu\n", kernel_number);
503 if ( kernel != (KernelInfo *) NULL )
504 kernel=DestroyKernelInfo(kernel);
505 return((KernelInfo *) NULL);
anthonydbc89892010-05-12 07:05:27 +0000506 }
anthonye108a3f2010-05-12 07:24:03 +0000507
508 /* initialise or append the kernel list */
anthony3dd0f622010-05-13 12:57:32 +0000509 if ( kernel == (KernelInfo *) NULL )
510 kernel = new_kernel;
511 else
anthony43c49252010-05-18 10:59:50 +0000512 LastKernelInfo(kernel)->next = new_kernel;
anthonydbc89892010-05-12 07:05:27 +0000513 }
514
515 /* look for the next kernel in list */
516 p = strchr(p, ';');
517 if ( p == (char *) NULL )
518 break;
519 p++;
520
521 }
anthony7a01dcf2010-05-11 12:25:52 +0000522 return(kernel);
anthony5ef8e942010-05-11 06:51:12 +0000523}
524
anthony602ab9b2010-01-05 08:06:50 +0000525
526/*
527%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
528% %
529% %
530% %
531% A c q u i r e K e r n e l B u i l t I n %
532% %
533% %
534% %
535%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
536%
537% AcquireKernelBuiltIn() returned one of the 'named' built-in types of
538% kernels used for special purposes such as gaussian blurring, skeleton
539% pruning, and edge distance determination.
540%
541% They take a KernelType, and a set of geometry style arguments, which were
542% typically decoded from a user supplied string, or from a more complex
543% Morphology Method that was requested.
544%
545% The format of the AcquireKernalBuiltIn method is:
546%
cristy2be15382010-01-21 02:38:03 +0000547% KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
anthony602ab9b2010-01-05 08:06:50 +0000548% const GeometryInfo args)
549%
550% A description of each parameter follows:
551%
552% o type: the pre-defined type of kernel wanted
553%
554% o args: arguments defining or modifying the kernel
555%
556% Convolution Kernels
557%
anthony46a369d2010-05-19 02:41:48 +0000558% Unity
559% the No-Op kernel, also requivelent to Gaussian of sigma zero.
560% Basically a 3x3 kernel of a 1 surrounded by zeros.
561%
anthony3c10fc82010-05-13 02:40:51 +0000562% Gaussian:{radius},{sigma}
563% Generate a two-dimentional gaussian kernel, as used by -gaussian.
anthonyc1061722010-05-14 06:23:49 +0000564% The sigma for the curve is required. The resulting kernel is
565% normalized,
566%
567% If 'sigma' is zero, you get a single pixel on a field of zeros.
anthony602ab9b2010-01-05 08:06:50 +0000568%
569% NOTE: that the 'radius' is optional, but if provided can limit (clip)
570% the final size of the resulting kernel to a square 2*radius+1 in size.
571% The radius should be at least 2 times that of the sigma value, or
572% sever clipping and aliasing may result. If not given or set to 0 the
573% radius will be determined so as to produce the best minimal error
574% result, which is usally much larger than is normally needed.
575%
anthonyc1061722010-05-14 06:23:49 +0000576% DOG:{radius},{sigma1},{sigma2}
577% "Difference of Gaussians" Kernel.
578% As "Gaussian" but with a gaussian produced by 'sigma2' subtracted
579% from the gaussian produced by 'sigma1'. Typically sigma2 > sigma1.
580% The result is a zero-summing kernel.
anthony602ab9b2010-01-05 08:06:50 +0000581%
anthony9eb4f742010-05-18 02:45:54 +0000582% LOG:{radius},{sigma}
583% "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
584% The supposed ideal edge detection, zero-summing kernel.
585%
586% An alturnative to this kernel is to use a "DOG" with a sigma ratio of
587% approx 1.6, which can also be applied as a 2 pass "DOB" (see below).
588%
anthonyc1061722010-05-14 06:23:49 +0000589% Blur:{radius},{sigma}[,{angle}]
590% Generates a 1 dimensional or linear gaussian blur, at the angle given
591% (current restricted to orthogonal angles). If a 'radius' is given the
592% kernel is clipped to a width of 2*radius+1. Kernel can be rotated
593% by a 90 degree angle.
594%
595% If 'sigma' is zero, you get a single pixel on a field of zeros.
596%
597% Note that two convolutions with two "Blur" kernels perpendicular to
598% each other, is equivelent to a far larger "Gaussian" kernel with the
599% same sigma value, However it is much faster to apply. This is how the
600% "-blur" operator actually works.
601%
602% DOB:{radius},{sigma1},{sigma2}[,{angle}]
603% "Difference of Blurs" Kernel.
604% As "Blur" but with the 1D gaussian produced by 'sigma2' subtracted
605% from thethe 1D gaussian produced by 'sigma1'.
606% The result is a zero-summing kernel.
607%
608% This can be used to generate a faster "DOG" convolution, in the same
609% way "Blur" can.
anthony602ab9b2010-01-05 08:06:50 +0000610%
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
anthony43c49252010-05-18 10:59:50 +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}
677% Frei-Chen Edge Detector is a set of 9 unique convolution kernels that
anthonyc3cd15b2010-05-27 06:05:40 +0000678% are specially weighted.
679%
680% Type 0: | -1, 0, 1 |
681% | -sqrt(2), 0, sqrt(2) |
682% | -1, 0, 1 |
683%
684% This is basically the unnormalized discrete kernel that can be used
685% instead ot a Sobel kernel.
686%
687% The next 9 kernel types are specially pre-weighted. They should not
688% be normalized. After applying each to the original image, the results
689% is then added together. The square root of the resulting image is
690% the cosine of the edge, and the direction of the feature detection.
anthonye2a60ce2010-05-19 12:30:40 +0000691%
692% Type 1: | 1, sqrt(2), 1 |
693% | 0, 0, 0 | / 2*sqrt(2)
694% | -1, -sqrt(2), -1 |
695%
696% Type 2: | 1, 0, 1 |
697% | sqrt(2), 0, sqrt(2) | / 2*sqrt(2)
698% | 1, 0, 1 |
699%
700% Type 3: | 0, -1, sqrt(2) |
701% | 1, 0, -1 | / 2*sqrt(2)
702% | -sqrt(2), 1, 0 |
703%
anthony6915d062010-05-19 12:45:51 +0000704% Type 4: | sqrt(2), -1, 0 |
anthonye2a60ce2010-05-19 12:30:40 +0000705% | -1, 0, 1 | / 2*sqrt(2)
706% | 0, 1, -sqrt(2) |
707%
708% Type 5: | 0, 1, 0 |
709% | -1, 0, -1 | / 2
710% | 0, 1, 0 |
711%
712% Type 6: | -1, 0, 1 |
713% | 0, 0, 0 | / 2
714% | 1, 0, -1 |
715%
anthonyf4e00312010-05-20 12:06:35 +0000716% Type 7: | 1, -2, 1 |
anthonye2a60ce2010-05-19 12:30:40 +0000717% | -2, 4, -2 | / 6
718% | 1, -2, 1 |
719%
anthonyf4e00312010-05-20 12:06:35 +0000720% Type 8: | -2, 1, -2 |
721% | 1, 4, 1 | / 6
722% | -2, 1, -2 |
anthonye2a60ce2010-05-19 12:30:40 +0000723%
anthonyf4e00312010-05-20 12:06:35 +0000724% Type 9: | 1, 1, 1 |
725% | 1, 1, 1 | / 3
726% | 1, 1, 1 |
anthonye2a60ce2010-05-19 12:30:40 +0000727%
728% The first 4 are for edge detection, the next 4 are for line detection
729% and the last is to add a average component to the results.
730%
anthonyc3cd15b2010-05-27 06:05:40 +0000731% Using a special type of '-1' will return all 9 pre-weighted kernels
732% as a multi-kernel list, so that you can use them directly (without
733% normalization) with the special "-set option:morphology:compose Plus"
734% setting to apply the full FreiChen Edge Detection Technique.
735%
anthonye2a60ce2010-05-19 12:30:40 +0000736%
anthony602ab9b2010-01-05 08:06:50 +0000737% Boolean Kernels
738%
anthony3c10fc82010-05-13 02:40:51 +0000739% Diamond:[{radius}[,{scale}]]
anthony1b2bc0a2010-05-12 05:25:22 +0000740% Generate a diamond shaped kernel with given radius to the points.
anthony602ab9b2010-01-05 08:06:50 +0000741% Kernel size will again be radius*2+1 square and defaults to radius 1,
742% generating a 3x3 kernel that is slightly larger than a square.
743%
anthony3c10fc82010-05-13 02:40:51 +0000744% Square:[{radius}[,{scale}]]
anthony602ab9b2010-01-05 08:06:50 +0000745% Generate a square shaped kernel of size radius*2+1, and defaulting
746% to a 3x3 (radius 1).
747%
anthonyc1061722010-05-14 06:23:49 +0000748% Note that using a larger radius for the "Square" or the "Diamond" is
749% also equivelent to iterating the basic morphological method that many
750% times. However iterating with the smaller radius is actually faster
751% than using a larger kernel radius.
752%
753% Rectangle:{geometry}
754% Simply generate a rectangle of 1's with the size given. You can also
755% specify the location of the 'control point', otherwise the closest
756% pixel to the center of the rectangle is selected.
757%
758% Properly centered and odd sized rectangles work the best.
anthony602ab9b2010-01-05 08:06:50 +0000759%
anthony3c10fc82010-05-13 02:40:51 +0000760% Disk:[{radius}[,{scale}]]
anthony602ab9b2010-01-05 08:06:50 +0000761% Generate a binary disk of the radius given, radius may be a float.
762% Kernel size will be ceil(radius)*2+1 square.
763% NOTE: Here are some disk shapes of specific interest
anthonyc1061722010-05-14 06:23:49 +0000764% "Disk:1" => "diamond" or "cross:1"
765% "Disk:1.5" => "square"
766% "Disk:2" => "diamond:2"
767% "Disk:2.5" => a general disk shape of radius 2
768% "Disk:2.9" => "square:2"
769% "Disk:3.5" => default - octagonal/disk shape of radius 3
770% "Disk:4.2" => roughly octagonal shape of radius 4
771% "Disk:4.3" => a general disk shape of radius 4
anthony602ab9b2010-01-05 08:06:50 +0000772% After this all the kernel shape becomes more and more circular.
773%
774% Because a "disk" is more circular when using a larger radius, using a
775% larger radius is preferred over iterating the morphological operation.
776%
anthonyc1061722010-05-14 06:23:49 +0000777% Symbol Dilation Kernels
778%
779% These kernel is not a good general morphological kernel, but is used
780% more for highlighting and marking any single pixels in an image using,
781% a "Dilate" method as appropriate.
782%
783% For the same reasons iterating these kernels does not produce the
784% same result as using a larger radius for the symbol.
785%
anthony3c10fc82010-05-13 02:40:51 +0000786% Plus:[{radius}[,{scale}]]
anthony3dd0f622010-05-13 12:57:32 +0000787% Cross:[{radius}[,{scale}]]
anthonyc1061722010-05-14 06:23:49 +0000788% Generate a kernel in the shape of a 'plus' or a 'cross' with
789% a each arm the length of the given radius (default 2).
anthony3dd0f622010-05-13 12:57:32 +0000790%
791% NOTE: "plus:1" is equivelent to a "Diamond" kernel.
anthony602ab9b2010-01-05 08:06:50 +0000792%
anthonyc1061722010-05-14 06:23:49 +0000793% Ring:{radius1},{radius2}[,{scale}]
794% A ring of the values given that falls between the two radii.
795% Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
796% This is the 'edge' pixels of the default "Disk" kernel,
797% More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
anthony602ab9b2010-01-05 08:06:50 +0000798%
anthony3dd0f622010-05-13 12:57:32 +0000799% Hit and Miss Kernels
800%
801% Peak:radius1,radius2
anthonyc1061722010-05-14 06:23:49 +0000802% Find any peak larger than the pixels the fall between the two radii.
803% The default ring of pixels is as per "Ring".
anthony43c49252010-05-18 10:59:50 +0000804% Edges
anthony1d45eb92010-05-25 11:13:23 +0000805% Find edges of a binary shape
anthony3dd0f622010-05-13 12:57:32 +0000806% Corners
807% Find corners of a binary shape
anthony47f5d062010-05-23 07:47:50 +0000808% Ridges
anthony1d45eb92010-05-25 11:13:23 +0000809% Find single pixel ridges or thin lines
810% Ridges2
811% Find 2 pixel thick ridges or lines
anthonya648a302010-05-27 02:14:36 +0000812% Ridges3
813% Find 2 pixel thick diagonal ridges (experimental)
anthony3dd0f622010-05-13 12:57:32 +0000814% LineEnds
815% Find end points of lines (for pruning a skeletion)
816% LineJunctions
anthony43c49252010-05-18 10:59:50 +0000817% Find three line junctions (within a skeletion)
anthony3dd0f622010-05-13 12:57:32 +0000818% ConvexHull
819% Octagonal thicken kernel, to generate convex hulls of 45 degrees
820% Skeleton
821% Thinning kernel, which leaves behind a skeletion of a shape
anthony602ab9b2010-01-05 08:06:50 +0000822%
823% Distance Measuring Kernels
824%
anthonyc1061722010-05-14 06:23:49 +0000825% Different types of distance measuring methods, which are used with the
826% a 'Distance' morphology method for generating a gradient based on
827% distance from an edge of a binary shape, though there is a technique
828% for handling a anti-aliased shape.
829%
830% See the 'Distance' Morphological Method, for information of how it is
831% applied.
832%
anthony3dd0f622010-05-13 12:57:32 +0000833% Chebyshev:[{radius}][x{scale}[%!]]
anthonyc94cdb02010-01-06 08:15:29 +0000834% Chebyshev Distance (also known as Tchebychev Distance) is a value of
835% one to any neighbour, orthogonal or diagonal. One why of thinking of
836% it is the number of squares a 'King' or 'Queen' in chess needs to
837% traverse reach any other position on a chess board. It results in a
838% 'square' like distance function, but one where diagonals are closer
839% than expected.
anthony602ab9b2010-01-05 08:06:50 +0000840%
anthonyc1061722010-05-14 06:23:49 +0000841% Manhatten:[{radius}][x{scale}[%!]]
anthonyc94cdb02010-01-06 08:15:29 +0000842% Manhatten Distance (also known as Rectilinear Distance, or the Taxi
843% Cab metric), is the distance needed when you can only travel in
844% orthogonal (horizontal or vertical) only. It is the distance a 'Rook'
845% in chess would travel. It results in a diamond like distances, where
846% diagonals are further than expected.
anthony602ab9b2010-01-05 08:06:50 +0000847%
anthonyc1061722010-05-14 06:23:49 +0000848% Euclidean:[{radius}][x{scale}[%!]]
anthonyc94cdb02010-01-06 08:15:29 +0000849% Euclidean Distance is the 'direct' or 'as the crow flys distance.
850% However by default the kernel size only has a radius of 1, which
851% limits the distance to 'Knight' like moves, with only orthogonal and
852% diagonal measurements being correct. As such for the default kernel
853% you will get octagonal like distance function, which is reasonally
854% accurate.
855%
856% However if you use a larger radius such as "Euclidean:4" you will
857% get a much smoother distance gradient from the edge of the shape.
858% Of course a larger kernel is slower to use, and generally not needed.
859%
860% To allow the use of fractional distances that you get with diagonals
861% the actual distance is scaled by a fixed value which the user can
862% provide. This is not actually nessary for either ""Chebyshev" or
863% "Manhatten" distance kernels, but is done for all three distance
864% kernels. If no scale is provided it is set to a value of 100,
865% allowing for a maximum distance measurement of 655 pixels using a Q16
866% version of IM, from any edge. However for small images this can
867% result in quite a dark gradient.
868%
anthony602ab9b2010-01-05 08:06:50 +0000869*/
870
cristy2be15382010-01-21 02:38:03 +0000871MagickExport KernelInfo *AcquireKernelBuiltIn(const KernelInfoType type,
anthony602ab9b2010-01-05 08:06:50 +0000872 const GeometryInfo *args)
873{
cristy2be15382010-01-21 02:38:03 +0000874 KernelInfo
anthony602ab9b2010-01-05 08:06:50 +0000875 *kernel;
876
cristy150989e2010-02-01 14:59:39 +0000877 register long
anthony602ab9b2010-01-05 08:06:50 +0000878 i;
879
880 register long
881 u,
882 v;
883
884 double
885 nan = sqrt((double)-1.0); /* Special Value : Not A Number */
886
anthonyc1061722010-05-14 06:23:49 +0000887 /* Generate a new empty kernel if needed */
cristye96405a2010-05-19 02:24:31 +0000888 kernel=(KernelInfo *) NULL;
anthonyc1061722010-05-14 06:23:49 +0000889 switch(type) {
anthony9eb4f742010-05-18 02:45:54 +0000890 case UndefinedKernel: /* These should not be used here */
891 case UserDefinedKernel:
892 break;
893 case LaplacianKernel: /* Named Descrete Convolution Kernels */
894 case SobelKernel:
895 case RobertsKernel:
896 case PrewittKernel:
897 case CompassKernel:
898 case KirschKernel:
899 case CornersKernel: /* Hit and Miss kernels */
900 case LineEndsKernel:
901 case LineJunctionsKernel:
anthony9eb4f742010-05-18 02:45:54 +0000902 case ConvexHullKernel:
903 case SkeletonKernel:
904 /* A pre-generated kernel is not needed */
905 break;
906#if 0
anthonyc1061722010-05-14 06:23:49 +0000907 case GaussianKernel:
908 case DOGKernel:
909 case BlurKernel:
910 case DOBKernel:
911 case CometKernel:
912 case DiamondKernel:
913 case SquareKernel:
914 case RectangleKernel:
915 case DiskKernel:
916 case PlusKernel:
917 case CrossKernel:
918 case RingKernel:
919 case PeaksKernel:
920 case ChebyshevKernel:
921 case ManhattenKernel:
922 case EuclideanKernel:
anthony9eb4f742010-05-18 02:45:54 +0000923#endif
924 default:
925 /* Generate the base Kernel Structure */
anthonyc1061722010-05-14 06:23:49 +0000926 kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
927 if (kernel == (KernelInfo *) NULL)
928 return(kernel);
929 (void) ResetMagickMemory(kernel,0,sizeof(*kernel));
anthony43c49252010-05-18 10:59:50 +0000930 kernel->minimum = kernel->maximum = kernel->angle = 0.0;
anthonyc1061722010-05-14 06:23:49 +0000931 kernel->negative_range = kernel->positive_range = 0.0;
932 kernel->type = type;
933 kernel->next = (KernelInfo *) NULL;
934 kernel->signature = MagickSignature;
anthonyc1061722010-05-14 06:23:49 +0000935 break;
936 }
anthony602ab9b2010-01-05 08:06:50 +0000937
938 switch(type) {
939 /* Convolution Kernels */
940 case GaussianKernel:
anthonyc1061722010-05-14 06:23:49 +0000941 case DOGKernel:
anthony9eb4f742010-05-18 02:45:54 +0000942 case LOGKernel:
anthony602ab9b2010-01-05 08:06:50 +0000943 { double
anthonyc1061722010-05-14 06:23:49 +0000944 sigma = fabs(args->sigma),
945 sigma2 = fabs(args->xi),
anthony9eb4f742010-05-18 02:45:54 +0000946 A, B, R;
anthony602ab9b2010-01-05 08:06:50 +0000947
anthonyc1061722010-05-14 06:23:49 +0000948 if ( args->rho >= 1.0 )
949 kernel->width = (unsigned long)args->rho*2+1;
anthony9eb4f742010-05-18 02:45:54 +0000950 else if ( (type != DOGKernel) || (sigma >= sigma2) )
anthonyc1061722010-05-14 06:23:49 +0000951 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
952 else
953 kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
954 kernel->height = kernel->width;
cristyc99304f2010-02-01 15:26:27 +0000955 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +0000956 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
957 kernel->height*sizeof(double));
958 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +0000959 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +0000960
anthony46a369d2010-05-19 02:41:48 +0000961 /* WARNING: The following generates a 'sampled gaussian' kernel.
anthony9eb4f742010-05-18 02:45:54 +0000962 * What we really want is a 'discrete gaussian' kernel.
anthony46a369d2010-05-19 02:41:48 +0000963 *
964 * How to do this is currently not known, but appears to be
965 * basied on the Error Function 'erf()' (intergral of a gaussian)
anthony9eb4f742010-05-18 02:45:54 +0000966 */
967
968 if ( type == GaussianKernel || type == DOGKernel )
969 { /* Calculate a Gaussian, OR positive half of a DOG */
970 if ( sigma > MagickEpsilon )
971 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
972 B = 1.0/(Magick2PI*sigma*sigma);
973 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
974 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
975 kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
976 }
977 else /* limiting case - a unity (normalized Dirac) kernel */
978 { (void) ResetMagickMemory(kernel->values,0, (size_t)
979 kernel->width*kernel->height*sizeof(double));
980 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
981 }
anthonyc1061722010-05-14 06:23:49 +0000982 }
anthony9eb4f742010-05-18 02:45:54 +0000983
anthonyc1061722010-05-14 06:23:49 +0000984 if ( type == DOGKernel )
985 { /* Subtract a Negative Gaussian for "Difference of Gaussian" */
986 if ( sigma2 > MagickEpsilon )
987 { sigma = sigma2; /* simplify loop expressions */
anthony9eb4f742010-05-18 02:45:54 +0000988 A = 1.0/(2.0*sigma*sigma);
989 B = 1.0/(Magick2PI*sigma*sigma);
anthonyc1061722010-05-14 06:23:49 +0000990 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
991 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
anthony9eb4f742010-05-18 02:45:54 +0000992 kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
anthonyc1061722010-05-14 06:23:49 +0000993 }
anthony9eb4f742010-05-18 02:45:54 +0000994 else /* limiting case - a unity (normalized Dirac) kernel */
anthonyc1061722010-05-14 06:23:49 +0000995 kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
996 }
anthony9eb4f742010-05-18 02:45:54 +0000997
998 if ( type == LOGKernel )
999 { /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
1000 if ( sigma > MagickEpsilon )
1001 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1002 B = 1.0/(MagickPI*sigma*sigma*sigma*sigma);
1003 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1004 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1005 { R = ((double)(u*u+v*v))*A;
1006 kernel->values[i] = (1-R)*exp(-R)*B;
1007 }
1008 }
1009 else /* special case - generate a unity kernel */
1010 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1011 kernel->width*kernel->height*sizeof(double));
1012 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1013 }
1014 }
1015
1016 /* Note the above kernels may have been 'clipped' by a user defined
anthonyc1061722010-05-14 06:23:49 +00001017 ** radius, producing a smaller (darker) kernel. Also for very small
1018 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1019 ** producing a very bright kernel.
1020 **
1021 ** Normalization will still be needed.
1022 */
anthony602ab9b2010-01-05 08:06:50 +00001023
anthony3dd0f622010-05-13 12:57:32 +00001024 /* Normalize the 2D Gaussian Kernel
1025 **
anthonyc1061722010-05-14 06:23:49 +00001026 ** NB: a CorrelateNormalize performs a normal Normalize if
1027 ** there are no negative values.
anthony3dd0f622010-05-13 12:57:32 +00001028 */
anthony46a369d2010-05-19 02:41:48 +00001029 CalcKernelMetaData(kernel); /* the other kernel meta-data */
anthonyc1061722010-05-14 06:23:49 +00001030 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
anthony602ab9b2010-01-05 08:06:50 +00001031
1032 break;
1033 }
1034 case BlurKernel:
anthonyc1061722010-05-14 06:23:49 +00001035 case DOBKernel:
anthony602ab9b2010-01-05 08:06:50 +00001036 { double
anthonyc1061722010-05-14 06:23:49 +00001037 sigma = fabs(args->sigma),
1038 sigma2 = fabs(args->xi),
anthony9eb4f742010-05-18 02:45:54 +00001039 A, B;
anthony602ab9b2010-01-05 08:06:50 +00001040
anthonyc1061722010-05-14 06:23:49 +00001041 if ( args->rho >= 1.0 )
1042 kernel->width = (unsigned long)args->rho*2+1;
1043 else if ( (type == BlurKernel) || (sigma >= sigma2) )
1044 kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
1045 else
1046 kernel->width = GetOptimalKernelWidth1D(args->rho,sigma2);
anthony602ab9b2010-01-05 08:06:50 +00001047 kernel->height = 1;
anthonyc1061722010-05-14 06:23:49 +00001048 kernel->x = (long) (kernel->width-1)/2;
cristyc99304f2010-02-01 15:26:27 +00001049 kernel->y = 0;
1050 kernel->negative_range = kernel->positive_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +00001051 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1052 kernel->height*sizeof(double));
1053 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001054 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001055
1056#if 1
1057#define KernelRank 3
1058 /* Formula derived from GetBlurKernel() in "effect.c" (plus bug fix).
1059 ** It generates a gaussian 3 times the width, and compresses it into
1060 ** the expected range. This produces a closer normalization of the
1061 ** resulting kernel, especially for very low sigma values.
1062 ** As such while wierd it is prefered.
1063 **
1064 ** I am told this method originally came from Photoshop.
anthony9eb4f742010-05-18 02:45:54 +00001065 **
1066 ** A properly normalized curve is generated (apart from edge clipping)
1067 ** even though we later normalize the result (for edge clipping)
1068 ** to allow the correct generation of a "Difference of Blurs".
anthony602ab9b2010-01-05 08:06:50 +00001069 */
anthonyc1061722010-05-14 06:23:49 +00001070
1071 /* initialize */
cristy150989e2010-02-01 14:59:39 +00001072 v = (long) (kernel->width*KernelRank-1)/2; /* start/end points to fit range */
anthony9eb4f742010-05-18 02:45:54 +00001073 (void) ResetMagickMemory(kernel->values,0, (size_t)
1074 kernel->width*kernel->height*sizeof(double));
anthonyc1061722010-05-14 06:23:49 +00001075 /* Calculate a Positive 1D Gaussian */
1076 if ( sigma > MagickEpsilon )
1077 { sigma *= KernelRank; /* simplify loop expressions */
anthony9eb4f742010-05-18 02:45:54 +00001078 A = 1.0/(2.0*sigma*sigma);
1079 B = 1.0/(MagickSQ2PI*sigma );
anthonyc1061722010-05-14 06:23:49 +00001080 for ( u=-v; u <= v; u++) {
anthony9eb4f742010-05-18 02:45:54 +00001081 kernel->values[(u+v)/KernelRank] += exp(-((double)(u*u))*A)*B;
anthonyc1061722010-05-14 06:23:49 +00001082 }
1083 }
1084 else /* special case - generate a unity kernel */
1085 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
anthony9eb4f742010-05-18 02:45:54 +00001086
1087 /* Subtract a Second 1D Gaussian for "Difference of Blur" */
anthonyc1061722010-05-14 06:23:49 +00001088 if ( type == DOBKernel )
anthony9eb4f742010-05-18 02:45:54 +00001089 {
anthonyc1061722010-05-14 06:23:49 +00001090 if ( sigma2 > MagickEpsilon )
1091 { sigma = sigma2*KernelRank; /* simplify loop expressions */
anthony9eb4f742010-05-18 02:45:54 +00001092 A = 1.0/(2.0*sigma*sigma);
1093 B = 1.0/(MagickSQ2PI*sigma);
anthonyc1061722010-05-14 06:23:49 +00001094 for ( u=-v; u <= v; u++)
anthony9eb4f742010-05-18 02:45:54 +00001095 kernel->values[(u+v)/KernelRank] -= exp(-((double)(u*u))*A)*B;
anthonyc1061722010-05-14 06:23:49 +00001096 }
anthony9eb4f742010-05-18 02:45:54 +00001097 else /* limiting case - a unity (normalized Dirac) kernel */
anthonyc1061722010-05-14 06:23:49 +00001098 kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1099 }
anthony602ab9b2010-01-05 08:06:50 +00001100#else
anthonyc1061722010-05-14 06:23:49 +00001101 /* Direct calculation without curve averaging */
1102
1103 /* Calculate a Positive Gaussian */
1104 if ( sigma > MagickEpsilon )
anthony9eb4f742010-05-18 02:45:54 +00001105 { A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1106 B = 1.0/(MagickSQ2PI*sigma);
anthonyc1061722010-05-14 06:23:49 +00001107 for ( i=0, u=-kernel->x; u <= (long)kernel->x; u++, i++)
anthony9eb4f742010-05-18 02:45:54 +00001108 kernel->values[i] = exp(-((double)(u*u))*A)*B;
anthonyc1061722010-05-14 06:23:49 +00001109 }
1110 else /* special case - generate a unity kernel */
1111 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1112 kernel->width*kernel->height*sizeof(double));
1113 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1114 }
anthony9eb4f742010-05-18 02:45:54 +00001115
1116 /* Subtract a Second 1D Gaussian for "Difference of Blur" */
anthonyc1061722010-05-14 06:23:49 +00001117 if ( type == DOBKernel )
anthony9eb4f742010-05-18 02:45:54 +00001118 {
anthonyc1061722010-05-14 06:23:49 +00001119 if ( sigma2 > MagickEpsilon )
1120 { sigma = sigma2; /* simplify loop expressions */
anthony9eb4f742010-05-18 02:45:54 +00001121 A = 1.0/(2.0*sigma*sigma);
1122 B = 1.0/(MagickSQ2PI*sigma);
anthonyc1061722010-05-14 06:23:49 +00001123 for ( i=0, u=-kernel->x; u <= (long)kernel->x; u++, i++)
anthony9eb4f742010-05-18 02:45:54 +00001124 kernel->values[i] -= exp(-((double)(u*u))*A)*B;
anthonyc1061722010-05-14 06:23:49 +00001125 }
anthony9eb4f742010-05-18 02:45:54 +00001126 else /* limiting case - a unity (normalized Dirac) kernel */
anthonyc1061722010-05-14 06:23:49 +00001127 kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1128 }
anthony602ab9b2010-01-05 08:06:50 +00001129#endif
anthonyc1061722010-05-14 06:23:49 +00001130 /* Note the above kernel may have been 'clipped' by a user defined
anthonycc6c8362010-01-25 04:14:01 +00001131 ** radius, producing a smaller (darker) kernel. Also for very small
1132 ** sigma's (> 0.1) the central value becomes larger than one, and thus
1133 ** producing a very bright kernel.
anthonyc1061722010-05-14 06:23:49 +00001134 **
1135 ** Normalization will still be needed.
anthony602ab9b2010-01-05 08:06:50 +00001136 */
anthonycc6c8362010-01-25 04:14:01 +00001137
anthony602ab9b2010-01-05 08:06:50 +00001138 /* Normalize the 1D Gaussian Kernel
1139 **
anthonyc1061722010-05-14 06:23:49 +00001140 ** NB: a CorrelateNormalize performs a normal Normalize if
1141 ** there are no negative values.
anthony602ab9b2010-01-05 08:06:50 +00001142 */
anthony46a369d2010-05-19 02:41:48 +00001143 CalcKernelMetaData(kernel); /* the other kernel meta-data */
1144 ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
anthonycc6c8362010-01-25 04:14:01 +00001145
anthonyc1061722010-05-14 06:23:49 +00001146 /* rotate the 1D kernel by given angle */
1147 RotateKernelInfo(kernel, (type == BlurKernel) ? args->xi : args->psi );
anthony602ab9b2010-01-05 08:06:50 +00001148 break;
1149 }
1150 case CometKernel:
1151 { double
anthony9eb4f742010-05-18 02:45:54 +00001152 sigma = fabs(args->sigma),
1153 A;
anthony602ab9b2010-01-05 08:06:50 +00001154
anthony602ab9b2010-01-05 08:06:50 +00001155 if ( args->rho < 1.0 )
anthonye1cf9462010-05-19 03:50:26 +00001156 kernel->width = (GetOptimalKernelWidth1D(args->rho,sigma)-1)/2+1;
anthony602ab9b2010-01-05 08:06:50 +00001157 else
1158 kernel->width = (unsigned long)args->rho;
cristyc99304f2010-02-01 15:26:27 +00001159 kernel->x = kernel->y = 0;
anthony602ab9b2010-01-05 08:06:50 +00001160 kernel->height = 1;
cristyc99304f2010-02-01 15:26:27 +00001161 kernel->negative_range = kernel->positive_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +00001162 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1163 kernel->height*sizeof(double));
1164 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001165 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001166
anthonyc1061722010-05-14 06:23:49 +00001167 /* A comet blur is half a 1D gaussian curve, so that the object is
anthony602ab9b2010-01-05 08:06:50 +00001168 ** blurred in one direction only. This may not be quite the right
anthony3dd0f622010-05-13 12:57:32 +00001169 ** curve to use so may change in the future. The function must be
1170 ** normalised after generation, which also resolves any clipping.
anthonyc1061722010-05-14 06:23:49 +00001171 **
1172 ** As we are normalizing and not subtracting gaussians,
1173 ** there is no need for a divisor in the gaussian formula
1174 **
anthony43c49252010-05-18 10:59:50 +00001175 ** It is less comples
anthony602ab9b2010-01-05 08:06:50 +00001176 */
anthony9eb4f742010-05-18 02:45:54 +00001177 if ( sigma > MagickEpsilon )
1178 {
anthony602ab9b2010-01-05 08:06:50 +00001179#if 1
1180#define KernelRank 3
anthony9eb4f742010-05-18 02:45:54 +00001181 v = (long) kernel->width*KernelRank; /* start/end points */
1182 (void) ResetMagickMemory(kernel->values,0, (size_t)
1183 kernel->width*sizeof(double));
1184 sigma *= KernelRank; /* simplify the loop expression */
1185 A = 1.0/(2.0*sigma*sigma);
1186 /* B = 1.0/(MagickSQ2PI*sigma); */
1187 for ( u=0; u < v; u++) {
1188 kernel->values[u/KernelRank] +=
1189 exp(-((double)(u*u))*A);
1190 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1191 }
1192 for (i=0; i < (long) kernel->width; i++)
1193 kernel->positive_range += kernel->values[i];
anthony602ab9b2010-01-05 08:06:50 +00001194#else
anthony9eb4f742010-05-18 02:45:54 +00001195 A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
1196 /* B = 1.0/(MagickSQ2PI*sigma); */
1197 for ( i=0; i < (long) kernel->width; i++)
1198 kernel->positive_range +=
1199 kernel->values[i] =
1200 exp(-((double)(i*i))*A);
1201 /* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
anthony602ab9b2010-01-05 08:06:50 +00001202#endif
anthony9eb4f742010-05-18 02:45:54 +00001203 }
1204 else /* special case - generate a unity kernel */
1205 { (void) ResetMagickMemory(kernel->values,0, (size_t)
1206 kernel->width*kernel->height*sizeof(double));
1207 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1208 kernel->positive_range = 1.0;
1209 }
anthony46a369d2010-05-19 02:41:48 +00001210
1211 kernel->minimum = 0.0;
cristyc99304f2010-02-01 15:26:27 +00001212 kernel->maximum = kernel->values[0];
anthony46a369d2010-05-19 02:41:48 +00001213 kernel->negative_range = 0.0;
anthony602ab9b2010-01-05 08:06:50 +00001214
anthony999bb2c2010-02-18 12:38:01 +00001215 ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1216 RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
anthony602ab9b2010-01-05 08:06:50 +00001217 break;
1218 }
anthonyc1061722010-05-14 06:23:49 +00001219
anthony3c10fc82010-05-13 02:40:51 +00001220 /* Convolution Kernels - Well Known Constants */
anthony3c10fc82010-05-13 02:40:51 +00001221 case LaplacianKernel:
anthonye2a60ce2010-05-19 12:30:40 +00001222 { switch ( (int) args->rho ) {
anthony3dd0f622010-05-13 12:57:32 +00001223 case 0:
anthony9eb4f742010-05-18 02:45:54 +00001224 default: /* laplacian square filter -- default */
anthonyc1061722010-05-14 06:23:49 +00001225 kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
anthony3dd0f622010-05-13 12:57:32 +00001226 break;
anthony9eb4f742010-05-18 02:45:54 +00001227 case 1: /* laplacian diamond filter */
anthonyc1061722010-05-14 06:23:49 +00001228 kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
anthony3c10fc82010-05-13 02:40:51 +00001229 break;
1230 case 2:
anthony9eb4f742010-05-18 02:45:54 +00001231 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1232 break;
1233 case 3:
anthonyc1061722010-05-14 06:23:49 +00001234 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
anthony3c10fc82010-05-13 02:40:51 +00001235 break;
anthony9eb4f742010-05-18 02:45:54 +00001236 case 5: /* a 5x5 laplacian */
anthony3c10fc82010-05-13 02:40:51 +00001237 kernel=ParseKernelArray(
anthony9eb4f742010-05-18 02:45:54 +00001238 "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 +00001239 break;
anthony9eb4f742010-05-18 02:45:54 +00001240 case 7: /* a 7x7 laplacian */
anthony3c10fc82010-05-13 02:40:51 +00001241 kernel=ParseKernelArray(
anthonyc1061722010-05-14 06:23:49 +00001242 "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 +00001243 break;
anthony43c49252010-05-18 10:59:50 +00001244 case 15: /* a 5x5 LOG (sigma approx 1.4) */
anthony9eb4f742010-05-18 02:45:54 +00001245 kernel=ParseKernelArray(
1246 "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");
1247 break;
anthony43c49252010-05-18 10:59:50 +00001248 case 19: /* a 9x9 LOG (sigma approx 1.4) */
1249 /* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1250 kernel=ParseKernelArray(
1251 "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");
1252 break;
anthony3c10fc82010-05-13 02:40:51 +00001253 }
1254 if (kernel == (KernelInfo *) NULL)
1255 return(kernel);
1256 kernel->type = type;
1257 break;
1258 }
anthonyc1061722010-05-14 06:23:49 +00001259 case SobelKernel:
anthony602ab9b2010-01-05 08:06:50 +00001260 {
anthonyc1061722010-05-14 06:23:49 +00001261 kernel=ParseKernelArray("3: -1,0,1 -2,0,2 -1,0,1");
1262 if (kernel == (KernelInfo *) NULL)
1263 return(kernel);
1264 kernel->type = type;
1265 RotateKernelInfo(kernel, args->rho); /* Rotate by angle */
1266 break;
1267 }
1268 case RobertsKernel:
1269 {
1270 kernel=ParseKernelArray("3: 0,0,0 -1,1,0 0,0,0");
1271 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 PrewittKernel:
1278 {
1279 kernel=ParseKernelArray("3: -1,1,1 0,0,0 -1,1,1");
1280 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 }
1286 case CompassKernel:
1287 {
1288 kernel=ParseKernelArray("3: -1,1,1 -1,-2,1 -1,1,1");
1289 if (kernel == (KernelInfo *) NULL)
1290 return(kernel);
1291 kernel->type = type;
anthony46a369d2010-05-19 02:41:48 +00001292 RotateKernelInfo(kernel, args->rho);
anthonyc1061722010-05-14 06:23:49 +00001293 break;
1294 }
anthony9eb4f742010-05-18 02:45:54 +00001295 case KirschKernel:
1296 {
1297 kernel=ParseKernelArray("3: -3,-3,5 -3,0,5 -3,-3,5");
1298 if (kernel == (KernelInfo *) NULL)
1299 return(kernel);
1300 kernel->type = type;
anthony46a369d2010-05-19 02:41:48 +00001301 RotateKernelInfo(kernel, args->rho);
anthony9eb4f742010-05-18 02:45:54 +00001302 break;
1303 }
anthonye2a60ce2010-05-19 12:30:40 +00001304 case FreiChenKernel:
anthony6915d062010-05-19 12:45:51 +00001305 /* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf */
1306 /* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf */
anthonyc3cd15b2010-05-27 06:05:40 +00001307 { switch ( (long) args->rho ) {
anthonye2a60ce2010-05-19 12:30:40 +00001308 default:
anthonyc3cd15b2010-05-27 06:05:40 +00001309 case 0:
1310 kernel=ParseKernelArray("3: -1,0,1 -2,0,2 -1,0,1");
1311 if (kernel == (KernelInfo *) NULL)
1312 return(kernel);
1313 kernel->values[4] = -MagickSQ2;
1314 kernel->values[6] = +MagickSQ2;
1315 CalcKernelMetaData(kernel); /* recalculate meta-data */
1316 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1317 break;
anthonye2a60ce2010-05-19 12:30:40 +00001318 case 1:
1319 kernel=ParseKernelArray("3: 1,2,1 0,0,0 -1,2,-1");
1320 if (kernel == (KernelInfo *) NULL)
1321 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001322 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001323 kernel->values[1] = +MagickSQ2;
1324 kernel->values[7] = -MagickSQ2;
1325 CalcKernelMetaData(kernel); /* recalculate meta-data */
1326 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1327 break;
1328 case 2:
1329 kernel=ParseKernelArray("3: 1,0,1 2,0,2 1,0,1");
1330 if (kernel == (KernelInfo *) NULL)
1331 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001332 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001333 kernel->values[3] = +MagickSQ2;
1334 kernel->values[5] = +MagickSQ2;
1335 CalcKernelMetaData(kernel);
1336 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1337 break;
1338 case 3:
1339 kernel=ParseKernelArray("3: 0,-1,2 1,0,-1 -2,1,0");
1340 if (kernel == (KernelInfo *) NULL)
1341 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001342 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001343 kernel->values[2] = +MagickSQ2;
1344 kernel->values[6] = -MagickSQ2;
1345 CalcKernelMetaData(kernel);
1346 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1347 break;
1348 case 4:
anthony6915d062010-05-19 12:45:51 +00001349 kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
anthonye2a60ce2010-05-19 12:30:40 +00001350 if (kernel == (KernelInfo *) NULL)
1351 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001352 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001353 kernel->values[0] = +MagickSQ2;
1354 kernel->values[8] = -MagickSQ2;
1355 CalcKernelMetaData(kernel);
1356 ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1357 break;
1358 case 5:
1359 kernel=ParseKernelArray("3: 0,1,0 -1,0,-1 0,1,0");
1360 if (kernel == (KernelInfo *) NULL)
1361 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001362 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001363 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1364 break;
1365 case 6:
1366 kernel=ParseKernelArray("3: -1,0,1 0,0,0 1,0,-1");
1367 if (kernel == (KernelInfo *) NULL)
1368 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001369 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001370 ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1371 break;
1372 case 7:
anthonyf4e00312010-05-20 12:06:35 +00001373 kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
anthonye2a60ce2010-05-19 12:30:40 +00001374 if (kernel == (KernelInfo *) NULL)
1375 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001376 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001377 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1378 break;
1379 case 8:
1380 kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1381 if (kernel == (KernelInfo *) NULL)
1382 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001383 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001384 ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1385 break;
1386 case 9:
anthonyc3cd15b2010-05-27 06:05:40 +00001387 kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
anthonye2a60ce2010-05-19 12:30:40 +00001388 if (kernel == (KernelInfo *) NULL)
1389 return(kernel);
anthonyc3cd15b2010-05-27 06:05:40 +00001390 kernel->type = type;
anthonye2a60ce2010-05-19 12:30:40 +00001391 ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1392 break;
anthonyc3cd15b2010-05-27 06:05:40 +00001393 case -1:
1394 kernel=ParseKernelName("FreiChen:1;FreiChen:2;FreiChen:3;FreiChen:4;FreiChen:5;FreiChen:6;FreiChen:7;FreiChen:8;FreiChen:9");
1395 break;
anthonye2a60ce2010-05-19 12:30:40 +00001396 }
anthonyc3cd15b2010-05-27 06:05:40 +00001397 if ( fabs(args->sigma) > MagickEpsilon )
1398 /* Rotate by correctly supplied 'angle' */
1399 RotateKernelInfo(kernel, args->sigma);
1400 else if ( args->rho > 30.0 || args->rho < -30.0 )
1401 /* Rotate by out of bounds 'type' */
1402 RotateKernelInfo(kernel, args->rho);
anthonye2a60ce2010-05-19 12:30:40 +00001403 break;
1404 }
1405
anthonyc1061722010-05-14 06:23:49 +00001406 /* Boolean Kernels */
1407 case DiamondKernel:
1408 {
1409 if (args->rho < 1.0)
1410 kernel->width = kernel->height = 3; /* default radius = 1 */
1411 else
1412 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
1413 kernel->x = kernel->y = (long) (kernel->width-1)/2;
1414
1415 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1416 kernel->height*sizeof(double));
1417 if (kernel->values == (double *) NULL)
1418 return(DestroyKernelInfo(kernel));
1419
1420 /* set all kernel values within diamond area to scale given */
1421 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1422 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1423 if ((labs(u)+labs(v)) <= (long)kernel->x)
1424 kernel->positive_range += kernel->values[i] = args->sigma;
1425 else
1426 kernel->values[i] = nan;
1427 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1428 break;
1429 }
1430 case SquareKernel:
1431 case RectangleKernel:
1432 { double
1433 scale;
anthony602ab9b2010-01-05 08:06:50 +00001434 if ( type == SquareKernel )
1435 {
1436 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001437 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001438 else
cristy150989e2010-02-01 14:59:39 +00001439 kernel->width = kernel->height = (unsigned long) (2*args->rho+1);
cristyc99304f2010-02-01 15:26:27 +00001440 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony4fd27e22010-02-07 08:17:18 +00001441 scale = args->sigma;
anthony602ab9b2010-01-05 08:06:50 +00001442 }
1443 else {
cristy2be15382010-01-21 02:38:03 +00001444 /* NOTE: user defaults set in "AcquireKernelInfo()" */
anthony602ab9b2010-01-05 08:06:50 +00001445 if ( args->rho < 1.0 || args->sigma < 1.0 )
anthony83ba99b2010-01-24 08:48:15 +00001446 return(DestroyKernelInfo(kernel)); /* invalid args given */
anthony602ab9b2010-01-05 08:06:50 +00001447 kernel->width = (unsigned long)args->rho;
1448 kernel->height = (unsigned long)args->sigma;
1449 if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
1450 args->psi < 0.0 || args->psi > (double)kernel->height )
anthony83ba99b2010-01-24 08:48:15 +00001451 return(DestroyKernelInfo(kernel)); /* invalid args given */
cristyc99304f2010-02-01 15:26:27 +00001452 kernel->x = (long) args->xi;
1453 kernel->y = (long) args->psi;
anthony4fd27e22010-02-07 08:17:18 +00001454 scale = 1.0;
anthony602ab9b2010-01-05 08:06:50 +00001455 }
1456 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1457 kernel->height*sizeof(double));
1458 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001459 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001460
anthony3dd0f622010-05-13 12:57:32 +00001461 /* set all kernel values to scale given */
cristy150989e2010-02-01 14:59:39 +00001462 u=(long) kernel->width*kernel->height;
1463 for ( i=0; i < u; i++)
anthony4fd27e22010-02-07 08:17:18 +00001464 kernel->values[i] = scale;
1465 kernel->minimum = kernel->maximum = scale; /* a flat shape */
1466 kernel->positive_range = scale*u;
anthonycc6c8362010-01-25 04:14:01 +00001467 break;
anthony602ab9b2010-01-05 08:06:50 +00001468 }
anthony602ab9b2010-01-05 08:06:50 +00001469 case DiskKernel:
1470 {
anthonyc1061722010-05-14 06:23:49 +00001471 long limit = (long)(args->rho*args->rho);
anthony83ba99b2010-01-24 08:48:15 +00001472 if (args->rho < 0.1) /* default radius approx 3.5 */
1473 kernel->width = kernel->height = 7L, limit = 10L;
anthony602ab9b2010-01-05 08:06:50 +00001474 else
1475 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
cristyc99304f2010-02-01 15:26:27 +00001476 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001477
1478 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1479 kernel->height*sizeof(double));
1480 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001481 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001482
anthony3dd0f622010-05-13 12:57:32 +00001483 /* set all kernel values within disk area to scale given */
1484 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
cristyc99304f2010-02-01 15:26:27 +00001485 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
anthony602ab9b2010-01-05 08:06:50 +00001486 if ((u*u+v*v) <= limit)
anthony4fd27e22010-02-07 08:17:18 +00001487 kernel->positive_range += kernel->values[i] = args->sigma;
anthony602ab9b2010-01-05 08:06:50 +00001488 else
1489 kernel->values[i] = nan;
anthony4fd27e22010-02-07 08:17:18 +00001490 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
anthony602ab9b2010-01-05 08:06:50 +00001491 break;
1492 }
1493 case PlusKernel:
1494 {
1495 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001496 kernel->width = kernel->height = 5; /* default radius 2 */
anthony602ab9b2010-01-05 08:06:50 +00001497 else
1498 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
cristyc99304f2010-02-01 15:26:27 +00001499 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001500
1501 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1502 kernel->height*sizeof(double));
1503 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001504 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001505
anthony3dd0f622010-05-13 12:57:32 +00001506 /* set all kernel values along axises to given scale */
cristyc99304f2010-02-01 15:26:27 +00001507 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1508 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
anthony4fd27e22010-02-07 08:17:18 +00001509 kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1510 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1511 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
anthony602ab9b2010-01-05 08:06:50 +00001512 break;
1513 }
anthony3dd0f622010-05-13 12:57:32 +00001514 case CrossKernel:
1515 {
1516 if (args->rho < 1.0)
1517 kernel->width = kernel->height = 5; /* default radius 2 */
1518 else
1519 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
1520 kernel->x = kernel->y = (long) (kernel->width-1)/2;
1521
1522 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1523 kernel->height*sizeof(double));
1524 if (kernel->values == (double *) NULL)
1525 return(DestroyKernelInfo(kernel));
1526
1527 /* set all kernel values along axises to given scale */
1528 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1529 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1530 kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1531 kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1532 kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1533 break;
1534 }
1535 /* HitAndMiss Kernels */
anthonyc1061722010-05-14 06:23:49 +00001536 case RingKernel:
anthony3dd0f622010-05-13 12:57:32 +00001537 case PeaksKernel:
1538 {
1539 long
1540 limit1,
anthonyc1061722010-05-14 06:23:49 +00001541 limit2,
1542 scale;
anthony3dd0f622010-05-13 12:57:32 +00001543
1544 if (args->rho < args->sigma)
1545 {
1546 kernel->width = ((unsigned long)args->sigma)*2+1;
1547 limit1 = (long)args->rho*args->rho;
1548 limit2 = (long)args->sigma*args->sigma;
1549 }
1550 else
1551 {
1552 kernel->width = ((unsigned long)args->rho)*2+1;
1553 limit1 = (long)args->sigma*args->sigma;
1554 limit2 = (long)args->rho*args->rho;
1555 }
anthonyc1061722010-05-14 06:23:49 +00001556 if ( limit2 <= 0 )
1557 kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1558
anthony3dd0f622010-05-13 12:57:32 +00001559 kernel->height = kernel->width;
1560 kernel->x = kernel->y = (long) (kernel->width-1)/2;
1561 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1562 kernel->height*sizeof(double));
1563 if (kernel->values == (double *) NULL)
1564 return(DestroyKernelInfo(kernel));
1565
anthonyc1061722010-05-14 06:23:49 +00001566 /* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
cristye96405a2010-05-19 02:24:31 +00001567 scale = (long) (( type == PeaksKernel) ? 0.0 : args->xi);
anthony3dd0f622010-05-13 12:57:32 +00001568 for ( i=0, v= -kernel->y; v <= (long)kernel->y; v++)
1569 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1570 { long radius=u*u+v*v;
anthonyc1061722010-05-14 06:23:49 +00001571 if (limit1 < radius && radius <= limit2)
cristye96405a2010-05-19 02:24:31 +00001572 kernel->positive_range += kernel->values[i] = (double) scale;
anthony3dd0f622010-05-13 12:57:32 +00001573 else
1574 kernel->values[i] = nan;
1575 }
cristye96405a2010-05-19 02:24:31 +00001576 kernel->minimum = kernel->minimum = (double) scale;
anthonyc1061722010-05-14 06:23:49 +00001577 if ( type == PeaksKernel ) {
1578 /* set the central point in the middle */
1579 kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1580 kernel->positive_range = 1.0;
1581 kernel->maximum = 1.0;
1582 }
anthony3dd0f622010-05-13 12:57:32 +00001583 break;
1584 }
anthony43c49252010-05-18 10:59:50 +00001585 case EdgesKernel:
1586 {
1587 kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1588 if (kernel == (KernelInfo *) NULL)
1589 return(kernel);
1590 kernel->type = type;
1591 ExpandKernelInfo(kernel, 90.0); /* Create a list of 4 rotated kernels */
1592 break;
1593 }
anthony3dd0f622010-05-13 12:57:32 +00001594 case CornersKernel:
1595 {
anthony4f1dcb72010-05-14 08:43:10 +00001596 kernel=ParseKernelArray("3: 0,0,- 0,1,1 -,1,-");
anthony3dd0f622010-05-13 12:57:32 +00001597 if (kernel == (KernelInfo *) NULL)
1598 return(kernel);
1599 kernel->type = type;
1600 ExpandKernelInfo(kernel, 90.0); /* Create a list of 4 rotated kernels */
1601 break;
1602 }
anthony47f5d062010-05-23 07:47:50 +00001603 case RidgesKernel:
1604 {
anthonya648a302010-05-27 02:14:36 +00001605 kernel=ParseKernelArray("3: 0,1,0 ");
anthony47f5d062010-05-23 07:47:50 +00001606 if (kernel == (KernelInfo *) NULL)
1607 return(kernel);
1608 kernel->type = type;
1609 ExpandKernelInfo(kernel, 45.0); /* 4 rotated kernels (symmetrical) */
1610 break;
1611 }
anthony1d45eb92010-05-25 11:13:23 +00001612 case Ridges2Kernel:
1613 {
1614 KernelInfo
1615 *new_kernel;
1616 kernel=ParseKernelArray("4x1^:0,1,1,0");
1617 if (kernel == (KernelInfo *) NULL)
1618 return(kernel);
1619 kernel->type = type;
1620 ExpandKernelInfo(kernel, 90.0); /* 4 rotated kernels */
anthonya648a302010-05-27 02:14:36 +00001621#if 0
1622 /* 2 pixel diagonaly thick - 4 rotates - not needed? */
anthony1d45eb92010-05-25 11:13:23 +00001623 new_kernel=ParseKernelArray("4x4^:0,-,-,- -,1,-,- -,-,1,- -,-,-,0'");
1624 if (new_kernel == (KernelInfo *) NULL)
1625 return(DestroyKernelInfo(kernel));
1626 new_kernel->type = type;
1627 ExpandKernelInfo(new_kernel, 90.0); /* 4 rotated kernels */
1628 LastKernelInfo(kernel)->next = new_kernel;
anthonya648a302010-05-27 02:14:36 +00001629#endif
1630 /* kernels to find a stepped 'thick' line - 4 rotates * mirror */
1631 /* Unfortunatally we can not yet rotate a non-square kernel */
1632 /* But then we can't flip a non-symetrical kernel either */
1633 new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1634 if (new_kernel == (KernelInfo *) NULL)
1635 return(DestroyKernelInfo(kernel));
1636 new_kernel->type = type;
1637 LastKernelInfo(kernel)->next = new_kernel;
1638 new_kernel=ParseKernelArray("4x3+2+1^:0,1,1,- -,1,1,- -,1,1,0");
1639 if (new_kernel == (KernelInfo *) NULL)
1640 return(DestroyKernelInfo(kernel));
1641 new_kernel->type = type;
1642 LastKernelInfo(kernel)->next = new_kernel;
1643 new_kernel=ParseKernelArray("4x3+1+1^:-,1,1,0 -,1,1,- 0,1,1,-");
1644 if (new_kernel == (KernelInfo *) NULL)
1645 return(DestroyKernelInfo(kernel));
1646 new_kernel->type = type;
1647 LastKernelInfo(kernel)->next = new_kernel;
1648 new_kernel=ParseKernelArray("4x3+2+1^:-,1,1,0 -,1,1,- 0,1,1,-");
1649 if (new_kernel == (KernelInfo *) NULL)
1650 return(DestroyKernelInfo(kernel));
1651 new_kernel->type = type;
1652 LastKernelInfo(kernel)->next = new_kernel;
1653 new_kernel=ParseKernelArray("3x4+1+1^:0,-,- 1,1,1 1,1,1 -,-,0");
1654 if (new_kernel == (KernelInfo *) NULL)
1655 return(DestroyKernelInfo(kernel));
1656 new_kernel->type = type;
1657 LastKernelInfo(kernel)->next = new_kernel;
1658 new_kernel=ParseKernelArray("3x4+1+2^:0,-,- 1,1,1 1,1,1 -,-,0");
1659 if (new_kernel == (KernelInfo *) NULL)
1660 return(DestroyKernelInfo(kernel));
1661 new_kernel->type = type;
1662 LastKernelInfo(kernel)->next = new_kernel;
1663 new_kernel=ParseKernelArray("3x4+1+1^:-,-,0 1,1,1 1,1,1 0,-,-");
1664 if (new_kernel == (KernelInfo *) NULL)
1665 return(DestroyKernelInfo(kernel));
1666 new_kernel->type = type;
1667 LastKernelInfo(kernel)->next = new_kernel;
1668 new_kernel=ParseKernelArray("3x4+1+2^:-,-,0 1,1,1 1,1,1 0,-,-");
1669 if (new_kernel == (KernelInfo *) NULL)
1670 return(DestroyKernelInfo(kernel));
1671 new_kernel->type = type;
1672 LastKernelInfo(kernel)->next = new_kernel;
anthony1d45eb92010-05-25 11:13:23 +00001673 break;
1674 }
anthony3dd0f622010-05-13 12:57:32 +00001675 case LineEndsKernel:
1676 {
anthony43c49252010-05-18 10:59:50 +00001677 KernelInfo
1678 *new_kernel;
1679 kernel=ParseKernelArray("3: 0,0,0 0,1,0 -,1,-");
anthony3dd0f622010-05-13 12:57:32 +00001680 if (kernel == (KernelInfo *) NULL)
1681 return(kernel);
1682 kernel->type = type;
anthony43c49252010-05-18 10:59:50 +00001683 ExpandKernelInfo(kernel, 90.0);
1684 /* append second set of 4 kernels */
1685 new_kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
1686 if (new_kernel == (KernelInfo *) NULL)
1687 return(DestroyKernelInfo(kernel));
1688 new_kernel->type = type;
1689 ExpandKernelInfo(new_kernel, 90.0);
1690 LastKernelInfo(kernel)->next = new_kernel;
anthony3dd0f622010-05-13 12:57:32 +00001691 break;
1692 }
1693 case LineJunctionsKernel:
1694 {
1695 KernelInfo
1696 *new_kernel;
anthony3dd0f622010-05-13 12:57:32 +00001697 /* first set of 4 kernels */
anthony4f1dcb72010-05-14 08:43:10 +00001698 kernel=ParseKernelArray("3: -,1,- -,1,- 1,-,1");
anthony3dd0f622010-05-13 12:57:32 +00001699 if (kernel == (KernelInfo *) NULL)
1700 return(kernel);
1701 kernel->type = type;
anthony43c49252010-05-18 10:59:50 +00001702 ExpandKernelInfo(kernel, 45.0);
anthony3dd0f622010-05-13 12:57:32 +00001703 /* append second set of 4 kernels */
anthony4f1dcb72010-05-14 08:43:10 +00001704 new_kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
anthony3dd0f622010-05-13 12:57:32 +00001705 if (new_kernel == (KernelInfo *) NULL)
1706 return(DestroyKernelInfo(kernel));
anthony43c49252010-05-18 10:59:50 +00001707 new_kernel->type = type;
anthony3dd0f622010-05-13 12:57:32 +00001708 ExpandKernelInfo(new_kernel, 90.0);
1709 LastKernelInfo(kernel)->next = new_kernel;
anthony4f1dcb72010-05-14 08:43:10 +00001710 break;
1711 }
anthony3dd0f622010-05-13 12:57:32 +00001712 case ConvexHullKernel:
1713 {
1714 KernelInfo
1715 *new_kernel;
anthony3dd0f622010-05-13 12:57:32 +00001716 /* first set of 4 kernels */
anthony4f1dcb72010-05-14 08:43:10 +00001717 kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
anthony3dd0f622010-05-13 12:57:32 +00001718 if (kernel == (KernelInfo *) NULL)
1719 return(kernel);
1720 kernel->type = type;
1721 ExpandKernelInfo(kernel, 90.0);
1722 /* append second set of 4 kernels */
anthony43c49252010-05-18 10:59:50 +00001723 new_kernel=ParseKernelArray("3: 1,1,1 1,0,0 -,-,0");
anthony3dd0f622010-05-13 12:57:32 +00001724 if (new_kernel == (KernelInfo *) NULL)
1725 return(DestroyKernelInfo(kernel));
anthony43c49252010-05-18 10:59:50 +00001726 new_kernel->type = type;
anthony3dd0f622010-05-13 12:57:32 +00001727 ExpandKernelInfo(new_kernel, 90.0);
1728 LastKernelInfo(kernel)->next = new_kernel;
1729 break;
1730 }
anthony47f5d062010-05-23 07:47:50 +00001731 case SkeletonKernel:
anthonya648a302010-05-27 02:14:36 +00001732 { /* what is the best form for skeletonization by thinning? */
anthony47f5d062010-05-23 07:47:50 +00001733#if 0
1734# if 0
1735 kernel=AcquireKernelInfo("Corners;Edges");
1736# else
1737 kernel=AcquireKernelInfo("Edges;Corners");
1738# endif
1739#else
anthony43c49252010-05-18 10:59:50 +00001740 kernel=ParseKernelArray("3: 0,0,- 0,1,1 -,1,1");
anthony3dd0f622010-05-13 12:57:32 +00001741 if (kernel == (KernelInfo *) NULL)
1742 return(kernel);
1743 kernel->type = type;
anthony43c49252010-05-18 10:59:50 +00001744 ExpandKernelInfo(kernel, 45);
1745 break;
anthony47f5d062010-05-23 07:47:50 +00001746#endif
anthony3dd0f622010-05-13 12:57:32 +00001747 break;
1748 }
anthonya648a302010-05-27 02:14:36 +00001749 case MatKernel: /* experimental - MAT from a Distance Gradient */
1750 {
1751 KernelInfo
1752 *new_kernel;
1753 /* Ridge Kernel but without the diagonal */
1754 kernel=ParseKernelArray("3x1: 0,1,0");
1755 if (kernel == (KernelInfo *) NULL)
1756 return(kernel);
1757 kernel->type = RidgesKernel;
1758 ExpandKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
1759 /* Plus the 2 pixel ridges kernel - no diagonal */
1760 new_kernel=AcquireKernelBuiltIn(Ridges2Kernel,args);
1761 if (new_kernel == (KernelInfo *) NULL)
1762 return(kernel);
1763 LastKernelInfo(kernel)->next = new_kernel;
1764 break;
1765 }
anthony602ab9b2010-01-05 08:06:50 +00001766 /* Distance Measuring Kernels */
1767 case ChebyshevKernel:
1768 {
anthony602ab9b2010-01-05 08:06:50 +00001769 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001770 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001771 else
1772 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
cristyc99304f2010-02-01 15:26:27 +00001773 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001774
1775 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1776 kernel->height*sizeof(double));
1777 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001778 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001779
cristyc99304f2010-02-01 15:26:27 +00001780 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1781 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1782 kernel->positive_range += ( kernel->values[i] =
anthonyc84dce52010-05-07 05:42:23 +00001783 args->sigma*((labs(u)>labs(v)) ? labs(u) : labs(v)) );
cristyc99304f2010-02-01 15:26:27 +00001784 kernel->maximum = kernel->values[0];
anthony602ab9b2010-01-05 08:06:50 +00001785 break;
1786 }
1787 case ManhattenKernel:
1788 {
anthony602ab9b2010-01-05 08:06:50 +00001789 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001790 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001791 else
1792 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
cristyc99304f2010-02-01 15:26:27 +00001793 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001794
1795 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1796 kernel->height*sizeof(double));
1797 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001798 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001799
cristyc99304f2010-02-01 15:26:27 +00001800 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1801 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1802 kernel->positive_range += ( kernel->values[i] =
anthonyc84dce52010-05-07 05:42:23 +00001803 args->sigma*(labs(u)+labs(v)) );
cristyc99304f2010-02-01 15:26:27 +00001804 kernel->maximum = kernel->values[0];
anthony602ab9b2010-01-05 08:06:50 +00001805 break;
1806 }
1807 case EuclideanKernel:
1808 {
anthony602ab9b2010-01-05 08:06:50 +00001809 if (args->rho < 1.0)
anthonyc94cdb02010-01-06 08:15:29 +00001810 kernel->width = kernel->height = 3; /* default radius = 1 */
anthony602ab9b2010-01-05 08:06:50 +00001811 else
1812 kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
cristyc99304f2010-02-01 15:26:27 +00001813 kernel->x = kernel->y = (long) (kernel->width-1)/2;
anthony602ab9b2010-01-05 08:06:50 +00001814
1815 kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1816 kernel->height*sizeof(double));
1817 if (kernel->values == (double *) NULL)
anthony83ba99b2010-01-24 08:48:15 +00001818 return(DestroyKernelInfo(kernel));
anthony602ab9b2010-01-05 08:06:50 +00001819
cristyc99304f2010-02-01 15:26:27 +00001820 for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
1821 for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1822 kernel->positive_range += ( kernel->values[i] =
anthonyc84dce52010-05-07 05:42:23 +00001823 args->sigma*sqrt((double)(u*u+v*v)) );
cristyc99304f2010-02-01 15:26:27 +00001824 kernel->maximum = kernel->values[0];
anthony602ab9b2010-01-05 08:06:50 +00001825 break;
1826 }
anthony46a369d2010-05-19 02:41:48 +00001827 case UnityKernel:
anthony602ab9b2010-01-05 08:06:50 +00001828 default:
anthonyc1061722010-05-14 06:23:49 +00001829 {
anthony46a369d2010-05-19 02:41:48 +00001830 /* Unity or No-Op Kernel - 3x3 with 1 in center */
1831 kernel=ParseKernelArray("3:0,0,0,0,1,0,0,0,0");
anthonyc1061722010-05-14 06:23:49 +00001832 if (kernel == (KernelInfo *) NULL)
1833 return(kernel);
anthony46a369d2010-05-19 02:41:48 +00001834 kernel->type = ( type == UnityKernel ) ? UnityKernel : UndefinedKernel;
anthonyc1061722010-05-14 06:23:49 +00001835 break;
1836 }
anthony602ab9b2010-01-05 08:06:50 +00001837 break;
1838 }
1839
1840 return(kernel);
1841}
anthonyc94cdb02010-01-06 08:15:29 +00001842
anthony602ab9b2010-01-05 08:06:50 +00001843/*
1844%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1845% %
1846% %
1847% %
cristy6771f1e2010-03-05 19:43:39 +00001848% C l o n e K e r n e l I n f o %
anthony4fd27e22010-02-07 08:17:18 +00001849% %
1850% %
1851% %
1852%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1853%
anthony1b2bc0a2010-05-12 05:25:22 +00001854% CloneKernelInfo() creates a new clone of the given Kernel List so that its
1855% can be modified without effecting the original. The cloned kernel should
1856% be destroyed using DestoryKernelInfo() when no longer needed.
anthony7a01dcf2010-05-11 12:25:52 +00001857%
cristye6365592010-04-02 17:31:23 +00001858% The format of the CloneKernelInfo method is:
anthony4fd27e22010-02-07 08:17:18 +00001859%
anthony930be612010-02-08 04:26:15 +00001860% KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
anthony4fd27e22010-02-07 08:17:18 +00001861%
1862% A description of each parameter follows:
1863%
1864% o kernel: the Morphology/Convolution kernel to be cloned
1865%
1866*/
cristyef656912010-03-05 19:54:59 +00001867MagickExport KernelInfo *CloneKernelInfo(const KernelInfo *kernel)
anthony4fd27e22010-02-07 08:17:18 +00001868{
1869 register long
1870 i;
1871
cristy19eb6412010-04-23 14:42:29 +00001872 KernelInfo
anthony7a01dcf2010-05-11 12:25:52 +00001873 *new_kernel;
anthony4fd27e22010-02-07 08:17:18 +00001874
1875 assert(kernel != (KernelInfo *) NULL);
anthony7a01dcf2010-05-11 12:25:52 +00001876 new_kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
1877 if (new_kernel == (KernelInfo *) NULL)
1878 return(new_kernel);
1879 *new_kernel=(*kernel); /* copy values in structure */
anthony7a01dcf2010-05-11 12:25:52 +00001880
1881 /* replace the values with a copy of the values */
1882 new_kernel->values=(double *) AcquireQuantumMemory(kernel->width,
cristy19eb6412010-04-23 14:42:29 +00001883 kernel->height*sizeof(double));
anthony7a01dcf2010-05-11 12:25:52 +00001884 if (new_kernel->values == (double *) NULL)
1885 return(DestroyKernelInfo(new_kernel));
anthony4fd27e22010-02-07 08:17:18 +00001886 for (i=0; i < (long) (kernel->width*kernel->height); i++)
anthony7a01dcf2010-05-11 12:25:52 +00001887 new_kernel->values[i]=kernel->values[i];
anthony1b2bc0a2010-05-12 05:25:22 +00001888
1889 /* Also clone the next kernel in the kernel list */
1890 if ( kernel->next != (KernelInfo *) NULL ) {
1891 new_kernel->next = CloneKernelInfo(kernel->next);
1892 if ( new_kernel->next == (KernelInfo *) NULL )
1893 return(DestroyKernelInfo(new_kernel));
1894 }
1895
anthony7a01dcf2010-05-11 12:25:52 +00001896 return(new_kernel);
anthony4fd27e22010-02-07 08:17:18 +00001897}
1898
1899/*
1900%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1901% %
1902% %
1903% %
anthony83ba99b2010-01-24 08:48:15 +00001904% D e s t r o y K e r n e l I n f o %
anthony602ab9b2010-01-05 08:06:50 +00001905% %
1906% %
1907% %
1908%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1909%
anthony83ba99b2010-01-24 08:48:15 +00001910% DestroyKernelInfo() frees the memory used by a Convolution/Morphology
1911% kernel.
anthony602ab9b2010-01-05 08:06:50 +00001912%
anthony83ba99b2010-01-24 08:48:15 +00001913% The format of the DestroyKernelInfo method is:
anthony602ab9b2010-01-05 08:06:50 +00001914%
anthony83ba99b2010-01-24 08:48:15 +00001915% KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
anthony602ab9b2010-01-05 08:06:50 +00001916%
1917% A description of each parameter follows:
1918%
1919% o kernel: the Morphology/Convolution kernel to be destroyed
1920%
1921*/
1922
anthony83ba99b2010-01-24 08:48:15 +00001923MagickExport KernelInfo *DestroyKernelInfo(KernelInfo *kernel)
anthony602ab9b2010-01-05 08:06:50 +00001924{
cristy2be15382010-01-21 02:38:03 +00001925 assert(kernel != (KernelInfo *) NULL);
anthony4fd27e22010-02-07 08:17:18 +00001926
anthony7a01dcf2010-05-11 12:25:52 +00001927 if ( kernel->next != (KernelInfo *) NULL )
1928 kernel->next = DestroyKernelInfo(kernel->next);
1929
1930 kernel->values = (double *)RelinquishMagickMemory(kernel->values);
1931 kernel = (KernelInfo *) RelinquishMagickMemory(kernel);
anthony602ab9b2010-01-05 08:06:50 +00001932 return(kernel);
1933}
anthonyc94cdb02010-01-06 08:15:29 +00001934
1935/*
1936%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1937% %
1938% %
1939% %
anthony3c10fc82010-05-13 02:40:51 +00001940% E x p a n d K e r n e l I n f o %
1941% %
1942% %
1943% %
1944%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1945%
1946% ExpandKernelInfo() takes a single kernel, and expands it into a list
1947% of kernels each incrementally rotated the angle given.
1948%
1949% WARNING: 45 degree rotations only works for 3x3 kernels.
1950% While 90 degree roatations only works for linear and square kernels
1951%
1952% The format of the RotateKernelInfo method is:
1953%
1954% void ExpandKernelInfo(KernelInfo *kernel, double angle)
1955%
1956% A description of each parameter follows:
1957%
1958% o kernel: the Morphology/Convolution kernel
1959%
1960% o angle: angle to rotate in degrees
1961%
1962% This function is only internel to this module, as it is not finalized,
1963% especially with regard to non-orthogonal angles, and rotation of larger
1964% 2D kernels.
1965*/
anthony47f5d062010-05-23 07:47:50 +00001966
1967/* Internal Routine - Return true if two kernels are the same */
1968static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
1969 const KernelInfo *kernel2)
1970{
1971 register unsigned long
1972 i;
anthony1d45eb92010-05-25 11:13:23 +00001973
1974 /* check size and origin location */
1975 if ( kernel1->width != kernel2->width
1976 || kernel1->height != kernel2->height
1977 || kernel1->x != kernel2->x
1978 || kernel1->y != kernel2->y )
anthony47f5d062010-05-23 07:47:50 +00001979 return MagickFalse;
anthony1d45eb92010-05-25 11:13:23 +00001980
1981 /* check actual kernel values */
anthony47f5d062010-05-23 07:47:50 +00001982 for (i=0; i < (kernel1->width*kernel1->height); i++) {
anthony1d45eb92010-05-25 11:13:23 +00001983 /* Test for Nan equivelence */
anthony47f5d062010-05-23 07:47:50 +00001984 if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
1985 return MagickFalse;
1986 if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
1987 return MagickFalse;
anthony1d45eb92010-05-25 11:13:23 +00001988 /* Test actual values are equivelent */
anthony47f5d062010-05-23 07:47:50 +00001989 if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
1990 return MagickFalse;
1991 }
anthony1d45eb92010-05-25 11:13:23 +00001992
anthony47f5d062010-05-23 07:47:50 +00001993 return MagickTrue;
1994}
1995
1996static void ExpandKernelInfo(KernelInfo *kernel, const double angle)
anthony3c10fc82010-05-13 02:40:51 +00001997{
1998 KernelInfo
cristy84d9b552010-05-24 18:23:54 +00001999 *clone,
anthony3c10fc82010-05-13 02:40:51 +00002000 *last;
cristya9a61ad2010-05-13 12:47:41 +00002001
anthony3c10fc82010-05-13 02:40:51 +00002002 last = kernel;
anthony47f5d062010-05-23 07:47:50 +00002003 while(1) {
cristy84d9b552010-05-24 18:23:54 +00002004 clone = CloneKernelInfo(last);
2005 RotateKernelInfo(clone, angle);
2006 if ( SameKernelInfo(kernel, clone) == MagickTrue )
anthony47f5d062010-05-23 07:47:50 +00002007 break;
cristy84d9b552010-05-24 18:23:54 +00002008 last->next = clone;
2009 last = clone;
anthony3c10fc82010-05-13 02:40:51 +00002010 }
cristy84d9b552010-05-24 18:23:54 +00002011 clone = DestroyKernelInfo(clone); /* This was the same as the first - junk */
anthony47f5d062010-05-23 07:47:50 +00002012 return;
anthony3c10fc82010-05-13 02:40:51 +00002013}
2014
2015/*
2016%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2017% %
2018% %
2019% %
anthony46a369d2010-05-19 02:41:48 +00002020+ C a l c M e t a K e r n a l I n f o %
2021% %
2022% %
2023% %
2024%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2025%
2026% CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2027% using the kernel values. This should only ne used if it is not posible to
2028% calculate that meta-data in some easier way.
2029%
2030% It is important that the meta-data is correct before ScaleKernelInfo() is
2031% used to perform kernel normalization.
2032%
2033% The format of the CalcKernelMetaData method is:
2034%
2035% void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2036%
2037% A description of each parameter follows:
2038%
2039% o kernel: the Morphology/Convolution kernel to modify
2040%
2041% WARNING: Minimum and Maximum values are assumed to include zero, even if
2042% zero is not part of the kernel (as in Gaussian Derived kernels). This
2043% however is not true for flat-shaped morphological kernels.
2044%
2045% WARNING: Only the specific kernel pointed to is modified, not a list of
2046% multiple kernels.
2047%
2048% This is an internal function and not expected to be useful outside this
2049% module. This could change however.
2050*/
2051static void CalcKernelMetaData(KernelInfo *kernel)
2052{
2053 register unsigned long
2054 i;
2055
2056 kernel->minimum = kernel->maximum = 0.0;
2057 kernel->negative_range = kernel->positive_range = 0.0;
2058 for (i=0; i < (kernel->width*kernel->height); i++)
2059 {
2060 if ( fabs(kernel->values[i]) < MagickEpsilon )
2061 kernel->values[i] = 0.0;
2062 ( kernel->values[i] < 0)
2063 ? ( kernel->negative_range += kernel->values[i] )
2064 : ( kernel->positive_range += kernel->values[i] );
2065 Minimize(kernel->minimum, kernel->values[i]);
2066 Maximize(kernel->maximum, kernel->values[i]);
2067 }
2068
2069 return;
2070}
2071
2072/*
2073%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2074% %
2075% %
2076% %
anthony9eb4f742010-05-18 02:45:54 +00002077% M o r p h o l o g y A p p l y %
anthony602ab9b2010-01-05 08:06:50 +00002078% %
2079% %
2080% %
2081%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2082%
anthony9eb4f742010-05-18 02:45:54 +00002083% MorphologyApply() applies a morphological method, multiple times using
2084% a list of multiple kernels.
anthony602ab9b2010-01-05 08:06:50 +00002085%
anthony9eb4f742010-05-18 02:45:54 +00002086% It is basically equivelent to as MorphologyImageChannel() (see below) but
2087% without user controls, that that function extracts and applies to kernels
2088% and morphology methods.
2089%
2090% More specifically kernels are not normalized/scaled/blended by the
2091% 'convolve:scale' Image Artifact (-set setting), and the convolve bias
2092% (-bias setting or image->bias) is passed directly to this function,
2093% and not extracted from an image.
anthony602ab9b2010-01-05 08:06:50 +00002094%
anthony47f5d062010-05-23 07:47:50 +00002095% The format of the MorphologyApply method is:
anthony602ab9b2010-01-05 08:06:50 +00002096%
anthony9eb4f742010-05-18 02:45:54 +00002097% Image *MorphologyApply(const Image *image,MorphologyMethod method,
anthony47f5d062010-05-23 07:47:50 +00002098% const long iterations,const KernelInfo *kernel,
2099% const CompositeMethod compose, const double bias,
anthony9eb4f742010-05-18 02:45:54 +00002100% ExceptionInfo *exception)
anthony602ab9b2010-01-05 08:06:50 +00002101%
2102% A description of each parameter follows:
2103%
2104% o image: the image.
2105%
2106% o method: the morphology method to be applied.
2107%
2108% o iterations: apply the operation this many times (or no change).
2109% A value of -1 means loop until no change found.
2110% How this is applied may depend on the morphology method.
2111% Typically this is a value of 1.
2112%
2113% o channel: the channel type.
2114%
2115% o kernel: An array of double representing the morphology kernel.
anthony29188a82010-01-22 10:12:34 +00002116% Warning: kernel may be normalized for the Convolve method.
anthony602ab9b2010-01-05 08:06:50 +00002117%
anthony47f5d062010-05-23 07:47:50 +00002118% o compose: How to handle or merge multi-kernel results.
2119% If 'Undefined' use default of the Morphology method.
2120% If 'No' force image to be re-iterated by each kernel.
2121% Otherwise merge the results using the mathematical compose
2122% method given.
2123%
2124% o bias: Convolution Output Bias.
anthony9eb4f742010-05-18 02:45:54 +00002125%
anthony602ab9b2010-01-05 08:06:50 +00002126% o exception: return any errors or warnings in this structure.
2127%
anthony602ab9b2010-01-05 08:06:50 +00002128*/
2129
anthony930be612010-02-08 04:26:15 +00002130
anthony9eb4f742010-05-18 02:45:54 +00002131/* Apply a Morphology Primative to an image using the given kernel.
2132** Two pre-created images must be provided, no image is created.
2133** Returning the number of pixels that changed.
2134*/
anthony46a369d2010-05-19 02:41:48 +00002135static unsigned long MorphologyPrimitive(const Image *image, Image
anthony602ab9b2010-01-05 08:06:50 +00002136 *result_image, const MorphologyMethod method, const ChannelType channel,
anthony9eb4f742010-05-18 02:45:54 +00002137 const KernelInfo *kernel,const double bias,ExceptionInfo *exception)
anthony602ab9b2010-01-05 08:06:50 +00002138{
cristy2be15382010-01-21 02:38:03 +00002139#define MorphologyTag "Morphology/Image"
anthony602ab9b2010-01-05 08:06:50 +00002140
2141 long
cristy150989e2010-02-01 14:59:39 +00002142 progress,
anthony29188a82010-01-22 10:12:34 +00002143 y, offx, offy,
anthony602ab9b2010-01-05 08:06:50 +00002144 changed;
2145
2146 MagickBooleanType
2147 status;
2148
anthony602ab9b2010-01-05 08:06:50 +00002149 CacheView
2150 *p_view,
2151 *q_view;
2152
anthony602ab9b2010-01-05 08:06:50 +00002153 status=MagickTrue;
2154 changed=0;
2155 progress=0;
2156
anthony602ab9b2010-01-05 08:06:50 +00002157 p_view=AcquireCacheView(image);
2158 q_view=AcquireCacheView(result_image);
anthony29188a82010-01-22 10:12:34 +00002159
anthonycc6c8362010-01-25 04:14:01 +00002160 /* Some methods (including convolve) needs use a reflected kernel.
anthony9eb4f742010-05-18 02:45:54 +00002161 * Adjust 'origin' offsets to loop though kernel as a reflection.
anthony29188a82010-01-22 10:12:34 +00002162 */
cristyc99304f2010-02-01 15:26:27 +00002163 offx = kernel->x;
2164 offy = kernel->y;
anthony29188a82010-01-22 10:12:34 +00002165 switch(method) {
anthony930be612010-02-08 04:26:15 +00002166 case ConvolveMorphology:
2167 case DilateMorphology:
2168 case DilateIntensityMorphology:
2169 case DistanceMorphology:
anthony5ef8e942010-05-11 06:51:12 +00002170 /* kernel needs to used with reflection about origin */
cristy150989e2010-02-01 14:59:39 +00002171 offx = (long) kernel->width-offx-1;
2172 offy = (long) kernel->height-offy-1;
anthony29188a82010-01-22 10:12:34 +00002173 break;
anthony5ef8e942010-05-11 06:51:12 +00002174 case ErodeMorphology:
2175 case ErodeIntensityMorphology:
2176 case HitAndMissMorphology:
2177 case ThinningMorphology:
2178 case ThickenMorphology:
2179 /* kernel is user as is, without reflection */
2180 break;
anthony930be612010-02-08 04:26:15 +00002181 default:
anthony9eb4f742010-05-18 02:45:54 +00002182 assert("Not a Primitive Morphology Method" != (char *) NULL);
anthony930be612010-02-08 04:26:15 +00002183 break;
anthony29188a82010-01-22 10:12:34 +00002184 }
2185
anthony602ab9b2010-01-05 08:06:50 +00002186#if defined(MAGICKCORE_OPENMP_SUPPORT)
2187 #pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2188#endif
cristy150989e2010-02-01 14:59:39 +00002189 for (y=0; y < (long) image->rows; y++)
anthony602ab9b2010-01-05 08:06:50 +00002190 {
2191 MagickBooleanType
2192 sync;
2193
2194 register const PixelPacket
2195 *restrict p;
2196
2197 register const IndexPacket
2198 *restrict p_indexes;
2199
2200 register PixelPacket
2201 *restrict q;
2202
2203 register IndexPacket
2204 *restrict q_indexes;
2205
cristy150989e2010-02-01 14:59:39 +00002206 register long
anthony602ab9b2010-01-05 08:06:50 +00002207 x;
2208
anthony29188a82010-01-22 10:12:34 +00002209 unsigned long
anthony602ab9b2010-01-05 08:06:50 +00002210 r;
2211
2212 if (status == MagickFalse)
2213 continue;
anthony29188a82010-01-22 10:12:34 +00002214 p=GetCacheViewVirtualPixels(p_view, -offx, y-offy,
2215 image->columns+kernel->width, kernel->height, exception);
anthony602ab9b2010-01-05 08:06:50 +00002216 q=GetCacheViewAuthenticPixels(q_view,0,y,result_image->columns,1,
2217 exception);
2218 if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
2219 {
2220 status=MagickFalse;
2221 continue;
2222 }
2223 p_indexes=GetCacheViewVirtualIndexQueue(p_view);
2224 q_indexes=GetCacheViewAuthenticIndexQueue(q_view);
anthony29188a82010-01-22 10:12:34 +00002225 r = (image->columns+kernel->width)*offy+offx; /* constant */
2226
cristy150989e2010-02-01 14:59:39 +00002227 for (x=0; x < (long) image->columns; x++)
anthony602ab9b2010-01-05 08:06:50 +00002228 {
cristy150989e2010-02-01 14:59:39 +00002229 long
anthony602ab9b2010-01-05 08:06:50 +00002230 v;
2231
cristy150989e2010-02-01 14:59:39 +00002232 register long
anthony602ab9b2010-01-05 08:06:50 +00002233 u;
2234
2235 register const double
2236 *restrict k;
2237
2238 register const PixelPacket
2239 *restrict k_pixels;
2240
2241 register const IndexPacket
2242 *restrict k_indexes;
2243
2244 MagickPixelPacket
anthony5ef8e942010-05-11 06:51:12 +00002245 result,
2246 min,
2247 max;
anthony602ab9b2010-01-05 08:06:50 +00002248
anthony29188a82010-01-22 10:12:34 +00002249 /* Copy input to ouput image for unused channels
anthony83ba99b2010-01-24 08:48:15 +00002250 * This removes need for 'cloning' a new image every iteration
anthony29188a82010-01-22 10:12:34 +00002251 */
anthony602ab9b2010-01-05 08:06:50 +00002252 *q = p[r];
2253 if (image->colorspace == CMYKColorspace)
2254 q_indexes[x] = p_indexes[r];
2255
anthony5ef8e942010-05-11 06:51:12 +00002256 /* Defaults */
2257 min.red =
2258 min.green =
2259 min.blue =
2260 min.opacity =
2261 min.index = (MagickRealType) QuantumRange;
2262 max.red =
2263 max.green =
2264 max.blue =
2265 max.opacity =
2266 max.index = (MagickRealType) 0;
anthony9eb4f742010-05-18 02:45:54 +00002267 /* default result is the original pixel value */
anthony5ef8e942010-05-11 06:51:12 +00002268 result.red = (MagickRealType) p[r].red;
2269 result.green = (MagickRealType) p[r].green;
2270 result.blue = (MagickRealType) p[r].blue;
2271 result.opacity = QuantumRange - (MagickRealType) p[r].opacity;
cristye96405a2010-05-19 02:24:31 +00002272 result.index = 0.0;
anthony5ef8e942010-05-11 06:51:12 +00002273 if ( image->colorspace == CMYKColorspace)
2274 result.index = (MagickRealType) p_indexes[r];
2275
anthony602ab9b2010-01-05 08:06:50 +00002276 switch (method) {
2277 case ConvolveMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002278 /* Set the user defined bias of the weighted average output */
2279 result.red =
2280 result.green =
2281 result.blue =
2282 result.opacity =
2283 result.index = bias;
anthony930be612010-02-08 04:26:15 +00002284 break;
anthony4fd27e22010-02-07 08:17:18 +00002285 case DilateIntensityMorphology:
2286 case ErodeIntensityMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002287 /* use a boolean flag indicating when first match found */
2288 result.red = 0.0; /* result is not used otherwise */
anthony4fd27e22010-02-07 08:17:18 +00002289 break;
anthony602ab9b2010-01-05 08:06:50 +00002290 default:
anthony602ab9b2010-01-05 08:06:50 +00002291 break;
2292 }
2293
2294 switch ( method ) {
2295 case ConvolveMorphology:
anthony930be612010-02-08 04:26:15 +00002296 /* Weighted Average of pixels using reflected kernel
2297 **
2298 ** NOTE for correct working of this operation for asymetrical
2299 ** kernels, the kernel needs to be applied in its reflected form.
2300 ** That is its values needs to be reversed.
2301 **
2302 ** Correlation is actually the same as this but without reflecting
2303 ** the kernel, and thus 'lower-level' that Convolution. However
2304 ** as Convolution is the more common method used, and it does not
2305 ** really cost us much in terms of processing to use a reflected
anthony5ef8e942010-05-11 06:51:12 +00002306 ** kernel, so it is Convolution that is implemented.
anthony930be612010-02-08 04:26:15 +00002307 **
2308 ** Correlation will have its kernel reflected before calling
2309 ** this function to do a Convolve.
2310 **
2311 ** For more details of Correlation vs Convolution see
2312 ** http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf
2313 */
anthony5ef8e942010-05-11 06:51:12 +00002314 if (((channel & SyncChannels) != 0 ) &&
2315 (image->matte == MagickTrue))
2316 { /* Channel has a 'Sync' Flag, and Alpha Channel enabled.
2317 ** Weight the color channels with Alpha Channel so that
2318 ** transparent pixels are not part of the results.
2319 */
anthony602ab9b2010-01-05 08:06:50 +00002320 MagickRealType
anthony5ef8e942010-05-11 06:51:12 +00002321 alpha, /* color channel weighting : kernel*alpha */
2322 gamma; /* divisor, sum of weighting values */
anthony602ab9b2010-01-05 08:06:50 +00002323
2324 gamma=0.0;
anthony29188a82010-01-22 10:12:34 +00002325 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002326 k_pixels = p;
2327 k_indexes = p_indexes;
cristy150989e2010-02-01 14:59:39 +00002328 for (v=0; v < (long) kernel->height; v++) {
2329 for (u=0; u < (long) kernel->width; u++, k--) {
anthony602ab9b2010-01-05 08:06:50 +00002330 if ( IsNan(*k) ) continue;
2331 alpha=(*k)*(QuantumScale*(QuantumRange-
2332 k_pixels[u].opacity));
2333 gamma += alpha;
2334 result.red += alpha*k_pixels[u].red;
2335 result.green += alpha*k_pixels[u].green;
2336 result.blue += alpha*k_pixels[u].blue;
anthony83ba99b2010-01-24 08:48:15 +00002337 result.opacity += (*k)*(QuantumRange-k_pixels[u].opacity);
anthony602ab9b2010-01-05 08:06:50 +00002338 if ( image->colorspace == CMYKColorspace)
2339 result.index += alpha*k_indexes[u];
2340 }
2341 k_pixels += image->columns+kernel->width;
2342 k_indexes += image->columns+kernel->width;
2343 }
2344 gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
anthony83ba99b2010-01-24 08:48:15 +00002345 result.red *= gamma;
2346 result.green *= gamma;
2347 result.blue *= gamma;
2348 result.opacity *= gamma;
2349 result.index *= gamma;
anthony602ab9b2010-01-05 08:06:50 +00002350 }
anthony5ef8e942010-05-11 06:51:12 +00002351 else
2352 {
2353 /* No 'Sync' flag, or no Alpha involved.
2354 ** Convolution is simple individual channel weigthed sum.
2355 */
2356 k = &kernel->values[ kernel->width*kernel->height-1 ];
2357 k_pixels = p;
2358 k_indexes = p_indexes;
2359 for (v=0; v < (long) kernel->height; v++) {
2360 for (u=0; u < (long) kernel->width; u++, k--) {
2361 if ( IsNan(*k) ) continue;
2362 result.red += (*k)*k_pixels[u].red;
2363 result.green += (*k)*k_pixels[u].green;
2364 result.blue += (*k)*k_pixels[u].blue;
2365 result.opacity += (*k)*(QuantumRange-k_pixels[u].opacity);
2366 if ( image->colorspace == CMYKColorspace)
2367 result.index += (*k)*k_indexes[u];
2368 }
2369 k_pixels += image->columns+kernel->width;
2370 k_indexes += image->columns+kernel->width;
2371 }
2372 }
anthony602ab9b2010-01-05 08:06:50 +00002373 break;
2374
anthony4fd27e22010-02-07 08:17:18 +00002375 case ErodeMorphology:
anthony5ef8e942010-05-11 06:51:12 +00002376 /* Minimum Value within kernel neighbourhood
anthony930be612010-02-08 04:26:15 +00002377 **
2378 ** NOTE that the kernel is not reflected for this operation!
2379 **
2380 ** NOTE: in normal Greyscale Morphology, the kernel value should
2381 ** be added to the real value, this is currently not done, due to
2382 ** the nature of the boolean kernels being used.
2383 */
anthony4fd27e22010-02-07 08:17:18 +00002384 k = kernel->values;
2385 k_pixels = p;
2386 k_indexes = p_indexes;
2387 for (v=0; v < (long) kernel->height; v++) {
2388 for (u=0; u < (long) kernel->width; u++, k++) {
2389 if ( IsNan(*k) || (*k) < 0.5 ) continue;
anthony5ef8e942010-05-11 06:51:12 +00002390 Minimize(min.red, (double) k_pixels[u].red);
2391 Minimize(min.green, (double) k_pixels[u].green);
2392 Minimize(min.blue, (double) k_pixels[u].blue);
2393 Minimize(min.opacity,
anthonyd37a5cb2010-05-07 06:37:03 +00002394 QuantumRange-(double) k_pixels[u].opacity);
anthony4fd27e22010-02-07 08:17:18 +00002395 if ( image->colorspace == CMYKColorspace)
anthony5ef8e942010-05-11 06:51:12 +00002396 Minimize(min.index, (double) k_indexes[u]);
anthony4fd27e22010-02-07 08:17:18 +00002397 }
2398 k_pixels += image->columns+kernel->width;
2399 k_indexes += image->columns+kernel->width;
2400 }
2401 break;
2402
anthony5ef8e942010-05-11 06:51:12 +00002403
anthony83ba99b2010-01-24 08:48:15 +00002404 case DilateMorphology:
anthony5ef8e942010-05-11 06:51:12 +00002405 /* Maximum Value within kernel neighbourhood
anthony930be612010-02-08 04:26:15 +00002406 **
2407 ** NOTE for correct working of this operation for asymetrical
2408 ** kernels, the kernel needs to be applied in its reflected form.
2409 ** That is its values needs to be reversed.
2410 **
2411 ** NOTE: in normal Greyscale Morphology, the kernel value should
2412 ** be added to the real value, this is currently not done, due to
2413 ** the nature of the boolean kernels being used.
2414 **
2415 */
anthony29188a82010-01-22 10:12:34 +00002416 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002417 k_pixels = p;
2418 k_indexes = p_indexes;
cristy150989e2010-02-01 14:59:39 +00002419 for (v=0; v < (long) kernel->height; v++) {
2420 for (u=0; u < (long) kernel->width; u++, k--) {
anthony602ab9b2010-01-05 08:06:50 +00002421 if ( IsNan(*k) || (*k) < 0.5 ) continue;
anthony5ef8e942010-05-11 06:51:12 +00002422 Maximize(max.red, (double) k_pixels[u].red);
2423 Maximize(max.green, (double) k_pixels[u].green);
2424 Maximize(max.blue, (double) k_pixels[u].blue);
2425 Maximize(max.opacity,
anthonyd37a5cb2010-05-07 06:37:03 +00002426 QuantumRange-(double) k_pixels[u].opacity);
anthony602ab9b2010-01-05 08:06:50 +00002427 if ( image->colorspace == CMYKColorspace)
anthony5ef8e942010-05-11 06:51:12 +00002428 Maximize(max.index, (double) k_indexes[u]);
anthony602ab9b2010-01-05 08:06:50 +00002429 }
2430 k_pixels += image->columns+kernel->width;
2431 k_indexes += image->columns+kernel->width;
2432 }
anthony602ab9b2010-01-05 08:06:50 +00002433 break;
2434
anthony5ef8e942010-05-11 06:51:12 +00002435 case HitAndMissMorphology:
2436 case ThinningMorphology:
2437 case ThickenMorphology:
2438 /* Minimum of Foreground Pixel minus Maxumum of Background Pixels
2439 **
2440 ** NOTE that the kernel is not reflected for this operation,
2441 ** and consists of both foreground and background pixel
2442 ** neighbourhoods, 0.0 for background, and 1.0 for foreground
2443 ** with either Nan or 0.5 values for don't care.
2444 **
2445 ** Note that this can produce negative results, though really
2446 ** only a positive match has any real value.
2447 */
2448 k = kernel->values;
2449 k_pixels = p;
2450 k_indexes = p_indexes;
2451 for (v=0; v < (long) kernel->height; v++) {
2452 for (u=0; u < (long) kernel->width; u++, k++) {
2453 if ( IsNan(*k) ) continue;
2454 if ( (*k) > 0.7 )
2455 { /* minimim of foreground pixels */
2456 Minimize(min.red, (double) k_pixels[u].red);
2457 Minimize(min.green, (double) k_pixels[u].green);
2458 Minimize(min.blue, (double) k_pixels[u].blue);
2459 Minimize(min.opacity,
2460 QuantumRange-(double) k_pixels[u].opacity);
2461 if ( image->colorspace == CMYKColorspace)
2462 Minimize(min.index, (double) k_indexes[u]);
2463 }
2464 else if ( (*k) < 0.3 )
2465 { /* maximum of background pixels */
2466 Maximize(max.red, (double) k_pixels[u].red);
2467 Maximize(max.green, (double) k_pixels[u].green);
2468 Maximize(max.blue, (double) k_pixels[u].blue);
2469 Maximize(max.opacity,
2470 QuantumRange-(double) k_pixels[u].opacity);
2471 if ( image->colorspace == CMYKColorspace)
2472 Maximize(max.index, (double) k_indexes[u]);
2473 }
2474 }
2475 k_pixels += image->columns+kernel->width;
2476 k_indexes += image->columns+kernel->width;
2477 }
2478 /* Pattern Match only if min fg larger than min bg pixels */
2479 min.red -= max.red; Maximize( min.red, 0.0 );
2480 min.green -= max.green; Maximize( min.green, 0.0 );
2481 min.blue -= max.blue; Maximize( min.blue, 0.0 );
2482 min.opacity -= max.opacity; Maximize( min.opacity, 0.0 );
2483 min.index -= max.index; Maximize( min.index, 0.0 );
2484 break;
2485
anthony4fd27e22010-02-07 08:17:18 +00002486 case ErodeIntensityMorphology:
anthony930be612010-02-08 04:26:15 +00002487 /* Select Pixel with Minimum Intensity within kernel neighbourhood
2488 **
2489 ** WARNING: the intensity test fails for CMYK and does not
2490 ** take into account the moderating effect of teh alpha channel
2491 ** on the intensity.
2492 **
2493 ** NOTE that the kernel is not reflected for this operation!
2494 */
anthony602ab9b2010-01-05 08:06:50 +00002495 k = kernel->values;
2496 k_pixels = p;
2497 k_indexes = p_indexes;
cristy150989e2010-02-01 14:59:39 +00002498 for (v=0; v < (long) kernel->height; v++) {
2499 for (u=0; u < (long) kernel->width; u++, k++) {
anthony602ab9b2010-01-05 08:06:50 +00002500 if ( IsNan(*k) || (*k) < 0.5 ) continue;
anthony4fd27e22010-02-07 08:17:18 +00002501 if ( result.red == 0.0 ||
2502 PixelIntensity(&(k_pixels[u])) < PixelIntensity(q) ) {
2503 /* copy the whole pixel - no channel selection */
2504 *q = k_pixels[u];
2505 if ( result.red > 0.0 ) changed++;
2506 result.red = 1.0;
2507 }
anthony602ab9b2010-01-05 08:06:50 +00002508 }
2509 k_pixels += image->columns+kernel->width;
2510 k_indexes += image->columns+kernel->width;
2511 }
anthony602ab9b2010-01-05 08:06:50 +00002512 break;
2513
anthony83ba99b2010-01-24 08:48:15 +00002514 case DilateIntensityMorphology:
anthony930be612010-02-08 04:26:15 +00002515 /* Select Pixel with Maximum Intensity within kernel neighbourhood
2516 **
2517 ** WARNING: the intensity test fails for CMYK and does not
anthony9eb4f742010-05-18 02:45:54 +00002518 ** take into account the moderating effect of the alpha channel
2519 ** on the intensity (yet).
anthony930be612010-02-08 04:26:15 +00002520 **
2521 ** NOTE for correct working of this operation for asymetrical
2522 ** kernels, the kernel needs to be applied in its reflected form.
2523 ** That is its values needs to be reversed.
2524 */
anthony29188a82010-01-22 10:12:34 +00002525 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002526 k_pixels = p;
2527 k_indexes = p_indexes;
cristy150989e2010-02-01 14:59:39 +00002528 for (v=0; v < (long) kernel->height; v++) {
2529 for (u=0; u < (long) kernel->width; u++, k--) {
anthony29188a82010-01-22 10:12:34 +00002530 if ( IsNan(*k) || (*k) < 0.5 ) continue; /* boolean kernel */
2531 if ( result.red == 0.0 ||
2532 PixelIntensity(&(k_pixels[u])) > PixelIntensity(q) ) {
2533 /* copy the whole pixel - no channel selection */
2534 *q = k_pixels[u];
2535 if ( result.red > 0.0 ) changed++;
2536 result.red = 1.0;
2537 }
anthony602ab9b2010-01-05 08:06:50 +00002538 }
2539 k_pixels += image->columns+kernel->width;
2540 k_indexes += image->columns+kernel->width;
2541 }
anthony602ab9b2010-01-05 08:06:50 +00002542 break;
2543
anthony5ef8e942010-05-11 06:51:12 +00002544
anthony602ab9b2010-01-05 08:06:50 +00002545 case DistanceMorphology:
anthony930be612010-02-08 04:26:15 +00002546 /* Add kernel Value and select the minimum value found.
2547 ** The result is a iterative distance from edge of image shape.
2548 **
2549 ** All Distance Kernels are symetrical, but that may not always
2550 ** be the case. For example how about a distance from left edges?
2551 ** To work correctly with asymetrical kernels the reflected kernel
2552 ** needs to be applied.
anthony5ef8e942010-05-11 06:51:12 +00002553 **
2554 ** Actually this is really a GreyErode with a negative kernel!
2555 **
anthony930be612010-02-08 04:26:15 +00002556 */
anthony29188a82010-01-22 10:12:34 +00002557 k = &kernel->values[ kernel->width*kernel->height-1 ];
anthony602ab9b2010-01-05 08:06:50 +00002558 k_pixels = p;
2559 k_indexes = p_indexes;
cristy150989e2010-02-01 14:59:39 +00002560 for (v=0; v < (long) kernel->height; v++) {
2561 for (u=0; u < (long) kernel->width; u++, k--) {
anthony602ab9b2010-01-05 08:06:50 +00002562 if ( IsNan(*k) ) continue;
2563 Minimize(result.red, (*k)+k_pixels[u].red);
2564 Minimize(result.green, (*k)+k_pixels[u].green);
2565 Minimize(result.blue, (*k)+k_pixels[u].blue);
2566 Minimize(result.opacity, (*k)+QuantumRange-k_pixels[u].opacity);
2567 if ( image->colorspace == CMYKColorspace)
2568 Minimize(result.index, (*k)+k_indexes[u]);
2569 }
2570 k_pixels += image->columns+kernel->width;
2571 k_indexes += image->columns+kernel->width;
2572 }
anthony602ab9b2010-01-05 08:06:50 +00002573 break;
2574
2575 case UndefinedMorphology:
2576 default:
2577 break; /* Do nothing */
anthony83ba99b2010-01-24 08:48:15 +00002578 }
anthony5ef8e942010-05-11 06:51:12 +00002579 /* Final mathematics of results (combine with original image?)
2580 **
2581 ** NOTE: Difference Morphology operators Edge* and *Hat could also
2582 ** be done here but works better with iteration as a image difference
2583 ** in the controling function (below). Thicken and Thinning however
2584 ** should be done here so thay can be iterated correctly.
2585 */
2586 switch ( method ) {
2587 case HitAndMissMorphology:
2588 case ErodeMorphology:
2589 result = min; /* minimum of neighbourhood */
2590 break;
2591 case DilateMorphology:
2592 result = max; /* maximum of neighbourhood */
2593 break;
2594 case ThinningMorphology:
2595 /* subtract pattern match from original */
2596 result.red -= min.red;
2597 result.green -= min.green;
2598 result.blue -= min.blue;
2599 result.opacity -= min.opacity;
2600 result.index -= min.index;
2601 break;
2602 case ThickenMorphology:
2603 /* Union with original image (maximize) - or should this be + */
2604 Maximize( result.red, min.red );
2605 Maximize( result.green, min.green );
2606 Maximize( result.blue, min.blue );
2607 Maximize( result.opacity, min.opacity );
2608 Maximize( result.index, min.index );
2609 break;
2610 default:
2611 /* result directly calculated or assigned */
2612 break;
2613 }
2614 /* Assign the resulting pixel values - Clamping Result */
anthony83ba99b2010-01-24 08:48:15 +00002615 switch ( method ) {
2616 case UndefinedMorphology:
2617 case DilateIntensityMorphology:
2618 case ErodeIntensityMorphology:
anthony930be612010-02-08 04:26:15 +00002619 break; /* full pixel was directly assigned - not a channel method */
anthony83ba99b2010-01-24 08:48:15 +00002620 default:
anthony83ba99b2010-01-24 08:48:15 +00002621 if ((channel & RedChannel) != 0)
2622 q->red = ClampToQuantum(result.red);
2623 if ((channel & GreenChannel) != 0)
2624 q->green = ClampToQuantum(result.green);
2625 if ((channel & BlueChannel) != 0)
2626 q->blue = ClampToQuantum(result.blue);
2627 if ((channel & OpacityChannel) != 0
2628 && image->matte == MagickTrue )
2629 q->opacity = ClampToQuantum(QuantumRange-result.opacity);
2630 if ((channel & IndexChannel) != 0
2631 && image->colorspace == CMYKColorspace)
2632 q_indexes[x] = ClampToQuantum(result.index);
2633 break;
2634 }
anthony5ef8e942010-05-11 06:51:12 +00002635 /* Count up changed pixels */
anthony83ba99b2010-01-24 08:48:15 +00002636 if ( ( p[r].red != q->red )
2637 || ( p[r].green != q->green )
2638 || ( p[r].blue != q->blue )
2639 || ( p[r].opacity != q->opacity )
2640 || ( image->colorspace == CMYKColorspace &&
2641 p_indexes[r] != q_indexes[x] ) )
2642 changed++; /* The pixel had some value changed! */
anthony602ab9b2010-01-05 08:06:50 +00002643 p++;
2644 q++;
anthony83ba99b2010-01-24 08:48:15 +00002645 } /* x */
anthony602ab9b2010-01-05 08:06:50 +00002646 sync=SyncCacheViewAuthenticPixels(q_view,exception);
2647 if (sync == MagickFalse)
2648 status=MagickFalse;
2649 if (image->progress_monitor != (MagickProgressMonitor) NULL)
2650 {
2651 MagickBooleanType
2652 proceed;
2653
2654#if defined(MAGICKCORE_OPENMP_SUPPORT)
2655 #pragma omp critical (MagickCore_MorphologyImage)
2656#endif
2657 proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
2658 if (proceed == MagickFalse)
2659 status=MagickFalse;
2660 }
anthony83ba99b2010-01-24 08:48:15 +00002661 } /* y */
anthony602ab9b2010-01-05 08:06:50 +00002662 result_image->type=image->type;
2663 q_view=DestroyCacheView(q_view);
2664 p_view=DestroyCacheView(p_view);
cristy150989e2010-02-01 14:59:39 +00002665 return(status ? (unsigned long) changed : 0);
anthony602ab9b2010-01-05 08:06:50 +00002666}
2667
anthony4fd27e22010-02-07 08:17:18 +00002668
anthony9eb4f742010-05-18 02:45:54 +00002669MagickExport Image *MorphologyApply(const Image *image, const ChannelType
2670 channel,const MorphologyMethod method, const long iterations,
anthony47f5d062010-05-23 07:47:50 +00002671 const KernelInfo *kernel, const CompositeOperator compose,
2672 const double bias, ExceptionInfo *exception)
cristy2be15382010-01-21 02:38:03 +00002673{
2674 Image
anthony47f5d062010-05-23 07:47:50 +00002675 *curr_image, /* Image we are working with or iterating */
2676 *work_image, /* secondary image for primative iteration */
2677 *save_image, /* saved image - for 'edge' method only */
2678 *rslt_image; /* resultant image - after multi-kernel handling */
anthony602ab9b2010-01-05 08:06:50 +00002679
anthony4fd27e22010-02-07 08:17:18 +00002680 KernelInfo
anthony47f5d062010-05-23 07:47:50 +00002681 *reflected_kernel, /* A reflected copy of the kernel (if needed) */
2682 *norm_kernel, /* the current normal un-reflected kernel */
2683 *rflt_kernel, /* the current reflected kernel (if needed) */
2684 *this_kernel; /* the kernel being applied */
anthony4fd27e22010-02-07 08:17:18 +00002685
2686 MorphologyMethod
anthony47f5d062010-05-23 07:47:50 +00002687 primative; /* the current morphology primative being applied */
anthony9eb4f742010-05-18 02:45:54 +00002688
2689 CompositeOperator
anthony47f5d062010-05-23 07:47:50 +00002690 rslt_compose; /* multi-kernel compose method for results to use */
2691
2692 MagickBooleanType
2693 verbose; /* verbose output of results */
anthony4fd27e22010-02-07 08:17:18 +00002694
anthony1b2bc0a2010-05-12 05:25:22 +00002695 unsigned long
anthony47f5d062010-05-23 07:47:50 +00002696 method_loop, /* Loop 1: number of compound method iterations */
2697 method_limit, /* maximum number of compound method iterations */
2698 kernel_number, /* Loop 2: the kernel number being applied */
2699 stage_loop, /* Loop 3: primative loop for compound morphology */
2700 stage_limit, /* how many primatives in this compound */
2701 kernel_loop, /* Loop 4: iterate the kernel (basic morphology) */
2702 kernel_limit, /* number of times to iterate kernel */
2703 count, /* total count of primative steps applied */
2704 changed, /* number pixels changed by last primative operation */
2705 kernel_changed, /* total count of changed using iterated kernel */
2706 method_changed; /* total count of changed over method iteration */
2707
2708 char
2709 v_info[80];
anthony1b2bc0a2010-05-12 05:25:22 +00002710
anthony602ab9b2010-01-05 08:06:50 +00002711 assert(image != (Image *) NULL);
2712 assert(image->signature == MagickSignature);
anthony4fd27e22010-02-07 08:17:18 +00002713 assert(kernel != (KernelInfo *) NULL);
2714 assert(kernel->signature == MagickSignature);
anthony602ab9b2010-01-05 08:06:50 +00002715 assert(exception != (ExceptionInfo *) NULL);
2716 assert(exception->signature == MagickSignature);
2717
anthonyc3e48252010-05-24 12:43:11 +00002718 count = 0; /* number of low-level morphology primatives performed */
anthony602ab9b2010-01-05 08:06:50 +00002719 if ( iterations == 0 )
anthony47f5d062010-05-23 07:47:50 +00002720 return((Image *)NULL); /* null operation - nothing to do! */
anthony602ab9b2010-01-05 08:06:50 +00002721
anthony47f5d062010-05-23 07:47:50 +00002722 kernel_limit = (unsigned long) iterations;
2723 if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
2724 kernel_limit = image->columns > image->rows ? image->columns : image->rows;
anthony602ab9b2010-01-05 08:06:50 +00002725
cristye96405a2010-05-19 02:24:31 +00002726 verbose = ( GetImageArtifact(image,"verbose") != (const char *) NULL ) ?
2727 MagickTrue : MagickFalse;
anthony4f1dcb72010-05-14 08:43:10 +00002728
anthony9eb4f742010-05-18 02:45:54 +00002729 /* initialise for cleanup */
anthony47f5d062010-05-23 07:47:50 +00002730 curr_image = (Image *) image;
2731 work_image = save_image = rslt_image = (Image *) NULL;
2732 reflected_kernel = (KernelInfo *) NULL;
anthony4fd27e22010-02-07 08:17:18 +00002733
anthony47f5d062010-05-23 07:47:50 +00002734 /* Initialize specific methods
2735 * + which loop should use the given iteratations
2736 * + how many primatives make up the compound morphology
2737 * + multi-kernel compose method to use (by default)
2738 */
2739 method_limit = 1; /* just do method once, unless otherwise set */
2740 stage_limit = 1; /* assume method is not a compount */
2741 rslt_compose = compose; /* and we are composing multi-kernels as given */
anthony9eb4f742010-05-18 02:45:54 +00002742 switch( method ) {
anthony47f5d062010-05-23 07:47:50 +00002743 case SmoothMorphology: /* 4 primative compound morphology */
2744 stage_limit = 4;
anthony9eb4f742010-05-18 02:45:54 +00002745 break;
anthony47f5d062010-05-23 07:47:50 +00002746 case OpenMorphology: /* 2 primative compound morphology */
anthony9eb4f742010-05-18 02:45:54 +00002747 case OpenIntensityMorphology:
anthony47f5d062010-05-23 07:47:50 +00002748 case TopHatMorphology:
2749 case CloseMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002750 case CloseIntensityMorphology:
anthony47f5d062010-05-23 07:47:50 +00002751 case BottomHatMorphology:
2752 case EdgeMorphology:
2753 stage_limit = 2;
anthony9eb4f742010-05-18 02:45:54 +00002754 break;
2755 case HitAndMissMorphology:
anthonyc3e48252010-05-24 12:43:11 +00002756 kernel_limit = 1; /* no method or kernel iteration */
anthony47f5d062010-05-23 07:47:50 +00002757 rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
anthony9eb4f742010-05-18 02:45:54 +00002758 break;
anthonyc3e48252010-05-24 12:43:11 +00002759 case ThinningMorphology:
anthony9eb4f742010-05-18 02:45:54 +00002760 case ThickenMorphology:
anthonyc3e48252010-05-24 12:43:11 +00002761 case DistanceMorphology:
2762 method_limit = kernel_limit; /* iterate method with each kernel */
2763 kernel_limit = 1; /* do not do kernel iteration */
2764 rslt_compose = NoCompositeOp; /* Re-iterate with multiple kernels */
anthony47f5d062010-05-23 07:47:50 +00002765 break;
2766 default:
anthony930be612010-02-08 04:26:15 +00002767 break;
anthony602ab9b2010-01-05 08:06:50 +00002768 }
2769
anthonyc3e48252010-05-24 12:43:11 +00002770 /* Handle user (caller) specified multi-kernel composition method */
anthony47f5d062010-05-23 07:47:50 +00002771 if ( compose != UndefinedCompositeOp )
2772 rslt_compose = compose; /* override default composition for method */
2773 if ( rslt_compose == UndefinedCompositeOp )
2774 rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
2775
anthonyc3e48252010-05-24 12:43:11 +00002776 /* Some methods require a reflected kernel to use with primatives.
2777 * Create the reflected kernel for those methods. */
anthony47f5d062010-05-23 07:47:50 +00002778 switch ( method ) {
2779 case CorrelateMorphology:
2780 case CloseMorphology:
2781 case CloseIntensityMorphology:
2782 case BottomHatMorphology:
2783 case SmoothMorphology:
2784 reflected_kernel = CloneKernelInfo(kernel);
2785 if (reflected_kernel == (KernelInfo *) NULL)
2786 goto error_cleanup;
2787 RotateKernelInfo(reflected_kernel,180);
2788 break;
2789 default:
2790 break;
anthony9eb4f742010-05-18 02:45:54 +00002791 }
anthony7a01dcf2010-05-11 12:25:52 +00002792
anthony47f5d062010-05-23 07:47:50 +00002793 /* Loop 1: iterate the compound method */
2794 method_loop = 0;
2795 method_changed = 1;
2796 while ( method_loop < method_limit && method_changed > 0 ) {
2797 method_loop++;
2798 method_changed = 0;
anthony9eb4f742010-05-18 02:45:54 +00002799
anthony47f5d062010-05-23 07:47:50 +00002800 /* Loop 2: iterate over each kernel in a multi-kernel list */
2801 norm_kernel = (KernelInfo *) kernel;
2802 rflt_kernel = reflected_kernel;
2803 kernel_number = 0;
2804 while ( norm_kernel != NULL ) {
anthony9eb4f742010-05-18 02:45:54 +00002805
anthony47f5d062010-05-23 07:47:50 +00002806 /* Loop 3: Compound Morphology Staging - Select Primative to apply */
2807 stage_loop = 0; /* the compound morphology stage number */
2808 while ( stage_loop < stage_limit ) {
2809 stage_loop++; /* The stage of the compound morphology */
anthony9eb4f742010-05-18 02:45:54 +00002810
anthony47f5d062010-05-23 07:47:50 +00002811 /* Select primative morphology for this stage of compound method */
2812 this_kernel = norm_kernel; /* default use unreflected kernel */
anthonybd0f5562010-05-24 13:05:02 +00002813 primative = method; /* Assume method is a primative */
anthony47f5d062010-05-23 07:47:50 +00002814 switch( method ) {
2815 case ErodeMorphology: /* just erode */
2816 case EdgeInMorphology: /* erode and image difference */
2817 primative = ErodeMorphology;
2818 break;
2819 case DilateMorphology: /* just dilate */
2820 case EdgeOutMorphology: /* dilate and image difference */
2821 primative = DilateMorphology;
2822 break;
2823 case OpenMorphology: /* erode then dialate */
2824 case TopHatMorphology: /* open and image difference */
2825 primative = ErodeMorphology;
2826 if ( stage_loop == 2 )
2827 primative = DilateMorphology;
2828 break;
2829 case OpenIntensityMorphology:
2830 primative = ErodeIntensityMorphology;
2831 if ( stage_loop == 2 )
2832 primative = DilateIntensityMorphology;
2833 case CloseMorphology: /* dilate, then erode */
2834 case BottomHatMorphology: /* close and image difference */
2835 this_kernel = rflt_kernel; /* use the reflected kernel */
2836 primative = DilateMorphology;
2837 if ( stage_loop == 2 )
2838 primative = ErodeMorphology;
2839 break;
2840 case CloseIntensityMorphology:
2841 this_kernel = rflt_kernel; /* use the reflected kernel */
2842 primative = DilateIntensityMorphology;
2843 if ( stage_loop == 2 )
2844 primative = ErodeIntensityMorphology;
2845 break;
2846 case SmoothMorphology: /* open, close */
2847 switch ( stage_loop ) {
2848 case 1: /* start an open method, which starts with Erode */
2849 primative = ErodeMorphology;
2850 break;
2851 case 2: /* now Dilate the Erode */
2852 primative = DilateMorphology;
2853 break;
2854 case 3: /* Reflect kernel a close */
2855 this_kernel = rflt_kernel; /* use the reflected kernel */
2856 primative = DilateMorphology;
2857 break;
2858 case 4: /* Finish the Close */
2859 this_kernel = rflt_kernel; /* use the reflected kernel */
2860 primative = ErodeMorphology;
2861 break;
2862 }
2863 break;
2864 case EdgeMorphology: /* dilate and erode difference */
2865 primative = DilateMorphology;
2866 if ( stage_loop == 2 ) {
2867 save_image = curr_image; /* save the image difference */
2868 curr_image = (Image *) image;
2869 primative = ErodeMorphology;
2870 }
2871 break;
2872 case CorrelateMorphology:
2873 /* A Correlation is a Convolution with a reflected kernel.
2874 ** However a Convolution is a weighted sum using a reflected
2875 ** kernel. It may seem stange to convert a Correlation into a
2876 ** Convolution as the Correlation is the simplier method, but
2877 ** Convolution is much more commonly used, and it makes sense to
2878 ** implement it directly so as to avoid the need to duplicate the
2879 ** kernel when it is not required (which is typically the
2880 ** default).
2881 */
2882 this_kernel = rflt_kernel; /* use the reflected kernel */
2883 primative = ConvolveMorphology;
2884 break;
2885 default:
anthony47f5d062010-05-23 07:47:50 +00002886 break;
2887 }
anthony9eb4f742010-05-18 02:45:54 +00002888
anthony47f5d062010-05-23 07:47:50 +00002889 /* Extra information for debugging compound operations */
2890 if ( verbose == MagickTrue ) {
2891 if ( stage_limit > 1 )
cristydc1c30b2010-05-23 14:23:12 +00002892 (void) FormatMagickString(v_info, MaxTextExtent, "%s:%lu.%lu -> ",
anthony47f5d062010-05-23 07:47:50 +00002893 MagickOptionToMnemonic(MagickMorphologyOptions, method),
2894 method_loop, stage_loop );
2895 else if ( primative != method )
cristydc1c30b2010-05-23 14:23:12 +00002896 (void) FormatMagickString(v_info, MaxTextExtent, "%s:%lu -> ",
anthony47f5d062010-05-23 07:47:50 +00002897 MagickOptionToMnemonic(MagickMorphologyOptions, method),
2898 method_loop );
2899 else
2900 v_info[0] = '\0';
2901 }
2902
2903 /* Loop 4: Iterate the kernel with primative */
2904 kernel_loop = 0;
2905 kernel_changed = 0;
2906 changed = 1;
2907 while ( kernel_loop < kernel_limit && changed > 0 ) {
2908 kernel_loop++; /* the iteration of this kernel */
anthony9eb4f742010-05-18 02:45:54 +00002909
2910 /* Create a destination image, if not yet defined */
2911 if ( work_image == (Image *) NULL )
2912 {
2913 work_image=CloneImage(image,0,0,MagickTrue,exception);
2914 if (work_image == (Image *) NULL)
2915 goto error_cleanup;
2916 if (SetImageStorageClass(work_image,DirectClass) == MagickFalse)
2917 {
2918 InheritException(exception,&work_image->exception);
2919 goto error_cleanup;
2920 }
2921 }
2922
anthony47f5d062010-05-23 07:47:50 +00002923 /* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
anthony9eb4f742010-05-18 02:45:54 +00002924 count++;
anthony47f5d062010-05-23 07:47:50 +00002925 changed = MorphologyPrimitive(curr_image, work_image, primative,
anthony9eb4f742010-05-18 02:45:54 +00002926 channel, this_kernel, bias, exception);
anthony47f5d062010-05-23 07:47:50 +00002927 kernel_changed += changed;
2928 method_changed += changed;
anthony9eb4f742010-05-18 02:45:54 +00002929
anthony47f5d062010-05-23 07:47:50 +00002930 if ( verbose == MagickTrue ) {
2931 if ( kernel_loop > 1 )
2932 fprintf(stderr, "\n"); /* add end-of-line from previous */
2933 fprintf(stderr, "%s%s%s:%lu.%lu #%lu => Changed %lu", v_info,
2934 MagickOptionToMnemonic(MagickMorphologyOptions, primative),
2935 ( this_kernel == rflt_kernel ) ? "*" : "",
2936 method_loop+kernel_loop-1, kernel_number, count, changed);
2937 }
anthony9eb4f742010-05-18 02:45:54 +00002938 /* prepare next loop */
2939 { Image *tmp = work_image; /* swap images for iteration */
2940 work_image = curr_image;
2941 curr_image = tmp;
2942 }
2943 if ( work_image == image )
anthony47f5d062010-05-23 07:47:50 +00002944 work_image = (Image *) NULL; /* replace input 'image' */
anthony7a01dcf2010-05-11 12:25:52 +00002945
anthony47f5d062010-05-23 07:47:50 +00002946 } /* End Loop 4: Iterate the kernel with primative */
anthony1b2bc0a2010-05-12 05:25:22 +00002947
anthony47f5d062010-05-23 07:47:50 +00002948 if ( verbose == MagickTrue && kernel_changed != changed )
2949 fprintf(stderr, " Total %lu", kernel_changed);
2950 if ( verbose == MagickTrue && stage_loop < stage_limit )
2951 fprintf(stderr, "\n"); /* add end-of-line before looping */
anthony9eb4f742010-05-18 02:45:54 +00002952
2953#if 0
anthony47f5d062010-05-23 07:47:50 +00002954 fprintf(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
2955 fprintf(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
2956 fprintf(stderr, " work =0x%lx\n", (unsigned long)work_image);
2957 fprintf(stderr, " save =0x%lx\n", (unsigned long)save_image);
2958 fprintf(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
anthony9eb4f742010-05-18 02:45:54 +00002959#endif
2960
anthony47f5d062010-05-23 07:47:50 +00002961 } /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
anthony9eb4f742010-05-18 02:45:54 +00002962
anthony47f5d062010-05-23 07:47:50 +00002963 /* Final Post-processing for some Compound Methods
2964 **
2965 ** The removal of any 'Sync' channel flag in the Image Compositon
2966 ** below ensures the methematical compose method is applied in a
2967 ** purely mathematical way, and only to the selected channels.
2968 ** Turn off SVG composition 'alpha blending'.
2969 */
2970 switch( method ) {
2971 case EdgeOutMorphology:
2972 case EdgeInMorphology:
2973 case TopHatMorphology:
2974 case BottomHatMorphology:
2975 if ( verbose == MagickTrue )
2976 fprintf(stderr, "\n%s: Difference with original image",
2977 MagickOptionToMnemonic(MagickMorphologyOptions, method) );
2978 (void) CompositeImageChannel(curr_image,
2979 (ChannelType) (channel & ~SyncChannels),
2980 DifferenceCompositeOp, image, 0, 0);
2981 break;
2982 case EdgeMorphology:
2983 if ( verbose == MagickTrue )
2984 fprintf(stderr, "\n%s: Difference of Dilate and Erode",
2985 MagickOptionToMnemonic(MagickMorphologyOptions, method) );
2986 (void) CompositeImageChannel(curr_image,
2987 (ChannelType) (channel & ~SyncChannels),
2988 DifferenceCompositeOp, save_image, 0, 0);
2989 save_image = DestroyImage(save_image); /* finished with save image */
2990 break;
2991 default:
2992 break;
2993 }
2994
2995 /* multi-kernel handling: re-iterate, or compose results */
2996 if ( kernel->next == (KernelInfo *) NULL )
anthonyc3e48252010-05-24 12:43:11 +00002997 rslt_image = curr_image; /* just return the resulting image */
anthony47f5d062010-05-23 07:47:50 +00002998 else if ( rslt_compose == NoCompositeOp )
anthonyc3e48252010-05-24 12:43:11 +00002999 { if ( verbose == MagickTrue ) {
3000 if ( this_kernel->next != (KernelInfo *) NULL )
3001 fprintf(stderr, " (re-iterate)");
3002 else
3003 fprintf(stderr, " (done)");
3004 }
3005 rslt_image = curr_image; /* return result, and re-iterate */
anthony9eb4f742010-05-18 02:45:54 +00003006 }
anthony47f5d062010-05-23 07:47:50 +00003007 else if ( rslt_image == (Image *) NULL)
3008 { if ( verbose == MagickTrue )
3009 fprintf(stderr, " (save for compose)");
3010 rslt_image = curr_image;
3011 curr_image = (Image *) image; /* continue with original image */
anthony9eb4f742010-05-18 02:45:54 +00003012 }
anthony47f5d062010-05-23 07:47:50 +00003013 else
3014 { /* add the new 'current' result to the composition
3015 **
3016 ** The removal of any 'Sync' channel flag in the Image Compositon
3017 ** below ensures the methematical compose method is applied in a
3018 ** purely mathematical way, and only to the selected channels.
3019 ** Turn off SVG composition 'alpha blending'.
3020 */
3021 if ( verbose == MagickTrue )
3022 fprintf(stderr, " (compose \"%s\")",
3023 MagickOptionToMnemonic(MagickComposeOptions, rslt_compose) );
3024 (void) CompositeImageChannel(rslt_image,
3025 (ChannelType) (channel & ~SyncChannels), rslt_compose,
3026 curr_image, 0, 0);
3027 curr_image = (Image *) image; /* continue with original image */
3028 }
3029 if ( verbose == MagickTrue )
3030 fprintf(stderr, "\n");
anthony9eb4f742010-05-18 02:45:54 +00003031
anthony47f5d062010-05-23 07:47:50 +00003032 /* loop to the next kernel in a multi-kernel list */
3033 norm_kernel = norm_kernel->next;
3034 if ( rflt_kernel != (KernelInfo *) NULL )
3035 rflt_kernel = rflt_kernel->next;
3036 kernel_number++;
3037 } /* End Loop 2: Loop over each kernel */
anthony9eb4f742010-05-18 02:45:54 +00003038
anthony47f5d062010-05-23 07:47:50 +00003039 } /* End Loop 1: compound method interation */
anthony602ab9b2010-01-05 08:06:50 +00003040
anthony9eb4f742010-05-18 02:45:54 +00003041 goto exit_cleanup;
anthony1b2bc0a2010-05-12 05:25:22 +00003042
anthony47f5d062010-05-23 07:47:50 +00003043 /* Yes goto's are bad, but it makes cleanup lot more efficient */
anthony1b2bc0a2010-05-12 05:25:22 +00003044error_cleanup:
anthony47f5d062010-05-23 07:47:50 +00003045 if ( curr_image != (Image *) NULL &&
3046 curr_image != rslt_image &&
3047 curr_image != image )
3048 curr_image = DestroyImage(curr_image);
3049 if ( rslt_image != (Image *) NULL )
3050 rslt_image = DestroyImage(rslt_image);
anthony1b2bc0a2010-05-12 05:25:22 +00003051exit_cleanup:
anthony47f5d062010-05-23 07:47:50 +00003052 if ( curr_image != (Image *) NULL &&
3053 curr_image != rslt_image &&
3054 curr_image != image )
3055 curr_image = DestroyImage(curr_image);
anthony9eb4f742010-05-18 02:45:54 +00003056 if ( work_image != (Image *) NULL )
anthony47f5d062010-05-23 07:47:50 +00003057 work_image = DestroyImage(work_image);
anthony9eb4f742010-05-18 02:45:54 +00003058 if ( save_image != (Image *) NULL )
anthony47f5d062010-05-23 07:47:50 +00003059 save_image = DestroyImage(save_image);
3060 if ( reflected_kernel != (KernelInfo *) NULL )
3061 reflected_kernel = DestroyKernelInfo(reflected_kernel);
3062 return(rslt_image);
anthony9eb4f742010-05-18 02:45:54 +00003063}
3064
3065/*
3066%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3067% %
3068% %
3069% %
3070% M o r p h o l o g y I m a g e C h a n n e l %
3071% %
3072% %
3073% %
3074%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3075%
3076% MorphologyImageChannel() applies a user supplied kernel to the image
3077% according to the given mophology method.
3078%
3079% This function applies any and all user defined settings before calling
3080% the above internal function MorphologyApply().
3081%
3082% User defined settings include...
anthony46a369d2010-05-19 02:41:48 +00003083% * Output Bias for Convolution and correlation ("-bias")
3084% * Kernel Scale/normalize settings ("-set 'option:convolve:scale'")
3085% This can also includes the addition of a scaled unity kernel.
3086% * Show Kernel being applied ("-set option:showkernel 1")
anthony9eb4f742010-05-18 02:45:54 +00003087%
3088% The format of the MorphologyImage method is:
3089%
3090% Image *MorphologyImage(const Image *image,MorphologyMethod method,
3091% const long iterations,KernelInfo *kernel,ExceptionInfo *exception)
3092%
3093% Image *MorphologyImageChannel(const Image *image, const ChannelType
3094% channel,MorphologyMethod method,const long iterations,
3095% KernelInfo *kernel,ExceptionInfo *exception)
3096%
3097% A description of each parameter follows:
3098%
3099% o image: the image.
3100%
3101% o method: the morphology method to be applied.
3102%
3103% o iterations: apply the operation this many times (or no change).
3104% A value of -1 means loop until no change found.
3105% How this is applied may depend on the morphology method.
3106% Typically this is a value of 1.
3107%
3108% o channel: the channel type.
3109%
3110% o kernel: An array of double representing the morphology kernel.
3111% Warning: kernel may be normalized for the Convolve method.
3112%
3113% o exception: return any errors or warnings in this structure.
3114%
3115*/
3116
3117MagickExport Image *MorphologyImageChannel(const Image *image,
3118 const ChannelType channel,const MorphologyMethod method,
3119 const long iterations,const KernelInfo *kernel,ExceptionInfo *exception)
3120{
3121 const char
3122 *artifact;
3123
3124 KernelInfo
3125 *curr_kernel;
3126
anthony47f5d062010-05-23 07:47:50 +00003127 CompositeOperator
3128 compose;
3129
anthony9eb4f742010-05-18 02:45:54 +00003130 Image
3131 *morphology_image;
3132
3133
anthony46a369d2010-05-19 02:41:48 +00003134 /* Apply Convolve/Correlate Normalization and Scaling Factors.
3135 * This is done BEFORE the ShowKernelInfo() function is called so that
3136 * users can see the results of the 'option:convolve:scale' option.
anthony9eb4f742010-05-18 02:45:54 +00003137 */
3138 curr_kernel = (KernelInfo *) kernel;
anthonyf71ca292010-05-19 04:08:43 +00003139 if ( method == ConvolveMorphology || method == CorrelateMorphology )
anthony9eb4f742010-05-18 02:45:54 +00003140 {
3141 artifact = GetImageArtifact(image,"convolve:scale");
3142 if ( artifact != (char *)NULL ) {
anthony9eb4f742010-05-18 02:45:54 +00003143 if ( curr_kernel == kernel )
3144 curr_kernel = CloneKernelInfo(kernel);
3145 if (curr_kernel == (KernelInfo *) NULL) {
3146 curr_kernel=DestroyKernelInfo(curr_kernel);
3147 return((Image *) NULL);
3148 }
anthony46a369d2010-05-19 02:41:48 +00003149 ScaleGeometryKernelInfo(curr_kernel, artifact);
anthony9eb4f742010-05-18 02:45:54 +00003150 }
3151 }
3152
3153 /* display the (normalized) kernel via stderr */
3154 artifact = GetImageArtifact(image,"showkernel");
anthony47f5d062010-05-23 07:47:50 +00003155 if ( artifact == (const char *) NULL)
3156 artifact = GetImageArtifact(image,"convolve:showkernel");
3157 if ( artifact == (const char *) NULL)
3158 artifact = GetImageArtifact(image,"morphology:showkernel");
anthony9eb4f742010-05-18 02:45:54 +00003159 if ( artifact != (const char *) NULL)
3160 ShowKernelInfo(curr_kernel);
3161
anthony47f5d062010-05-23 07:47:50 +00003162 /* override the default handling of multi-kernel morphology results
3163 * if 'Undefined' use the default method
3164 * if 'None' (default for 'Convolve') re-iterate previous result
3165 * otherwise merge resulting images using compose method given
3166 */
3167 compose = UndefinedCompositeOp; /* use default for method */
3168 artifact = GetImageArtifact(image,"morphology:compose");
3169 if ( artifact != (const char *) NULL)
3170 compose = (CompositeOperator) ParseMagickOption(
3171 MagickComposeOptions,MagickFalse,artifact);
3172
anthony9eb4f742010-05-18 02:45:54 +00003173 /* Apply the Morphology */
3174 morphology_image = MorphologyApply(image, channel, method, iterations,
anthony47f5d062010-05-23 07:47:50 +00003175 curr_kernel, compose, image->bias, exception);
anthony9eb4f742010-05-18 02:45:54 +00003176
3177 /* Cleanup and Exit */
3178 if ( curr_kernel != kernel )
anthony1b2bc0a2010-05-12 05:25:22 +00003179 curr_kernel=DestroyKernelInfo(curr_kernel);
anthony9eb4f742010-05-18 02:45:54 +00003180 return(morphology_image);
3181}
3182
3183MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod
3184 method, const long iterations,const KernelInfo *kernel, ExceptionInfo
3185 *exception)
3186{
3187 Image
3188 *morphology_image;
3189
3190 morphology_image=MorphologyImageChannel(image,DefaultChannels,method,
3191 iterations,kernel,exception);
3192 return(morphology_image);
anthony602ab9b2010-01-05 08:06:50 +00003193}
anthony83ba99b2010-01-24 08:48:15 +00003194
3195/*
3196%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3197% %
3198% %
3199% %
anthony4fd27e22010-02-07 08:17:18 +00003200+ R o t a t e K e r n e l I n f o %
anthony83ba99b2010-01-24 08:48:15 +00003201% %
3202% %
3203% %
3204%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3205%
anthony46a369d2010-05-19 02:41:48 +00003206% RotateKernelInfo() rotates the kernel by the angle given.
3207%
3208% Currently it is restricted to 90 degree angles, of either 1D kernels
3209% or square kernels. And 'circular' rotations of 45 degrees for 3x3 kernels.
3210% It will ignore usless rotations for specific 'named' built-in kernels.
anthony83ba99b2010-01-24 08:48:15 +00003211%
anthony4fd27e22010-02-07 08:17:18 +00003212% The format of the RotateKernelInfo method is:
anthony83ba99b2010-01-24 08:48:15 +00003213%
anthony4fd27e22010-02-07 08:17:18 +00003214% void RotateKernelInfo(KernelInfo *kernel, double angle)
anthony83ba99b2010-01-24 08:48:15 +00003215%
3216% A description of each parameter follows:
3217%
3218% o kernel: the Morphology/Convolution kernel
3219%
3220% o angle: angle to rotate in degrees
3221%
anthony46a369d2010-05-19 02:41:48 +00003222% This function is currently internal to this module only, but can be exported
3223% to other modules if needed.
anthony83ba99b2010-01-24 08:48:15 +00003224*/
anthony4fd27e22010-02-07 08:17:18 +00003225static void RotateKernelInfo(KernelInfo *kernel, double angle)
anthony83ba99b2010-01-24 08:48:15 +00003226{
anthony1b2bc0a2010-05-12 05:25:22 +00003227 /* angle the lower kernels first */
3228 if ( kernel->next != (KernelInfo *) NULL)
3229 RotateKernelInfo(kernel->next, angle);
3230
anthony83ba99b2010-01-24 08:48:15 +00003231 /* WARNING: Currently assumes the kernel (rightly) is horizontally symetrical
3232 **
3233 ** TODO: expand beyond simple 90 degree rotates, flips and flops
3234 */
3235
3236 /* Modulus the angle */
3237 angle = fmod(angle, 360.0);
3238 if ( angle < 0 )
3239 angle += 360.0;
3240
anthony3c10fc82010-05-13 02:40:51 +00003241 if ( 337.5 < angle || angle <= 22.5 )
anthony43c49252010-05-18 10:59:50 +00003242 return; /* Near zero angle - no change! - At least not at this time */
anthony83ba99b2010-01-24 08:48:15 +00003243
anthony3dd0f622010-05-13 12:57:32 +00003244 /* Handle special cases */
anthony83ba99b2010-01-24 08:48:15 +00003245 switch (kernel->type) {
3246 /* These built-in kernels are cylindrical kernels, rotating is useless */
3247 case GaussianKernel:
anthony83ba99b2010-01-24 08:48:15 +00003248 case DOGKernel:
3249 case DiskKernel:
anthony3dd0f622010-05-13 12:57:32 +00003250 case PeaksKernel:
3251 case LaplacianKernel:
anthony83ba99b2010-01-24 08:48:15 +00003252 case ChebyshevKernel:
3253 case ManhattenKernel:
3254 case EuclideanKernel:
3255 return;
3256
3257 /* These may be rotatable at non-90 angles in the future */
3258 /* but simply rotating them in multiples of 90 degrees is useless */
3259 case SquareKernel:
3260 case DiamondKernel:
3261 case PlusKernel:
anthony3dd0f622010-05-13 12:57:32 +00003262 case CrossKernel:
anthony83ba99b2010-01-24 08:48:15 +00003263 return;
3264
3265 /* These only allows a +/-90 degree rotation (by transpose) */
3266 /* A 180 degree rotation is useless */
3267 case BlurKernel:
3268 case RectangleKernel:
3269 if ( 135.0 < angle && angle <= 225.0 )
3270 return;
3271 if ( 225.0 < angle && angle <= 315.0 )
3272 angle -= 180;
3273 break;
3274
anthony3dd0f622010-05-13 12:57:32 +00003275 default:
anthony83ba99b2010-01-24 08:48:15 +00003276 break;
3277 }
anthony3c10fc82010-05-13 02:40:51 +00003278 /* Attempt rotations by 45 degrees */
3279 if ( 22.5 < fmod(angle,90.0) && fmod(angle,90.0) <= 67.5 )
3280 {
3281 if ( kernel->width == 3 && kernel->height == 3 )
3282 { /* Rotate a 3x3 square by 45 degree angle */
3283 MagickRealType t = kernel->values[0];
anthony43c49252010-05-18 10:59:50 +00003284 kernel->values[0] = kernel->values[3];
3285 kernel->values[3] = kernel->values[6];
3286 kernel->values[6] = kernel->values[7];
3287 kernel->values[7] = kernel->values[8];
3288 kernel->values[8] = kernel->values[5];
3289 kernel->values[5] = kernel->values[2];
3290 kernel->values[2] = kernel->values[1];
3291 kernel->values[1] = t;
anthony1d45eb92010-05-25 11:13:23 +00003292 /* rotate non-centered origin */
3293 if ( kernel->x != 1 || kernel->y != 1 ) {
3294 long x,y;
3295 x = (long) kernel->x-1;
3296 y = (long) kernel->y-1;
3297 if ( x == y ) x = 0;
3298 else if ( x == 0 ) x = -y;
3299 else if ( x == -y ) y = 0;
3300 else if ( y == 0 ) y = x;
3301 kernel->x = (unsigned long) x+1;
3302 kernel->y = (unsigned long) y+1;
3303 }
anthony43c49252010-05-18 10:59:50 +00003304 angle = fmod(angle+315.0, 360.0); /* angle reduced 45 degrees */
3305 kernel->angle = fmod(kernel->angle+45.0, 360.0);
anthony3c10fc82010-05-13 02:40:51 +00003306 }
3307 else
3308 perror("Unable to rotate non-3x3 kernel by 45 degrees");
3309 }
3310 if ( 45.0 < fmod(angle, 180.0) && fmod(angle,180.0) <= 135.0 )
3311 {
3312 if ( kernel->width == 1 || kernel->height == 1 )
3313 { /* Do a transpose of the image, which results in a 90
3314 ** degree rotation of a 1 dimentional kernel
3315 */
3316 long
3317 t;
3318 t = (long) kernel->width;
3319 kernel->width = kernel->height;
3320 kernel->height = (unsigned long) t;
3321 t = kernel->x;
3322 kernel->x = kernel->y;
3323 kernel->y = t;
anthony43c49252010-05-18 10:59:50 +00003324 if ( kernel->width == 1 ) {
3325 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
3326 kernel->angle = fmod(kernel->angle+90.0, 360.0);
3327 } else {
3328 angle = fmod(angle+90.0, 360.0); /* angle increased 90 degrees */
3329 kernel->angle = fmod(kernel->angle+270.0, 360.0);
3330 }
anthony3c10fc82010-05-13 02:40:51 +00003331 }
3332 else if ( kernel->width == kernel->height )
3333 { /* Rotate a square array of values by 90 degrees */
anthony1d45eb92010-05-25 11:13:23 +00003334 { register unsigned long
3335 i,j,x,y;
3336 register MagickRealType
3337 *k,t;
3338 k=kernel->values;
3339 for( i=0, x=kernel->width-1; i<=x; i++, x--)
3340 for( j=0, y=kernel->height-1; j<y; j++, y--)
3341 { t = k[i+j*kernel->width];
3342 k[i+j*kernel->width] = k[j+x*kernel->width];
3343 k[j+x*kernel->width] = k[x+y*kernel->width];
3344 k[x+y*kernel->width] = k[y+i*kernel->width];
3345 k[y+i*kernel->width] = t;
3346 }
3347 }
3348 /* rotate the origin - relative to center of array */
3349 { register long x,y;
3350 x = (long) kernel->x*2-kernel->width+1;
3351 y = (long) kernel->y*2-kernel->height+1;
3352 kernel->x = (unsigned long) ( -y +kernel->width-1)/2;
3353 kernel->y = (unsigned long) ( +x +kernel->height-1)/2;
3354 }
anthony43c49252010-05-18 10:59:50 +00003355 angle = fmod(angle+270.0, 360.0); /* angle reduced 90 degrees */
3356 kernel->angle = fmod(kernel->angle+90.0, 360.0);
anthony3c10fc82010-05-13 02:40:51 +00003357 }
3358 else
3359 perror("Unable to rotate a non-square, non-linear kernel 90 degrees");
3360 }
anthony83ba99b2010-01-24 08:48:15 +00003361 if ( 135.0 < angle && angle <= 225.0 )
3362 {
anthony43c49252010-05-18 10:59:50 +00003363 /* For a 180 degree rotation - also know as a reflection
3364 * This is actually a very very common operation!
3365 * Basically all that is needed is a reversal of the kernel data!
3366 * And a reflection of the origon
3367 */
anthony83ba99b2010-01-24 08:48:15 +00003368 unsigned long
3369 i,j;
3370 register double
3371 *k,t;
3372
3373 k=kernel->values;
3374 for ( i=0, j=kernel->width*kernel->height-1; i<j; i++, j--)
3375 t=k[i], k[i]=k[j], k[j]=t;
3376
anthony930be612010-02-08 04:26:15 +00003377 kernel->x = (long) kernel->width - kernel->x - 1;
3378 kernel->y = (long) kernel->height - kernel->y - 1;
anthony43c49252010-05-18 10:59:50 +00003379 angle = fmod(angle-180.0, 360.0); /* angle+180 degrees */
3380 kernel->angle = fmod(kernel->angle+180.0, 360.0);
anthony83ba99b2010-01-24 08:48:15 +00003381 }
anthony3c10fc82010-05-13 02:40:51 +00003382 /* At this point angle should at least between -45 (315) and +45 degrees
anthony83ba99b2010-01-24 08:48:15 +00003383 * In the future some form of non-orthogonal angled rotates could be
3384 * performed here, posibily with a linear kernel restriction.
3385 */
3386
3387#if 0
anthony3c10fc82010-05-13 02:40:51 +00003388 { /* Do a Flop by reversing each row.
anthony83ba99b2010-01-24 08:48:15 +00003389 */
3390 unsigned long
3391 y;
cristy150989e2010-02-01 14:59:39 +00003392 register long
anthony83ba99b2010-01-24 08:48:15 +00003393 x,r;
3394 register double
3395 *k,t;
3396
3397 for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
3398 for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
3399 t=k[x], k[x]=k[r], k[r]=t;
3400
cristyc99304f2010-02-01 15:26:27 +00003401 kernel->x = kernel->width - kernel->x - 1;
anthony83ba99b2010-01-24 08:48:15 +00003402 angle = fmod(angle+180.0, 360.0);
3403 }
3404#endif
3405 return;
3406}
3407
3408/*
3409%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3410% %
3411% %
3412% %
anthony46a369d2010-05-19 02:41:48 +00003413% S c a l e G e o m e t r y K e r n e l I n f o %
3414% %
3415% %
3416% %
3417%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3418%
3419% ScaleGeometryKernelInfo() takes a geometry argument string, typically
3420% provided as a "-set option:convolve:scale {geometry}" user setting,
3421% and modifies the kernel according to the parsed arguments of that setting.
3422%
3423% The first argument (and any normalization flags) are passed to
3424% ScaleKernelInfo() to scale/normalize the kernel. The second argument
3425% is then passed to UnityAddKernelInfo() to add a scled unity kernel
3426% into the scaled/normalized kernel.
3427%
3428% The format of the ScaleKernelInfo method is:
3429%
3430% void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
3431% const MagickStatusType normalize_flags )
3432%
3433% A description of each parameter follows:
3434%
3435% o kernel: the Morphology/Convolution kernel to modify
3436%
3437% o geometry:
3438% The geometry string to parse, typically from the user provided
3439% "-set option:convolve:scale {geometry}" setting.
3440%
3441*/
3442MagickExport void ScaleGeometryKernelInfo (KernelInfo *kernel,
3443 const char *geometry)
3444{
3445 GeometryFlags
3446 flags;
3447 GeometryInfo
3448 args;
3449
3450 SetGeometryInfo(&args);
3451 flags = (GeometryFlags) ParseGeometry(geometry, &args);
3452
3453#if 0
3454 /* For Debugging Geometry Input */
3455 fprintf(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
3456 flags, args.rho, args.sigma, args.xi, args.psi );
3457#endif
3458
3459 if ( (flags & PercentValue) != 0 ) /* Handle Percentage flag*/
3460 args.rho *= 0.01, args.sigma *= 0.01;
3461
3462 if ( (flags & RhoValue) == 0 ) /* Set Defaults for missing args */
3463 args.rho = 1.0;
3464 if ( (flags & SigmaValue) == 0 )
3465 args.sigma = 0.0;
3466
3467 /* Scale/Normalize the input kernel */
3468 ScaleKernelInfo(kernel, args.rho, flags);
3469
3470 /* Add Unity Kernel, for blending with original */
3471 if ( (flags & SigmaValue) != 0 )
3472 UnityAddKernelInfo(kernel, args.sigma);
3473
3474 return;
3475}
3476/*
3477%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3478% %
3479% %
3480% %
cristy6771f1e2010-03-05 19:43:39 +00003481% S c a l e K e r n e l I n f o %
anthonycc6c8362010-01-25 04:14:01 +00003482% %
3483% %
3484% %
3485%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3486%
anthony1b2bc0a2010-05-12 05:25:22 +00003487% ScaleKernelInfo() scales the given kernel list by the given amount, with or
3488% without normalization of the sum of the kernel values (as per given flags).
anthonycc6c8362010-01-25 04:14:01 +00003489%
anthony999bb2c2010-02-18 12:38:01 +00003490% By default (no flags given) the values within the kernel is scaled
anthony1b2bc0a2010-05-12 05:25:22 +00003491% directly using given scaling factor without change.
anthonycc6c8362010-01-25 04:14:01 +00003492%
anthony46a369d2010-05-19 02:41:48 +00003493% If either of the two 'normalize_flags' are given the kernel will first be
3494% normalized and then further scaled by the scaling factor value given.
anthony999bb2c2010-02-18 12:38:01 +00003495%
3496% Kernel normalization ('normalize_flags' given) is designed to ensure that
3497% any use of the kernel scaling factor with 'Convolve' or 'Correlate'
anthony1b2bc0a2010-05-12 05:25:22 +00003498% morphology methods will fall into -1.0 to +1.0 range. Note that for
3499% non-HDRI versions of IM this may cause images to have any negative results
3500% clipped, unless some 'bias' is used.
anthony999bb2c2010-02-18 12:38:01 +00003501%
3502% More specifically. Kernels which only contain positive values (such as a
3503% 'Gaussian' kernel) will be scaled so that those values sum to +1.0,
anthony1b2bc0a2010-05-12 05:25:22 +00003504% ensuring a 0.0 to +1.0 output range for non-HDRI images.
anthony999bb2c2010-02-18 12:38:01 +00003505%
3506% For Kernels that contain some negative values, (such as 'Sharpen' kernels)
3507% the kernel will be scaled by the absolute of the sum of kernel values, so
3508% that it will generally fall within the +/- 1.0 range.
3509%
3510% For kernels whose values sum to zero, (such as 'Laplician' kernels) kernel
3511% will be scaled by just the sum of the postive values, so that its output
3512% range will again fall into the +/- 1.0 range.
3513%
3514% For special kernels designed for locating shapes using 'Correlate', (often
3515% only containing +1 and -1 values, representing foreground/brackground
3516% matching) a special normalization method is provided to scale the positive
3517% values seperatally to those of the negative values, so the kernel will be
3518% forced to become a zero-sum kernel better suited to such searches.
3519%
anthony1b2bc0a2010-05-12 05:25:22 +00003520% WARNING: Correct normalization of the kernel assumes that the '*_range'
anthony999bb2c2010-02-18 12:38:01 +00003521% attributes within the kernel structure have been correctly set during the
3522% kernels creation.
3523%
3524% NOTE: The values used for 'normalize_flags' have been selected specifically
anthony46a369d2010-05-19 02:41:48 +00003525% to match the use of geometry options, so that '!' means NormalizeValue, '^'
3526% means CorrelateNormalizeValue. All other GeometryFlags values are ignored.
anthonycc6c8362010-01-25 04:14:01 +00003527%
anthony4fd27e22010-02-07 08:17:18 +00003528% The format of the ScaleKernelInfo method is:
anthonycc6c8362010-01-25 04:14:01 +00003529%
anthony999bb2c2010-02-18 12:38:01 +00003530% void ScaleKernelInfo(KernelInfo *kernel, const double scaling_factor,
3531% const MagickStatusType normalize_flags )
anthonycc6c8362010-01-25 04:14:01 +00003532%
3533% A description of each parameter follows:
3534%
3535% o kernel: the Morphology/Convolution kernel
3536%
anthony999bb2c2010-02-18 12:38:01 +00003537% o scaling_factor:
3538% multiply all values (after normalization) by this factor if not
3539% zero. If the kernel is normalized regardless of any flags.
3540%
3541% o normalize_flags:
3542% GeometryFlags defining normalization method to use.
3543% specifically: NormalizeValue, CorrelateNormalizeValue,
3544% and/or PercentValue
anthonycc6c8362010-01-25 04:14:01 +00003545%
3546*/
cristy6771f1e2010-03-05 19:43:39 +00003547MagickExport void ScaleKernelInfo(KernelInfo *kernel,
3548 const double scaling_factor,const GeometryFlags normalize_flags)
anthonycc6c8362010-01-25 04:14:01 +00003549{
cristy150989e2010-02-01 14:59:39 +00003550 register long
anthonycc6c8362010-01-25 04:14:01 +00003551 i;
3552
anthony999bb2c2010-02-18 12:38:01 +00003553 register double
3554 pos_scale,
3555 neg_scale;
3556
anthony46a369d2010-05-19 02:41:48 +00003557 /* do the other kernels in a multi-kernel list first */
anthony1b2bc0a2010-05-12 05:25:22 +00003558 if ( kernel->next != (KernelInfo *) NULL)
3559 ScaleKernelInfo(kernel->next, scaling_factor, normalize_flags);
3560
anthony46a369d2010-05-19 02:41:48 +00003561 /* Normalization of Kernel */
anthony999bb2c2010-02-18 12:38:01 +00003562 pos_scale = 1.0;
3563 if ( (normalize_flags&NormalizeValue) != 0 ) {
anthony999bb2c2010-02-18 12:38:01 +00003564 if ( fabs(kernel->positive_range + kernel->negative_range) > MagickEpsilon )
anthonyf4e00312010-05-20 12:06:35 +00003565 /* non-zero-summing kernel (generally positive) */
anthony999bb2c2010-02-18 12:38:01 +00003566 pos_scale = fabs(kernel->positive_range + kernel->negative_range);
anthonycc6c8362010-01-25 04:14:01 +00003567 else
anthonyf4e00312010-05-20 12:06:35 +00003568 /* zero-summing kernel */
3569 pos_scale = kernel->positive_range;
anthony999bb2c2010-02-18 12:38:01 +00003570 }
anthony46a369d2010-05-19 02:41:48 +00003571 /* Force kernel into a normalized zero-summing kernel */
anthony999bb2c2010-02-18 12:38:01 +00003572 if ( (normalize_flags&CorrelateNormalizeValue) != 0 ) {
3573 pos_scale = ( fabs(kernel->positive_range) > MagickEpsilon )
3574 ? kernel->positive_range : 1.0;
3575 neg_scale = ( fabs(kernel->negative_range) > MagickEpsilon )
3576 ? -kernel->negative_range : 1.0;
3577 }
3578 else
3579 neg_scale = pos_scale;
3580
3581 /* finialize scaling_factor for positive and negative components */
3582 pos_scale = scaling_factor/pos_scale;
3583 neg_scale = scaling_factor/neg_scale;
anthonycc6c8362010-01-25 04:14:01 +00003584
cristy150989e2010-02-01 14:59:39 +00003585 for (i=0; i < (long) (kernel->width*kernel->height); i++)
anthonycc6c8362010-01-25 04:14:01 +00003586 if ( ! IsNan(kernel->values[i]) )
anthony999bb2c2010-02-18 12:38:01 +00003587 kernel->values[i] *= (kernel->values[i] >= 0) ? pos_scale : neg_scale;
anthonycc6c8362010-01-25 04:14:01 +00003588
anthony999bb2c2010-02-18 12:38:01 +00003589 /* convolution output range */
3590 kernel->positive_range *= pos_scale;
3591 kernel->negative_range *= neg_scale;
3592 /* maximum and minimum values in kernel */
3593 kernel->maximum *= (kernel->maximum >= 0.0) ? pos_scale : neg_scale;
3594 kernel->minimum *= (kernel->minimum >= 0.0) ? pos_scale : neg_scale;
3595
anthony46a369d2010-05-19 02:41:48 +00003596 /* swap kernel settings if user's scaling factor is negative */
anthony999bb2c2010-02-18 12:38:01 +00003597 if ( scaling_factor < MagickEpsilon ) {
3598 double t;
3599 t = kernel->positive_range;
3600 kernel->positive_range = kernel->negative_range;
3601 kernel->negative_range = t;
3602 t = kernel->maximum;
3603 kernel->maximum = kernel->minimum;
3604 kernel->minimum = 1;
3605 }
anthonycc6c8362010-01-25 04:14:01 +00003606
3607 return;
3608}
3609
3610/*
3611%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3612% %
3613% %
3614% %
anthony46a369d2010-05-19 02:41:48 +00003615% S h o w K e r n e l I n f o %
anthony83ba99b2010-01-24 08:48:15 +00003616% %
3617% %
3618% %
3619%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3620%
anthony4fd27e22010-02-07 08:17:18 +00003621% ShowKernelInfo() outputs the details of the given kernel defination to
3622% standard error, generally due to a users 'showkernel' option request.
anthony83ba99b2010-01-24 08:48:15 +00003623%
3624% The format of the ShowKernel method is:
3625%
anthony4fd27e22010-02-07 08:17:18 +00003626% void ShowKernelInfo(KernelInfo *kernel)
anthony83ba99b2010-01-24 08:48:15 +00003627%
3628% A description of each parameter follows:
3629%
3630% o kernel: the Morphology/Convolution kernel
3631%
anthony83ba99b2010-01-24 08:48:15 +00003632*/
anthony4fd27e22010-02-07 08:17:18 +00003633MagickExport void ShowKernelInfo(KernelInfo *kernel)
anthony83ba99b2010-01-24 08:48:15 +00003634{
anthony7a01dcf2010-05-11 12:25:52 +00003635 KernelInfo
3636 *k;
anthony83ba99b2010-01-24 08:48:15 +00003637
anthony43c49252010-05-18 10:59:50 +00003638 unsigned long
anthony7a01dcf2010-05-11 12:25:52 +00003639 c, i, u, v;
3640
3641 for (c=0, k=kernel; k != (KernelInfo *) NULL; c++, k=k->next ) {
3642
anthony46a369d2010-05-19 02:41:48 +00003643 fprintf(stderr, "Kernel");
anthony7a01dcf2010-05-11 12:25:52 +00003644 if ( kernel->next != (KernelInfo *) NULL )
cristye96405a2010-05-19 02:24:31 +00003645 fprintf(stderr, " #%lu", c );
anthony43c49252010-05-18 10:59:50 +00003646 fprintf(stderr, " \"%s",
3647 MagickOptionToMnemonic(MagickKernelOptions, k->type) );
3648 if ( fabs(k->angle) > MagickEpsilon )
3649 fprintf(stderr, "@%lg", k->angle);
anthonya648a302010-05-27 02:14:36 +00003650 fprintf(stderr, "\" of size %lux%lu%+ld%+ld",
anthony43c49252010-05-18 10:59:50 +00003651 k->width, k->height,
3652 k->x, k->y );
anthony7a01dcf2010-05-11 12:25:52 +00003653 fprintf(stderr,
3654 " with values from %.*lg to %.*lg\n",
3655 GetMagickPrecision(), k->minimum,
3656 GetMagickPrecision(), k->maximum);
anthony46a369d2010-05-19 02:41:48 +00003657 fprintf(stderr, "Forming a output range from %.*lg to %.*lg",
anthony7a01dcf2010-05-11 12:25:52 +00003658 GetMagickPrecision(), k->negative_range,
anthony46a369d2010-05-19 02:41:48 +00003659 GetMagickPrecision(), k->positive_range);
3660 if ( fabs(k->positive_range+k->negative_range) < MagickEpsilon )
3661 fprintf(stderr, " (Zero-Summing)\n");
3662 else if ( fabs(k->positive_range+k->negative_range-1.0) < MagickEpsilon )
3663 fprintf(stderr, " (Normalized)\n");
3664 else
3665 fprintf(stderr, " (Sum %.*lg)\n",
3666 GetMagickPrecision(), k->positive_range+k->negative_range);
anthony43c49252010-05-18 10:59:50 +00003667 for (i=v=0; v < k->height; v++) {
anthony46a369d2010-05-19 02:41:48 +00003668 fprintf(stderr, "%2lu:", v );
anthony43c49252010-05-18 10:59:50 +00003669 for (u=0; u < k->width; u++, i++)
anthony7a01dcf2010-05-11 12:25:52 +00003670 if ( IsNan(k->values[i]) )
anthonyf4e00312010-05-20 12:06:35 +00003671 fprintf(stderr," %*s", GetMagickPrecision()+3, "nan");
anthony7a01dcf2010-05-11 12:25:52 +00003672 else
anthonyf4e00312010-05-20 12:06:35 +00003673 fprintf(stderr," %*.*lg", GetMagickPrecision()+3,
anthony7a01dcf2010-05-11 12:25:52 +00003674 GetMagickPrecision(), k->values[i]);
3675 fprintf(stderr,"\n");
3676 }
anthony83ba99b2010-01-24 08:48:15 +00003677 }
3678}
anthonycc6c8362010-01-25 04:14:01 +00003679
3680/*
3681%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3682% %
3683% %
3684% %
anthony43c49252010-05-18 10:59:50 +00003685% U n i t y A d d K e r n a l I n f o %
3686% %
3687% %
3688% %
3689%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3690%
3691% UnityAddKernelInfo() Adds a given amount of the 'Unity' Convolution Kernel
3692% to the given pre-scaled and normalized Kernel. This in effect adds that
3693% amount of the original image into the resulting convolution kernel. This
3694% value is usually provided by the user as a percentage value in the
3695% 'convolve:scale' setting.
3696%
3697% The resulting effect is to either convert a 'zero-summing' edge detection
3698% kernel (such as a "Laplacian", "DOG" or a "LOG") into a 'sharpening'
3699% kernel.
3700%
3701% Alternativally by using a purely positive kernel, and using a negative
3702% post-normalizing scaling factor, you can convert a 'blurring' kernel (such
3703% as a "Gaussian") into a 'unsharp' kernel.
3704%
anthony46a369d2010-05-19 02:41:48 +00003705% The format of the UnityAdditionKernelInfo method is:
anthony43c49252010-05-18 10:59:50 +00003706%
3707% void UnityAdditionKernelInfo(KernelInfo *kernel, const double scale )
3708%
3709% A description of each parameter follows:
3710%
3711% o kernel: the Morphology/Convolution kernel
3712%
3713% o scale:
3714% scaling factor for the unity kernel to be added to
3715% the given kernel.
3716%
anthony43c49252010-05-18 10:59:50 +00003717*/
3718MagickExport void UnityAddKernelInfo(KernelInfo *kernel,
3719 const double scale)
3720{
anthony46a369d2010-05-19 02:41:48 +00003721 /* do the other kernels in a multi-kernel list first */
3722 if ( kernel->next != (KernelInfo *) NULL)
3723 UnityAddKernelInfo(kernel->next, scale);
anthony43c49252010-05-18 10:59:50 +00003724
anthony46a369d2010-05-19 02:41:48 +00003725 /* Add the scaled unity kernel to the existing kernel */
anthony43c49252010-05-18 10:59:50 +00003726 kernel->values[kernel->x+kernel->y*kernel->width] += scale;
anthony46a369d2010-05-19 02:41:48 +00003727 CalcKernelMetaData(kernel); /* recalculate the meta-data */
anthony43c49252010-05-18 10:59:50 +00003728
3729 return;
3730}
3731
3732/*
3733%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3734% %
3735% %
3736% %
3737% Z e r o K e r n e l N a n s %
anthonycc6c8362010-01-25 04:14:01 +00003738% %
3739% %
3740% %
3741%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3742%
3743% ZeroKernelNans() replaces any special 'nan' value that may be present in
3744% the kernel with a zero value. This is typically done when the kernel will
3745% be used in special hardware (GPU) convolution processors, to simply
3746% matters.
3747%
3748% The format of the ZeroKernelNans method is:
3749%
anthony46a369d2010-05-19 02:41:48 +00003750% void ZeroKernelNans (KernelInfo *kernel)
anthonycc6c8362010-01-25 04:14:01 +00003751%
3752% A description of each parameter follows:
3753%
3754% o kernel: the Morphology/Convolution kernel
3755%
anthonycc6c8362010-01-25 04:14:01 +00003756*/
anthonyc4c86e02010-01-27 09:30:32 +00003757MagickExport void ZeroKernelNans(KernelInfo *kernel)
anthonycc6c8362010-01-25 04:14:01 +00003758{
anthony43c49252010-05-18 10:59:50 +00003759 register unsigned long
anthonycc6c8362010-01-25 04:14:01 +00003760 i;
3761
anthony46a369d2010-05-19 02:41:48 +00003762 /* do the other kernels in a multi-kernel list first */
anthony1b2bc0a2010-05-12 05:25:22 +00003763 if ( kernel->next != (KernelInfo *) NULL)
3764 ZeroKernelNans(kernel->next);
3765
anthony43c49252010-05-18 10:59:50 +00003766 for (i=0; i < (kernel->width*kernel->height); i++)
anthonycc6c8362010-01-25 04:14:01 +00003767 if ( IsNan(kernel->values[i]) )
3768 kernel->values[i] = 0.0;
3769
3770 return;
3771}