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