337
335
Maximize(kernel->maximum, kernel->values[i]);
341
/* sanity check -- no more values in kernel definition */
342
GetMagickToken(p,&p,token);
343
if ( *token != '\0' && *token != ';' && *token != '\'' )
338
/* check that we recieved at least one real (non-nan) value! */
339
if ( kernel->minimum == MagickHuge )
344
340
return(DestroyKernelInfo(kernel));
347
/* this was the old method of handling a incomplete kernel */
348
if ( i < (ssize_t) (kernel->width*kernel->height) ) {
342
/* This should not be needed for a fully defined kernel
343
* Perhaps an error should be reported instead!
344
* Kept for backward compatibility.
346
if ( i < (long) (kernel->width*kernel->height) ) {
349
347
Minimize(kernel->minimum, kernel->values[i]);
350
348
Maximize(kernel->maximum, kernel->values[i]);
351
for ( ; i < (ssize_t) (kernel->width*kernel->height); i++)
349
for ( ; i < (long) (kernel->width*kernel->height); i++)
352
350
kernel->values[i]=0.0;
355
/* Number of values for kernel was not enough - Report Error */
356
if ( i < (ssize_t) (kernel->width*kernel->height) )
357
return(DestroyKernelInfo(kernel));
360
/* check that we recieved at least one real (non-nan) value! */
361
if ( kernel->minimum == MagickHuge )
362
return(DestroyKernelInfo(kernel));
364
if ( (flags & AreaValue) != 0 ) /* '@' symbol in kernel size */
365
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 */
374
static KernelInfo *ParseKernelName(const char *kernel_string)
380
token[MaxTextExtent];
395
/* Parse special 'named' kernel */
396
GetMagickToken(kernel_string,&p,token);
397
type=ParseMagickOption(MagickKernelOptions,MagickFalse,token);
398
if ( type < 0 || type == UserDefinedKernel )
399
return((KernelInfo *)NULL); /* not a valid named kernel */
401
while (((isspace((int) ((unsigned char) *p)) != 0) ||
402
(*p == ',') || (*p == ':' )) && (*p != '\0') && (*p != ';'))
405
end = strchr(p, ';'); /* end of this kernel defintion */
406
if ( end == (char *) NULL )
407
end = strchr(p, '\0');
409
/* ParseGeometry() needs the geometry separated! -- Arrgghh */
410
memcpy(token, p, (size_t) (end-p));
412
SetGeometryInfo(&args);
413
flags = ParseGeometry(token, &args);
416
/* For Debugging Geometry Input */
417
fprintf(stderr, "Geometry = 0x%04X : %lg x %lg %+lg %+lg\n",
418
flags, args.rho, args.sigma, args.xi, args.psi );
421
/* special handling of missing values in input string */
423
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 */
431
args.xi = (double)(((ssize_t)args.rho-1)/2);
432
if ( (flags & YValue) == 0 )
433
args.psi = (double)(((ssize_t)args.sigma-1)/2);
440
/* If no scale given (a 0 scale is valid! - set it to 1.0 */
441
if ( (flags & HeightValue) == 0 )
445
if ( (flags & XValue) == 0 )
448
case ChebyshevKernel:
449
case ManhattanKernel:
450
case EuclideanKernel:
451
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 */
462
kernel = AcquireKernelBuiltIn((KernelInfoType)type, &args);
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 */
467
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);
477
MagickExport KernelInfo *AcquireKernelInfo(const char *kernel_string)
485
token[MaxTextExtent];
497
while ( GetMagickToken(p,NULL,token), *token != '\0' ) {
499
/* ignore extra or multiple ';' kernel seperators */
500
if ( *token != ';' ) {
502
/* tokens starting with alpha is a Named kernel */
503
if (isalpha((int) *token) != 0)
504
new_kernel = ParseKernelName(p);
505
else /* otherwise a user defined kernel array */
506
new_kernel = ParseKernelArray(p);
508
/* Error handling -- this is not proper error handling! */
509
if ( new_kernel == (KernelInfo *) NULL ) {
510
fprintf(stderr, "Failed to parse kernel number #%.20g\n",(double)
512
if ( kernel != (KernelInfo *) NULL )
513
kernel=DestroyKernelInfo(kernel);
514
return((KernelInfo *) NULL);
517
/* initialise or append the kernel list */
518
if ( kernel == (KernelInfo *) NULL )
521
LastKernelInfo(kernel)->next = new_kernel;
524
/* look for the next kernel in list */
526
if ( p == (char *) NULL )
536
357
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
582
396
% radius will be determined so as to produce the best minimal error
583
397
% result, which is usally much larger than is normally needed.
585
% LoG:{radius},{sigma}
586
% "Laplacian of a Gaussian" or "Mexician Hat" Kernel.
587
% The supposed ideal edge detection, zero-summing kernel.
589
% An alturnative to this kernel is to use a "DoG" with a sigma ratio of
590
% approx 1.6 (according to wikipedia).
592
% DoG:{radius},{sigma1},{sigma2}
593
% "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.
598
% 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.
604
% If 'sigma' is zero, you get a single pixel on a field of zeros.
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.
611
% Comet:{width},{sigma},{angle}
612
% Blur in one direction only, much like how a bright object leaves
399
% Blur "{radius},{sigma},{angle}"
400
% As per Gaussian, but generates a 1 dimensional or linear gaussian
401
% blur, at the angle given (current restricted to orthogonal angles).
402
% If a 'radius' is given the kernel is clipped to a width of 2*radius+1.
404
% NOTE that two such blurs perpendicular to each other is equivelent to
405
% -blur and the previous gaussian, but is often 10 or more times faster.
407
% Comet "{width},{sigma},{angle}"
408
% Blur in one direction only, mush like how a bright object leaves
613
409
% a comet like trail. The Kernel is actually half a gaussian curve,
614
% Adding two such blurs in opposite directions produces a Blur Kernel.
615
% Angle can be rotated in multiples of 90 degrees.
410
% Adding two such blurs in oppiste directions produces a Linear Blur.
617
% Note that the first argument is the width of the kernel and not the
412
% NOTE: that the first argument is the width of the kernel and not the
618
413
% radius of the kernel.
620
415
% # Still to be implemented...
417
% # Sharpen "{radius},{sigma}
418
% # Negated Gaussian (center zeroed and re-normalized),
419
% # with a 2 unit positive peak. -- Check On line documentation
421
% # Laplacian "{radius},{sigma}"
422
% # Laplacian (a mexican hat like) Function
424
% # LOG "{radius},{sigma1},{sigma2}
425
% # Laplacian of Gaussian
427
% # DOG "{radius},{sigma1},{sigma2}
428
% # Difference of two Gaussians
624
432
% # Set kernel values using a resize filter, and given scale (sigma)
625
433
% # Cylindrical or Linear. Is this posible with an image?
628
% Named Constant Convolution Kernels
630
% 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
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.
639
% Discrete Lapacian Kernels, (without normalization)
640
% Type 0 : 3x3 with center:8 surounded by -1 (8 neighbourhood)
641
% Type 1 : 3x3 with center:4 edge:-1 corner:0 (4 neighbourhood)
642
% 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
646
% Type 15 : 5x5 LoG (sigma approx 1.4)
647
% Type 19 : 9x9 LoG (sigma approx 1.4)
650
% Sobel 'Edge' convolution kernel (3x3)
655
% Sobel:{type},{angle}
656
% Type 0: default un-nomalized version shown above.
658
% Type 1: As default but pre-normalized
663
% Type 2: Diagonal version with same normalization as 1
669
% Roberts convolution kernel (3x3)
675
% Prewitt Edge convolution kernel (3x3)
681
% Prewitt's "Compass" convolution kernel (3x3)
687
% Kirsch's "Compass" convolution kernel (3x3)
693
% Frei-Chen Edge Detector is based on a kernel that is similar to
694
% the Sobel Kernel, but is designed to be isotropic. That is it takes
695
% into account the distance of the diagonal in the kernel.
698
% | sqrt(2), 0, -sqrt(2) |
701
% FreiChen:{type},{angle}
703
% Frei-Chen Pre-weighted kernels...
705
% Type 0: default un-nomalized version shown above.
707
% Type 1: Orthogonal Kernel (same as type 11 below)
709
% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
712
% Type 2: Diagonal form of Kernel...
714
% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
717
% However this kernel is als at the heart of the FreiChen Edge Detection
718
% Process which uses a set of 9 specially weighted kernel. These 9
719
% kernels not be normalized, but directly applied to the image. The
720
% results is then added together, to produce the intensity of an edge in
721
% a specific direction. The square root of the pixel value can then be
722
% taken as the cosine of the edge, and at least 2 such runs at 90 degrees
723
% from each other, both the direction and the strength of the edge can be
726
% Type 10: All 9 of the following pre-weighted kernels...
728
% Type 11: | 1, 0, -1 |
729
% | sqrt(2), 0, -sqrt(2) | / 2*sqrt(2)
732
% Type 12: | 1, sqrt(2), 1 |
733
% | 0, 0, 0 | / 2*sqrt(2)
736
% Type 13: | sqrt(2), -1, 0 |
737
% | -1, 0, 1 | / 2*sqrt(2)
740
% Type 14: | 0, 1, -sqrt(2) |
741
% | -1, 0, 1 | / 2*sqrt(2)
744
% Type 15: | 0, -1, 0 |
748
% Type 16: | 1, 0, -1 |
752
% Type 17: | 1, -2, 1 |
756
% Type 18: | -2, 1, -2 |
760
% Type 19: | 1, 1, 1 |
764
% The first 4 are for edge detection, the next 4 are for line detection
765
% and the last is to add a average component to the results.
767
% Using a special type of '-1' will return all 9 pre-weighted kernels
768
% as a multi-kernel list, so that you can use them directly (without
769
% normalization) with the special "-set option:morphology:compose Plus"
770
% setting to apply the full FreiChen Edge Detection Technique.
772
% If 'type' is large it will be taken to be an actual rotation angle for
773
% the default FreiChen (type 0) kernel. As such FreiChen:45 will look
774
% like a Sobel:45 but with 'sqrt(2)' instead of '2' values.
776
% WARNING: The above was layed out as per
777
% http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf
778
% But rotated 90 degrees so direction is from left rather than the top.
779
% I have yet to find any secondary confirmation of the above. The only
780
% other source found was actual source code at
781
% http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf
782
% Neigher paper defineds the kernels in a way that looks locical or
783
% correct when taken as a whole.
785
436
% Boolean Kernels
787
% Diamond:[{radius}[,{scale}]]
788
% Generate a diamond shaped kernel with given radius to the points.
438
% Rectangle "{geometry}"
439
% Simply generate a rectangle of 1's with the size given. You can also
440
% specify the location of the 'control point', otherwise the closest
441
% pixel to the center of the rectangle is selected.
443
% Properly centered and odd sized rectangles work the best.
445
% Diamond "[{radius}[,{scale}]]"
446
% Generate a diamond shaped kernal with given radius to the points.
789
447
% Kernel size will again be radius*2+1 square and defaults to radius 1,
790
448
% generating a 3x3 kernel that is slightly larger than a square.
792
% Square:[{radius}[,{scale}]]
450
% Square "[{radius}[,{scale}]]"
793
451
% Generate a square shaped kernel of size radius*2+1, and defaulting
794
452
% to a 3x3 (radius 1).
796
% Note that using a larger radius for the "Square" or the "Diamond" is
797
% also equivelent to iterating the basic morphological method that many
798
% times. However iterating with the smaller radius is actually faster
799
% than using a larger kernel radius.
801
% Rectangle:{geometry}
802
% Simply generate a rectangle of 1's with the size given. You can also
803
% specify the location of the 'control point', otherwise the closest
804
% pixel to the center of the rectangle is selected.
806
% Properly centered and odd sized rectangles work the best.
808
% Disk:[{radius}[,{scale}]]
454
% Note that using a larger radius for the "Square" or the "Diamond"
455
% is also equivelent to iterating the basic morphological method
456
% that many times. However However iterating with the smaller radius 1
457
% default is actually faster than using a larger kernel radius.
459
% Disk "[{radius}[,{scale}]]
809
460
% Generate a binary disk of the radius given, radius may be a float.
810
461
% Kernel size will be ceil(radius)*2+1 square.
811
462
% NOTE: Here are some disk shapes of specific interest
812
% "Disk:1" => "diamond" or "cross:1"
813
% "Disk:1.5" => "square"
814
% "Disk:2" => "diamond:2"
815
% "Disk:2.5" => a general disk shape of radius 2
816
% "Disk:2.9" => "square:2"
817
% "Disk:3.5" => default - octagonal/disk shape of radius 3
818
% "Disk:4.2" => roughly octagonal shape of radius 4
819
% "Disk:4.3" => a general disk shape of radius 4
463
% "disk:1" => "diamond" or "cross:1"
464
% "disk:1.5" => "square"
465
% "disk:2" => "diamond:2"
466
% "disk:2.5" => a general disk shape of radius 2
467
% "disk:2.9" => "square:2"
468
% "disk:3.5" => default - octagonal/disk shape of radius 3
469
% "disk:4.2" => roughly octagonal shape of radius 4
470
% "disk:4.3" => a general disk shape of radius 4
820
471
% After this all the kernel shape becomes more and more circular.
822
473
% Because a "disk" is more circular when using a larger radius, using a
823
474
% larger radius is preferred over iterating the morphological operation.
825
% Symbol Dilation Kernels
827
% These kernel is not a good general morphological kernel, but is used
828
% more for highlighting and marking any single pixels in an image using,
829
% a "Dilate" method as appropriate.
831
% For the same reasons iterating these kernels does not produce the
832
% same result as using a larger radius for the symbol.
834
% Plus:[{radius}[,{scale}]]
835
% Cross:[{radius}[,{scale}]]
836
% Generate a kernel in the shape of a 'plus' or a 'cross' with
837
% a each arm the length of the given radius (default 2).
476
% Plus "[{radius}[,{scale}]]"
477
% Generate a kernel in the shape of a 'plus' sign. The length of each
478
% arm is also the radius, which defaults to 2.
480
% This kernel is not a good general morphological kernel, but is used
481
% more for highlighting and marking any single pixels in an image using,
482
% a "Dilate" or "Erode" method as appropriate.
839
484
% NOTE: "plus:1" is equivelent to a "Diamond" kernel.
841
% Ring:{radius1},{radius2}[,{scale}]
842
% A ring of the values given that falls between the two radii.
843
% Defaults to a ring of approximataly 3 radius in a 7x7 kernel.
844
% This is the 'edge' pixels of the default "Disk" kernel,
845
% More specifically, "Ring" -> "Ring:2.5,3.5,1.0"
847
% Hit and Miss Kernels
849
% Peak:radius1,radius2
850
% Find any peak larger than the pixels the fall between the two radii.
851
% The default ring of pixels is as per "Ring".
853
% Find flat orthogonal edges of a binary shape
855
% Find 90 degree corners of a binary shape
857
% Find end points of lines (for pruning a skeletion)
858
% Two types of lines ends (default to both) can be searched for
859
% Type 0: All line ends
860
% Type 1: single kernel for 4-conneected line ends
861
% Type 2: single kernel for simple line ends
863
% Find three line junctions (within a skeletion)
864
% Type 0: all line junctions
865
% Type 1: Y Junction kernel
866
% Type 2: Diagonal T Junction kernel
867
% Type 3: Orthogonal T Junction kernel
868
% Type 4: Diagonal X Junction kernel
869
% Type 5: Orthogonal + Junction kernel
871
% Find single pixel ridges or thin lines
872
% Type 1: Fine single pixel thick lines and ridges
873
% Type 2: Find two pixel thick lines and ridges
875
% Octagonal thicken kernel, to generate convex hulls of 45 degrees
877
% Traditional skeleton generating kernels.
878
% Type 1: Tradional Skeleton kernel (4 connected skeleton)
879
% Type 2: HIPR2 Skeleton kernel (8 connected skeleton)
880
% Type 3: Experimental Variation to try to present left-right symmetry
881
% Type 4: Experimental Variation to preserve left-right symmetry
486
% Note that unlike other kernels iterating a plus does not produce the
487
% same result as using a larger radius for the cross.
883
489
% Distance Measuring Kernels
885
% Different types of distance measuring methods, which are used with the
886
% a 'Distance' morphology method for generating a gradient based on
887
% distance from an edge of a binary shape, though there is a technique
888
% for handling a anti-aliased shape.
890
% See the 'Distance' Morphological Method, for information of how it is
893
% Chebyshev:[{radius}][x{scale}[%!]]
491
% Chebyshev "[{radius}][x{scale}]" largest x or y distance (default r=1)
492
% Manhatten "[{radius}][x{scale}]" square grid distance (default r=1)
493
% Euclidean "[{radius}][x{scale}]" direct distance (default r=1)
495
% Different types of distance measuring methods, which are used with the
496
% a 'Distance' morphology method for generating a gradient based on
497
% distance from an edge of a binary shape, though there is a technique
498
% for handling a anti-aliased shape.
894
500
% Chebyshev Distance (also known as Tchebychev Distance) is a value of
895
501
% one to any neighbour, orthogonal or diagonal. One why of thinking of
896
502
% it is the number of squares a 'King' or 'Queen' in chess needs to
945
556
nan = sqrt((double)-1.0); /* Special Value : Not A Number */
947
/* Generate a new empty kernel if needed */
948
kernel=(KernelInfo *) NULL;
950
case UndefinedKernel: /* These should not call this function */
951
case UserDefinedKernel:
953
case UnityKernel: /* Named Descrete Convolution Kernels */
954
case LaplacianKernel:
961
case EdgesKernel: /* Hit and Miss kernels */
963
case ThinDiagonalsKernel:
965
case LineJunctionsKernel:
967
case ConvexHullKernel:
969
break; /* A pre-generated kernel is not needed */
971
/* set to 1 to do a compile-time check that we haven't missed anything */
979
case RectangleKernel:
985
case ChebyshevKernel:
986
case ManhattanKernel:
987
case EuclideanKernel:
991
/* Generate the base Kernel Structure */
992
kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
993
if (kernel == (KernelInfo *) NULL)
995
(void) ResetMagickMemory(kernel,0,sizeof(*kernel));
996
kernel->minimum = kernel->maximum = kernel->angle = 0.0;
997
kernel->negative_range = kernel->positive_range = 0.0;
999
kernel->next = (KernelInfo *) NULL;
1000
kernel->signature = MagickSignature;
558
kernel=(KernelInfo *) AcquireMagickMemory(sizeof(*kernel));
559
if (kernel == (KernelInfo *) NULL)
561
(void) ResetMagickMemory(kernel,0,sizeof(*kernel));
562
kernel->minimum = kernel->maximum = 0.0;
563
kernel->negative_range = kernel->positive_range = 0.0;
565
kernel->signature = MagickSignature;
1005
568
/* Convolution Kernels */
1006
569
case GaussianKernel:
1010
sigma = fabs(args->sigma),
1011
sigma2 = fabs(args->xi),
1014
if ( args->rho >= 1.0 )
1015
kernel->width = (size_t)args->rho*2+1;
1016
else if ( (type != DoGKernel) || (sigma >= sigma2) )
1017
kernel->width = GetOptimalKernelWidth2D(args->rho,sigma);
1019
kernel->width = GetOptimalKernelWidth2D(args->rho,sigma2);
1020
kernel->height = kernel->width;
1021
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
571
sigma = fabs(args->sigma);
573
sigma = (sigma <= MagickEpsilon) ? 1.0 : sigma;
575
kernel->width = kernel->height =
576
GetOptimalKernelWidth2D(args->rho,sigma);
577
kernel->x = kernel->y = (long) (kernel->width-1)/2;
578
kernel->negative_range = kernel->positive_range = 0.0;
1022
579
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1023
580
kernel->height*sizeof(double));
1024
581
if (kernel->values == (double *) NULL)
1025
582
return(DestroyKernelInfo(kernel));
1027
/* WARNING: The following generates a 'sampled gaussian' kernel.
1028
* What we really want is a 'discrete gaussian' kernel.
1030
* How to do this is currently not known, but appears to be
1031
* basied on the Error Function 'erf()' (intergral of a gaussian)
1034
if ( type == GaussianKernel || type == DoGKernel )
1035
{ /* Calculate a Gaussian, OR positive half of a DoG */
1036
if ( sigma > MagickEpsilon )
1037
{ A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1038
B = 1.0/(Magick2PI*sigma*sigma);
1039
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1040
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1041
kernel->values[i] = exp(-((double)(u*u+v*v))*A)*B;
1043
else /* limiting case - a unity (normalized Dirac) kernel */
1044
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
1045
kernel->width*kernel->height*sizeof(double));
1046
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1050
if ( type == DoGKernel )
1051
{ /* Subtract a Negative Gaussian for "Difference of Gaussian" */
1052
if ( sigma2 > MagickEpsilon )
1053
{ sigma = sigma2; /* simplify loop expressions */
1054
A = 1.0/(2.0*sigma*sigma);
1055
B = 1.0/(Magick2PI*sigma*sigma);
1056
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1057
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1058
kernel->values[i] -= exp(-((double)(u*u+v*v))*A)*B;
1060
else /* limiting case - a unity (normalized Dirac) kernel */
1061
kernel->values[kernel->x+kernel->y*kernel->width] -= 1.0;
1064
if ( type == LoGKernel )
1065
{ /* Calculate a Laplacian of a Gaussian - Or Mexician Hat */
1066
if ( sigma > MagickEpsilon )
1067
{ A = 1.0/(2.0*sigma*sigma); /* simplify loop expressions */
1068
B = 1.0/(MagickPI*sigma*sigma*sigma*sigma);
1069
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1070
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1071
{ R = ((double)(u*u+v*v))*A;
1072
kernel->values[i] = (1-R)*exp(-R)*B;
1075
else /* special case - generate a unity kernel */
1076
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
1077
kernel->width*kernel->height*sizeof(double));
1078
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1082
/* Note the above kernels may have been 'clipped' by a user defined
1083
** radius, producing a smaller (darker) kernel. Also for very small
1084
** sigma's (> 0.1) the central value becomes larger than one, and thus
1085
** producing a very bright kernel.
1087
** Normalization will still be needed.
1090
/* Normalize the 2D Gaussian Kernel
1092
** NB: a CorrelateNormalize performs a normal Normalize if
1093
** there are no negative values.
1095
CalcKernelMetaData(kernel); /* the other kernel meta-data */
1096
ScaleKernelInfo(kernel, 1.0, CorrelateNormalizeValue);
584
sigma = 2.0*sigma*sigma; /* simplify the expression */
585
for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
586
for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
587
kernel->positive_range += (
589
exp(-((double)(u*u+v*v))/sigma)
590
/* / (MagickPI*sigma) */ );
592
kernel->maximum = kernel->values[
593
kernel->y*kernel->width+kernel->x ];
595
ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1100
599
case BlurKernel:
1102
sigma = fabs(args->sigma),
1105
if ( args->rho >= 1.0 )
1106
kernel->width = (size_t)args->rho*2+1;
1108
kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
601
sigma = fabs(args->sigma);
603
sigma = (sigma <= MagickEpsilon) ? 1.0 : sigma;
605
kernel->width = GetOptimalKernelWidth1D(args->rho,sigma);
606
kernel->x = (long) (kernel->width-1)/2;
1109
607
kernel->height = 1;
1110
kernel->x = (ssize_t) (kernel->width-1)/2;
1112
609
kernel->negative_range = kernel->positive_range = 0.0;
1113
610
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1199
678
if (kernel->values == (double *) NULL)
1200
679
return(DestroyKernelInfo(kernel));
1202
/* A comet blur is half a 1D gaussian curve, so that the object is
681
/* A comet blur is half a gaussian curve, so that the object is
1203
682
** blurred in one direction only. This may not be quite the right
1204
** curve to use so may change in the future. The function must be
1205
** normalised after generation, which also resolves any clipping.
1207
** As we are normalizing and not subtracting gaussians,
1208
** there is no need for a divisor in the gaussian formula
1210
** It is less comples
683
** curve so may change in the future. The function must be normalised.
1212
if ( sigma > MagickEpsilon )
1215
686
#define KernelRank 3
1216
v = (ssize_t) kernel->width*KernelRank; /* start/end points */
1217
(void) ResetMagickMemory(kernel->values,0, (size_t)
1218
kernel->width*sizeof(double));
1219
sigma *= KernelRank; /* simplify the loop expression */
1220
A = 1.0/(2.0*sigma*sigma);
1221
/* B = 1.0/(MagickSQ2PI*sigma); */
1222
for ( u=0; u < v; u++) {
1223
kernel->values[u/KernelRank] +=
1224
exp(-((double)(u*u))*A);
1225
/* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
1227
for (i=0; i < (ssize_t) kernel->width; i++)
1228
kernel->positive_range += kernel->values[i];
687
sigma *= KernelRank; /* simplify expanded curve */
688
v = (long) kernel->width*KernelRank; /* start/end points to fit range */
689
(void) ResetMagickMemory(kernel->values,0, (size_t)
690
kernel->width*sizeof(double));
691
for ( u=0; u < v; u++) {
692
kernel->values[u/KernelRank] +=
693
exp(-((double)(u*u))/(2.0*sigma*sigma))
694
/* / (MagickSQ2PI*sigma/KernelRank) */ ;
696
for (i=0; i < (long) kernel->width; i++)
697
kernel->positive_range += kernel->values[i];
1230
A = 1.0/(2.0*sigma*sigma); /* simplify the loop expression */
1231
/* B = 1.0/(MagickSQ2PI*sigma); */
1232
for ( i=0; i < (ssize_t) kernel->width; i++)
1233
kernel->positive_range +=
1235
exp(-((double)(i*i))*A);
1236
/* exp(-((double)(i*i))/2.0*sigma*sigma)/(MagickSQ2PI*sigma); */
699
for ( i=0; i < (long) kernel->width; i++)
700
kernel->positive_range += (
702
exp(-((double)(i*i))/(2.0*sigma*sigma))
703
/* / (MagickSQ2PI*sigma) */ );
1239
else /* special case - generate a unity kernel */
1240
{ (void) ResetMagickMemory(kernel->values,0, (size_t)
1241
kernel->width*kernel->height*sizeof(double));
1242
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1243
kernel->positive_range = 1.0;
1246
kernel->minimum = 0.0;
1247
706
kernel->maximum = kernel->values[0];
1248
kernel->negative_range = 0.0;
1250
708
ScaleKernelInfo(kernel, 1.0, NormalizeValue); /* Normalize */
1251
709
RotateKernelInfo(kernel, args->xi); /* Rotate by angle */
1255
/* Convolution Kernels - Well Known Constants */
1256
case LaplacianKernel:
1257
{ switch ( (int) args->rho ) {
1259
default: /* laplacian square filter -- default */
1260
kernel=ParseKernelArray("3: -1,-1,-1 -1,8,-1 -1,-1,-1");
1262
case 1: /* laplacian diamond filter */
1263
kernel=ParseKernelArray("3: 0,-1,0 -1,4,-1 0,-1,0");
1266
kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1269
kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 1,-2,1");
1271
case 5: /* a 5x5 laplacian */
1272
kernel=ParseKernelArray(
1273
"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");
1275
case 7: /* a 7x7 laplacian */
1276
kernel=ParseKernelArray(
1277
"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" );
1279
case 15: /* a 5x5 LoG (sigma approx 1.4) */
1280
kernel=ParseKernelArray(
1281
"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");
1283
case 19: /* a 9x9 LoG (sigma approx 1.4) */
1284
/* http://www.cscjournals.org/csc/manuscript/Journals/IJIP/volume3/Issue1/IJIP-15.pdf */
1285
kernel=ParseKernelArray(
1286
"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");
1289
if (kernel == (KernelInfo *) NULL)
1291
kernel->type = type;
1296
{ /* Sobel with optional 'sub-types' */
1297
switch ( (int) args->rho ) {
1300
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1301
if (kernel == (KernelInfo *) NULL)
1303
kernel->type = type;
1306
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1307
if (kernel == (KernelInfo *) NULL)
1309
kernel->type = type;
1310
ScaleKernelInfo(kernel, 0.25, NoValue);
1313
kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1");
1314
if (kernel == (KernelInfo *) NULL)
1316
kernel->type = type;
1317
ScaleKernelInfo(kernel, 0.25, NoValue);
1320
if ( fabs(args->sigma) > MagickEpsilon )
1321
/* Rotate by correctly supplied 'angle' */
1322
RotateKernelInfo(kernel, args->sigma);
1323
else if ( args->rho > 30.0 || args->rho < -30.0 )
1324
/* Rotate by out of bounds 'type' */
1325
RotateKernelInfo(kernel, args->rho);
1329
{ /* Simple Sobel Kernel */
1330
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1331
if (kernel == (KernelInfo *) NULL)
1333
kernel->type = type;
1334
RotateKernelInfo(kernel, args->rho);
1340
kernel=ParseKernelArray("3: 0,0,0 1,-1,0 0,0,0");
1341
if (kernel == (KernelInfo *) NULL)
1343
kernel->type = type;
1344
RotateKernelInfo(kernel, args->rho);
1349
kernel=ParseKernelArray("3: 1,0,-1 1,0,-1 1,0,-1");
1350
if (kernel == (KernelInfo *) NULL)
1352
kernel->type = type;
1353
RotateKernelInfo(kernel, args->rho);
1358
kernel=ParseKernelArray("3: 1,1,-1 1,-2,-1 1,1,-1");
1359
if (kernel == (KernelInfo *) NULL)
1361
kernel->type = type;
1362
RotateKernelInfo(kernel, args->rho);
1367
kernel=ParseKernelArray("3: 5,-3,-3 5,0,-3 5,-3,-3");
1368
if (kernel == (KernelInfo *) NULL)
1370
kernel->type = type;
1371
RotateKernelInfo(kernel, args->rho);
1374
case FreiChenKernel:
1375
/* Direction is set to be left to right positive */
1376
/* http://www.math.tau.ac.il/~turkel/notes/edge_detectors.pdf -- RIGHT? */
1377
/* http://ltswww.epfl.ch/~courstiv/exos_labos/sol3.pdf -- WRONG? */
1378
{ switch ( (int) args->rho ) {
1381
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1382
if (kernel == (KernelInfo *) NULL)
1384
kernel->type = type;
1385
kernel->values[3] = +MagickSQ2;
1386
kernel->values[5] = -MagickSQ2;
1387
CalcKernelMetaData(kernel); /* recalculate meta-data */
1390
kernel=ParseKernelArray("3: 1,2,0 2,0,-2 0,-2,-1");
1391
if (kernel == (KernelInfo *) NULL)
1393
kernel->type = type;
1394
kernel->values[1] = kernel->values[3] = +MagickSQ2;
1395
kernel->values[5] = kernel->values[7] = -MagickSQ2;
1396
CalcKernelMetaData(kernel); /* recalculate meta-data */
1397
ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1400
kernel=AcquireKernelInfo("FreiChen:11;FreiChen:12;FreiChen:13;FreiChen:14;FreiChen:15;FreiChen:16;FreiChen:17;FreiChen:18;FreiChen:19");
1401
if (kernel == (KernelInfo *) NULL)
1406
kernel=ParseKernelArray("3: 1,0,-1 2,0,-2 1,0,-1");
1407
if (kernel == (KernelInfo *) NULL)
1409
kernel->type = type;
1410
kernel->values[3] = +MagickSQ2;
1411
kernel->values[5] = -MagickSQ2;
1412
CalcKernelMetaData(kernel); /* recalculate meta-data */
1413
ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1416
kernel=ParseKernelArray("3: 1,2,1 0,0,0 1,2,1");
1417
if (kernel == (KernelInfo *) NULL)
1419
kernel->type = type;
1420
kernel->values[1] = +MagickSQ2;
1421
kernel->values[7] = +MagickSQ2;
1422
CalcKernelMetaData(kernel);
1423
ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1426
kernel=ParseKernelArray("3: 2,-1,0 -1,0,1 0,1,-2");
1427
if (kernel == (KernelInfo *) NULL)
1429
kernel->type = type;
1430
kernel->values[0] = +MagickSQ2;
1431
kernel->values[8] = -MagickSQ2;
1432
CalcKernelMetaData(kernel);
1433
ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1436
kernel=ParseKernelArray("3: 0,1,-2 -1,0,1 2,-1,0");
1437
if (kernel == (KernelInfo *) NULL)
1439
kernel->type = type;
1440
kernel->values[2] = -MagickSQ2;
1441
kernel->values[6] = +MagickSQ2;
1442
CalcKernelMetaData(kernel);
1443
ScaleKernelInfo(kernel, 1.0/2.0*MagickSQ2, NoValue);
1446
kernel=ParseKernelArray("3: 0,-1,0 1,0,1 0,-1,0");
1447
if (kernel == (KernelInfo *) NULL)
1449
kernel->type = type;
1450
ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1453
kernel=ParseKernelArray("3: 1,0,-1 0,0,0 -1,0,1");
1454
if (kernel == (KernelInfo *) NULL)
1456
kernel->type = type;
1457
ScaleKernelInfo(kernel, 1.0/2.0, NoValue);
1460
kernel=ParseKernelArray("3: 1,-2,1 -2,4,-2 -1,-2,1");
1461
if (kernel == (KernelInfo *) NULL)
1463
kernel->type = type;
1464
ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1467
kernel=ParseKernelArray("3: -2,1,-2 1,4,1 -2,1,-2");
1468
if (kernel == (KernelInfo *) NULL)
1470
kernel->type = type;
1471
ScaleKernelInfo(kernel, 1.0/6.0, NoValue);
1474
kernel=ParseKernelArray("3: 1,1,1 1,1,1 1,1,1");
1475
if (kernel == (KernelInfo *) NULL)
1477
kernel->type = type;
1478
ScaleKernelInfo(kernel, 1.0/3.0, NoValue);
1481
if ( fabs(args->sigma) > MagickEpsilon )
1482
/* Rotate by correctly supplied 'angle' */
1483
RotateKernelInfo(kernel, args->sigma);
1484
else if ( args->rho > 30.0 || args->rho < -30.0 )
1485
/* Rotate by out of bounds 'type' */
1486
RotateKernelInfo(kernel, args->rho);
1490
712
/* Boolean Kernels */
713
case RectangleKernel:
1493
if (args->rho < 1.0)
1494
kernel->width = kernel->height = 3; /* default radius = 1 */
1496
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1497
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1499
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1500
kernel->height*sizeof(double));
1501
if (kernel->values == (double *) NULL)
1502
return(DestroyKernelInfo(kernel));
1504
/* set all kernel values within diamond area to scale given */
1505
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1506
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1507
if ( (labs((long) u)+labs((long) v)) <= (long) kernel->x)
1508
kernel->positive_range += kernel->values[i] = args->sigma;
1510
kernel->values[i] = nan;
1511
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1515
case RectangleKernel:
1518
717
if ( type == SquareKernel )
1520
719
if (args->rho < 1.0)
1521
720
kernel->width = kernel->height = 3; /* default radius = 1 */
1523
kernel->width = kernel->height = (size_t) (2*args->rho+1);
1524
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
722
kernel->width = kernel->height = (unsigned long) (2*args->rho+1);
723
kernel->x = kernel->y = (long) (kernel->width-1)/2;
1525
724
scale = args->sigma;
1528
727
/* NOTE: user defaults set in "AcquireKernelInfo()" */
1529
728
if ( args->rho < 1.0 || args->sigma < 1.0 )
1530
729
return(DestroyKernelInfo(kernel)); /* invalid args given */
1531
kernel->width = (size_t)args->rho;
1532
kernel->height = (size_t)args->sigma;
730
kernel->width = (unsigned long)args->rho;
731
kernel->height = (unsigned long)args->sigma;
1533
732
if ( args->xi < 0.0 || args->xi > (double)kernel->width ||
1534
733
args->psi < 0.0 || args->psi > (double)kernel->height )
1535
734
return(DestroyKernelInfo(kernel)); /* invalid args given */
1536
kernel->x = (ssize_t) args->xi;
1537
kernel->y = (ssize_t) args->psi;
735
kernel->x = (long) args->xi;
736
kernel->y = (long) args->psi;
1540
739
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1581
804
if (args->rho < 1.0)
1582
805
kernel->width = kernel->height = 5; /* default radius 2 */
1584
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1585
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
807
kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
808
kernel->x = kernel->y = (long) (kernel->width-1)/2;
1587
810
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1588
811
kernel->height*sizeof(double));
1589
812
if (kernel->values == (double *) NULL)
1590
813
return(DestroyKernelInfo(kernel));
1592
/* set all kernel values along axises to given scale */
1593
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1594
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
815
/* set all kernel values along axises to 1.0 */
816
for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
817
for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
1595
818
kernel->values[i] = (u == 0 || v == 0) ? args->sigma : nan;
1596
819
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1597
820
kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1602
if (args->rho < 1.0)
1603
kernel->width = kernel->height = 5; /* default radius 2 */
1605
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
1606
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1608
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1609
kernel->height*sizeof(double));
1610
if (kernel->values == (double *) NULL)
1611
return(DestroyKernelInfo(kernel));
1613
/* set all kernel values along axises to given scale */
1614
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
1615
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1616
kernel->values[i] = (u == v || u == -v) ? args->sigma : nan;
1617
kernel->minimum = kernel->maximum = args->sigma; /* a flat shape */
1618
kernel->positive_range = args->sigma*(kernel->width*2.0 - 1.0);
1621
/* HitAndMiss Kernels */
1630
if (args->rho < args->sigma)
1632
kernel->width = ((size_t)args->sigma)*2+1;
1633
limit1 = (ssize_t)(args->rho*args->rho);
1634
limit2 = (ssize_t)(args->sigma*args->sigma);
1638
kernel->width = ((size_t)args->rho)*2+1;
1639
limit1 = (ssize_t)(args->sigma*args->sigma);
1640
limit2 = (ssize_t)(args->rho*args->rho);
1643
kernel->width = 7L, limit1 = 7L, limit2 = 11L;
1645
kernel->height = kernel->width;
1646
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
1647
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
1648
kernel->height*sizeof(double));
1649
if (kernel->values == (double *) NULL)
1650
return(DestroyKernelInfo(kernel));
1652
/* set a ring of points of 'scale' ( 0.0 for PeaksKernel ) */
1653
scale = (ssize_t) (( type == PeaksKernel) ? 0.0 : args->xi);
1654
for ( i=0, v= -kernel->y; v <= (ssize_t)kernel->y; v++)
1655
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
1656
{ ssize_t radius=u*u+v*v;
1657
if (limit1 < radius && radius <= limit2)
1658
kernel->positive_range += kernel->values[i] = (double) scale;
1660
kernel->values[i] = nan;
1662
kernel->minimum = kernel->minimum = (double) scale;
1663
if ( type == PeaksKernel ) {
1664
/* set the central point in the middle */
1665
kernel->values[kernel->x+kernel->y*kernel->width] = 1.0;
1666
kernel->positive_range = 1.0;
1667
kernel->maximum = 1.0;
1673
kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1674
if (kernel == (KernelInfo *) NULL)
1676
kernel->type = type;
1677
ExpandMirrorKernelInfo(kernel); /* mirror expansion of other kernels */
1682
kernel=ParseKernelArray("3: 0,0,- 0,1,1 -,1,-");
1683
if (kernel == (KernelInfo *) NULL)
1685
kernel->type = type;
1686
ExpandRotateKernelInfo(kernel, 90.0); /* Expand 90 degree rotations */
1689
case ThinDiagonalsKernel:
1691
switch ( (int) args->rho ) {
1696
kernel=ParseKernelArray("3: 0,0,0 0,1,1 1,1,-");
1697
if (kernel == (KernelInfo *) NULL)
1699
kernel->type = type;
1700
new_kernel=ParseKernelArray("3: 0,0,1 0,1,1 0,1,-");
1701
if (new_kernel == (KernelInfo *) NULL)
1702
return(DestroyKernelInfo(kernel));
1703
new_kernel->type = type;
1704
LastKernelInfo(kernel)->next = new_kernel;
1705
ExpandMirrorKernelInfo(kernel);
1709
kernel=ParseKernelArray("3: 0,0,0 0,1,1 1,1,-");
1710
if (kernel == (KernelInfo *) NULL)
1712
kernel->type = type;
1713
RotateKernelInfo(kernel, args->sigma);
1716
kernel=ParseKernelArray("3: 0,0,1 0,1,1 0,1,-");
1717
if (kernel == (KernelInfo *) NULL)
1719
kernel->type = type;
1720
RotateKernelInfo(kernel, args->sigma);
1725
case LineEndsKernel:
1726
{ /* Kernels for finding the end of thin lines */
1727
switch ( (int) args->rho ) {
1730
/* set of kernels to find all end of lines */
1731
kernel=AcquireKernelInfo("LineEnds:1>;LineEnds:2>");
1732
if (kernel == (KernelInfo *) NULL)
1736
/* kernel for 4-connected line ends - no rotation */
1737
kernel=ParseKernelArray("3: 0,0,- 0,1,1 0,0,-");
1738
if (kernel == (KernelInfo *) NULL)
1740
kernel->type = type;
1741
RotateKernelInfo(kernel, args->sigma);
1744
/* kernel to add for 8-connected lines - no rotation */
1745
kernel=ParseKernelArray("3: 0,0,0 0,1,0 0,0,1");
1746
if (kernel == (KernelInfo *) NULL)
1748
kernel->type = type;
1749
RotateKernelInfo(kernel, args->sigma);
1752
/* kernel to add for orthogonal line ends - does not find corners */
1753
kernel=ParseKernelArray("3: 0,0,0 0,1,1 0,0,0");
1754
if (kernel == (KernelInfo *) NULL)
1756
kernel->type = type;
1757
RotateKernelInfo(kernel, args->sigma);
1760
/* traditional line end - fails on last T end */
1761
kernel=ParseKernelArray("3: 0,0,0 0,1,- 0,0,-");
1762
if (kernel == (KernelInfo *) NULL)
1764
kernel->type = type;
1765
RotateKernelInfo(kernel, args->sigma);
1770
case LineJunctionsKernel:
1771
{ /* kernels for finding the junctions of multiple lines */
1772
switch ( (int) args->rho ) {
1775
/* set of kernels to find all line junctions */
1776
kernel=AcquireKernelInfo("LineJunctions:1@;LineJunctions:2>");
1777
if (kernel == (KernelInfo *) NULL)
1782
kernel=ParseKernelArray("3: 1,-,1 -,1,- -,1,-");
1783
if (kernel == (KernelInfo *) NULL)
1785
kernel->type = type;
1786
RotateKernelInfo(kernel, args->sigma);
1789
/* Diagonal T Junctions */
1790
kernel=ParseKernelArray("3: 1,-,- -,1,- 1,-,1");
1791
if (kernel == (KernelInfo *) NULL)
1793
kernel->type = type;
1794
RotateKernelInfo(kernel, args->sigma);
1797
/* Orthogonal T Junctions */
1798
kernel=ParseKernelArray("3: -,-,- 1,1,1 -,1,-");
1799
if (kernel == (KernelInfo *) NULL)
1801
kernel->type = type;
1802
RotateKernelInfo(kernel, args->sigma);
1805
/* Diagonal X Junctions */
1806
kernel=ParseKernelArray("3: 1,-,1 -,1,- 1,-,1");
1807
if (kernel == (KernelInfo *) NULL)
1809
kernel->type = type;
1810
RotateKernelInfo(kernel, args->sigma);
1813
/* Orthogonal X Junctions - minimal diamond kernel */
1814
kernel=ParseKernelArray("3: -,1,- 1,1,1 -,1,-");
1815
if (kernel == (KernelInfo *) NULL)
1817
kernel->type = type;
1818
RotateKernelInfo(kernel, args->sigma);
1824
{ /* Ridges - Ridge finding kernels */
1827
switch ( (int) args->rho ) {
1830
kernel=ParseKernelArray("3x1:0,1,0");
1831
if (kernel == (KernelInfo *) NULL)
1833
kernel->type = type;
1834
ExpandRotateKernelInfo(kernel, 90.0); /* 2 rotated kernels (symmetrical) */
1837
kernel=ParseKernelArray("4x1:0,1,1,0");
1838
if (kernel == (KernelInfo *) NULL)
1840
kernel->type = type;
1841
ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotated kernels */
1843
/* Kernels to find a stepped 'thick' line, 4 rotates + mirrors */
1844
/* Unfortunatally we can not yet rotate a non-square kernel */
1845
/* But then we can't flip a non-symetrical kernel either */
1846
new_kernel=ParseKernelArray("4x3+1+1:0,1,1,- -,1,1,- -,1,1,0");
1847
if (new_kernel == (KernelInfo *) NULL)
1848
return(DestroyKernelInfo(kernel));
1849
new_kernel->type = type;
1850
LastKernelInfo(kernel)->next = new_kernel;
1851
new_kernel=ParseKernelArray("4x3+2+1:0,1,1,- -,1,1,- -,1,1,0");
1852
if (new_kernel == (KernelInfo *) NULL)
1853
return(DestroyKernelInfo(kernel));
1854
new_kernel->type = type;
1855
LastKernelInfo(kernel)->next = new_kernel;
1856
new_kernel=ParseKernelArray("4x3+1+1:-,1,1,0 -,1,1,- 0,1,1,-");
1857
if (new_kernel == (KernelInfo *) NULL)
1858
return(DestroyKernelInfo(kernel));
1859
new_kernel->type = type;
1860
LastKernelInfo(kernel)->next = new_kernel;
1861
new_kernel=ParseKernelArray("4x3+2+1:-,1,1,0 -,1,1,- 0,1,1,-");
1862
if (new_kernel == (KernelInfo *) NULL)
1863
return(DestroyKernelInfo(kernel));
1864
new_kernel->type = type;
1865
LastKernelInfo(kernel)->next = new_kernel;
1866
new_kernel=ParseKernelArray("3x4+1+1:0,-,- 1,1,1 1,1,1 -,-,0");
1867
if (new_kernel == (KernelInfo *) NULL)
1868
return(DestroyKernelInfo(kernel));
1869
new_kernel->type = type;
1870
LastKernelInfo(kernel)->next = new_kernel;
1871
new_kernel=ParseKernelArray("3x4+1+2:0,-,- 1,1,1 1,1,1 -,-,0");
1872
if (new_kernel == (KernelInfo *) NULL)
1873
return(DestroyKernelInfo(kernel));
1874
new_kernel->type = type;
1875
LastKernelInfo(kernel)->next = new_kernel;
1876
new_kernel=ParseKernelArray("3x4+1+1:-,-,0 1,1,1 1,1,1 0,-,-");
1877
if (new_kernel == (KernelInfo *) NULL)
1878
return(DestroyKernelInfo(kernel));
1879
new_kernel->type = type;
1880
LastKernelInfo(kernel)->next = new_kernel;
1881
new_kernel=ParseKernelArray("3x4+1+2:-,-,0 1,1,1 1,1,1 0,-,-");
1882
if (new_kernel == (KernelInfo *) NULL)
1883
return(DestroyKernelInfo(kernel));
1884
new_kernel->type = type;
1885
LastKernelInfo(kernel)->next = new_kernel;
1890
case ConvexHullKernel:
1894
/* first set of 8 kernels */
1895
kernel=ParseKernelArray("3: 1,1,- 1,0,- 1,-,0");
1896
if (kernel == (KernelInfo *) NULL)
1898
kernel->type = type;
1899
ExpandRotateKernelInfo(kernel, 90.0);
1900
/* append the mirror versions too - no flip function yet */
1901
new_kernel=ParseKernelArray("3: 1,1,1 1,0,- -,-,0");
1902
if (new_kernel == (KernelInfo *) NULL)
1903
return(DestroyKernelInfo(kernel));
1904
new_kernel->type = type;
1905
ExpandRotateKernelInfo(new_kernel, 90.0);
1906
LastKernelInfo(kernel)->next = new_kernel;
1909
case SkeletonKernel:
1913
switch ( (int) args->rho ) {
1916
/* Traditional Skeleton...
1917
** A cyclically rotated single kernel
1919
kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1920
if (kernel == (KernelInfo *) NULL)
1922
kernel->type = type;
1923
ExpandRotateKernelInfo(kernel, 45.0); /* 8 rotations */
1926
/* HIPR Variation of the cyclic skeleton
1927
** Corners of the traditional method made more forgiving,
1928
** but the retain the same cyclic order.
1930
kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1931
if (kernel == (KernelInfo *) NULL)
1933
kernel->type = type;
1934
new_kernel=ParseKernelArray("3: -,0,0 1,1,0 -,1,-");
1935
if (new_kernel == (KernelInfo *) NULL)
1937
new_kernel->type = type;
1938
LastKernelInfo(kernel)->next = new_kernel;
1939
ExpandRotateKernelInfo(kernel, 90.0); /* 4 rotations of the 2 kernels */
1942
/* Jittered Skeleton: do top, then bottom, then each sides */
1944
kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1945
if (kernel == (KernelInfo *) NULL)
1947
kernel->type = type;
1948
new_kernel=ParseKernelArray("3: 0,0,- 0,1,1 -,1,-");
1949
if (new_kernel == (KernelInfo *) NULL)
1951
new_kernel->type = type;
1952
LastKernelInfo(kernel)->next = new_kernel;
1953
new_kernel=ParseKernelArray("3: -,0,0 1,1,0 -,1,-");
1954
if (new_kernel == (KernelInfo *) NULL)
1956
new_kernel->type = type;
1957
LastKernelInfo(kernel)->next = new_kernel;
1958
/* Do Bottom edge */
1959
new_kernel=ParseKernelArray("3: 1,1,1 -,1,- 0,0,0");
1960
if (new_kernel == (KernelInfo *) NULL)
1962
new_kernel->type = type;
1963
LastKernelInfo(kernel)->next = new_kernel;
1964
new_kernel=ParseKernelArray("3: -,1,- 1,1,0 -,0,0");
1965
if (new_kernel == (KernelInfo *) NULL)
1967
new_kernel->type = type;
1968
LastKernelInfo(kernel)->next = new_kernel;
1969
new_kernel=ParseKernelArray("3: -,1,- 0,1,1 0,0,-");
1970
if (new_kernel == (KernelInfo *) NULL)
1972
new_kernel->type = type;
1973
LastKernelInfo(kernel)->next = new_kernel;
1974
/* Last the two sides */
1975
new_kernel=ParseKernelArray("3: 0,-,1 0,1,1 0,-,1");
1976
if (new_kernel == (KernelInfo *) NULL)
1978
new_kernel->type = type;
1979
LastKernelInfo(kernel)->next = new_kernel;
1980
new_kernel=ParseKernelArray("3: 1,-,0 1,1,0 1,-,0");
1981
if (new_kernel == (KernelInfo *) NULL)
1983
new_kernel->type = type;
1984
LastKernelInfo(kernel)->next = new_kernel;
1987
/* Just a simple 'Edge' kernel, but with a extra two kernels
1988
** to finish off diagonal lines, top then bottom then sides.
1989
** Works well for test case but fails for general case.
1991
kernel=ParseKernelArray("3: 0,0,0 -,1,- 1,1,1");
1992
if (kernel == (KernelInfo *) NULL)
1994
kernel->type = type;
1995
new_kernel=ParseKernelArray("3: 0,0,0 0,1,1 1,1,-");
1996
if (new_kernel == (KernelInfo *) NULL)
1997
return(DestroyKernelInfo(kernel));
1998
new_kernel->type = type;
1999
LastKernelInfo(kernel)->next = new_kernel;
2000
new_kernel=ParseKernelArray("3: 0,0,0 1,1,0 -,1,1");
2001
if (new_kernel == (KernelInfo *) NULL)
2002
return(DestroyKernelInfo(kernel));
2003
new_kernel->type = type;
2004
LastKernelInfo(kernel)->next = new_kernel;
2005
ExpandMirrorKernelInfo(kernel);
2006
/* Append a set of corner kernels */
2007
new_kernel=ParseKernelArray("3: 0,0,- 0,1,1 -,1,-");
2008
if (new_kernel == (KernelInfo *) NULL)
2009
return(DestroyKernelInfo(kernel));
2010
new_kernel->type = type;
2011
ExpandRotateKernelInfo(new_kernel, 90.0);
2012
LastKernelInfo(kernel)->next = new_kernel;
2017
823
/* Distance Measuring Kernels */
2018
824
case ChebyshevKernel:
2020
829
if (args->rho < 1.0)
2021
830
kernel->width = kernel->height = 3; /* default radius = 1 */
2023
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2024
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
832
kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
833
kernel->x = kernel->y = (long) (kernel->width-1)/2;
2026
835
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
2027
836
kernel->height*sizeof(double));
2028
837
if (kernel->values == (double *) NULL)
2029
838
return(DestroyKernelInfo(kernel));
2031
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2032
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
840
scale = (args->sigma < 1.0) ? 100.0 : args->sigma;
841
for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
842
for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
2033
843
kernel->positive_range += ( kernel->values[i] =
2034
args->sigma*((labs((long) u)>labs((long) v)) ? labs((long) u) : labs((long) v)) );
844
scale*((labs(u)>labs(v)) ? labs(u) : labs(v)) );
2035
845
kernel->maximum = kernel->values[0];
2038
case ManhattanKernel:
848
case ManhattenKernel:
2040
853
if (args->rho < 1.0)
2041
854
kernel->width = kernel->height = 3; /* default radius = 1 */
2043
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2044
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
856
kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
857
kernel->x = kernel->y = (long) (kernel->width-1)/2;
2046
859
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
2047
860
kernel->height*sizeof(double));
2048
861
if (kernel->values == (double *) NULL)
2049
862
return(DestroyKernelInfo(kernel));
2051
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2052
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
864
scale = (args->sigma < 1.0) ? 100.0 : args->sigma;
865
for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
866
for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
2053
867
kernel->positive_range += ( kernel->values[i] =
2054
args->sigma*(labs((long) u)+labs((long) v)) );
868
scale*(labs(u)+labs(v)) );
2055
869
kernel->maximum = kernel->values[0];
2058
872
case EuclideanKernel:
2060
877
if (args->rho < 1.0)
2061
878
kernel->width = kernel->height = 3; /* default radius = 1 */
2063
kernel->width = kernel->height = ((size_t)args->rho)*2+1;
2064
kernel->x = kernel->y = (ssize_t) (kernel->width-1)/2;
880
kernel->width = kernel->height = ((unsigned long)args->rho)*2+1;
881
kernel->x = kernel->y = (long) (kernel->width-1)/2;
2066
883
kernel->values=(double *) AcquireQuantumMemory(kernel->width,
2067
884
kernel->height*sizeof(double));
2068
885
if (kernel->values == (double *) NULL)
2069
886
return(DestroyKernelInfo(kernel));
2071
for ( i=0, v=-kernel->y; v <= (ssize_t)kernel->y; v++)
2072
for ( u=-kernel->x; u <= (ssize_t)kernel->x; u++, i++)
888
scale = (args->sigma < 1.0) ? 100.0 : args->sigma;
889
for ( i=0, v=-kernel->y; v <= (long)kernel->y; v++)
890
for ( u=-kernel->x; u <= (long)kernel->x; u++, i++)
2073
891
kernel->positive_range += ( kernel->values[i] =
2074
args->sigma*sqrt((double)(u*u+v*v)) );
892
scale*sqrt((double)(u*u+v*v)) );
2075
893
kernel->maximum = kernel->values[0];
896
/* Undefined Kernels */
897
case LaplacianKernel:
900
perror("Kernel Type has not been defined yet");
2081
/* Unity or No-Op Kernel - Basically just a single pixel on its own */
2082
kernel=ParseKernelArray("1:1");
2083
if (kernel == (KernelInfo *) NULL)
2085
kernel->type = ( type == UnityKernel ) ? UnityKernel : UndefinedKernel;
903
/* Generate a No-Op minimal kernel - 1x1 pixel */
904
kernel->values=(double *)AcquireQuantumMemory((size_t)1,sizeof(double));
905
if (kernel->values == (double *) NULL)
906
return(DestroyKernelInfo(kernel));
907
kernel->width = kernel->height = 1;
908
kernel->x = kernel->x = 0;
909
kernel->type = UndefinedKernel;
911
kernel->positive_range =
912
kernel->values[0] = 1.0; /* a flat single-point no-op kernel! */
2190
% E x p a n d M i r r o r K e r n e l I n f o %
2194
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2196
% ExpandMirrorKernelInfo() takes a single kernel, and expands it into a
2197
% sequence of 90-degree rotated kernels but providing a reflected 180
2198
% rotatation, before the -/+ 90-degree rotations.
2200
% This special rotation order produces a better, more symetrical thinning of
2203
% The format of the ExpandMirrorKernelInfo method is:
2205
% void ExpandMirrorKernelInfo(KernelInfo *kernel)
2207
% A description of each parameter follows:
2209
% o kernel: the Morphology/Convolution kernel
2211
% This function is only internel to this module, as it is not finalized,
2212
% especially with regard to non-orthogonal angles, and rotation of larger
2217
static void FlopKernelInfo(KernelInfo *kernel)
2218
{ /* Do a Flop by reversing each row. */
2226
for ( y=0, k=kernel->values; y < kernel->height; y++, k+=kernel->width)
2227
for ( x=0, r=kernel->width-1; x<kernel->width/2; x++, r--)
2228
t=k[x], k[x]=k[r], k[r]=t;
2230
kernel->x = kernel->width - kernel->x - 1;
2231
angle = fmod(angle+180.0, 360.0);
2235
static void ExpandMirrorKernelInfo(KernelInfo *kernel)
2243
clone = CloneKernelInfo(last);
2244
RotateKernelInfo(clone, 180); /* flip */
2245
LastKernelInfo(last)->next = clone;
2248
clone = CloneKernelInfo(last);
2249
RotateKernelInfo(clone, 90); /* transpose */
2250
LastKernelInfo(last)->next = clone;
2253
clone = CloneKernelInfo(last);
2254
RotateKernelInfo(clone, 180); /* flop */
2255
LastKernelInfo(last)->next = clone;
2261
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2265
% E x p a n d R o t a t e K e r n e l I n f o %
2269
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2271
% ExpandRotateKernelInfo() takes a kernel list, and expands it by rotating
2272
% incrementally by the angle given, until the first kernel repeats.
2274
% WARNING: 45 degree rotations only works for 3x3 kernels.
2275
% While 90 degree roatations only works for linear and square kernels
2277
% The format of the ExpandRotateKernelInfo method is:
2279
% void ExpandRotateKernelInfo(KernelInfo *kernel, double angle)
2281
% A description of each parameter follows:
2283
% o kernel: the Morphology/Convolution kernel
2285
% o angle: angle to rotate in degrees
2287
% This function is only internel to this module, as it is not finalized,
2288
% especially with regard to non-orthogonal angles, and rotation of larger
2292
/* Internal Routine - Return true if two kernels are the same */
2293
static MagickBooleanType SameKernelInfo(const KernelInfo *kernel1,
2294
const KernelInfo *kernel2)
2299
/* check size and origin location */
2300
if ( kernel1->width != kernel2->width
2301
|| kernel1->height != kernel2->height
2302
|| kernel1->x != kernel2->x
2303
|| kernel1->y != kernel2->y )
2306
/* check actual kernel values */
2307
for (i=0; i < (kernel1->width*kernel1->height); i++) {
2308
/* Test for Nan equivelence */
2309
if ( IsNan(kernel1->values[i]) && !IsNan(kernel2->values[i]) )
2311
if ( IsNan(kernel2->values[i]) && !IsNan(kernel1->values[i]) )
2313
/* Test actual values are equivelent */
2314
if ( fabs(kernel1->values[i] - kernel2->values[i]) > MagickEpsilon )
2321
static void ExpandRotateKernelInfo(KernelInfo *kernel, const double angle)
2329
clone = CloneKernelInfo(last);
2330
RotateKernelInfo(clone, angle);
2331
if ( SameKernelInfo(kernel, clone) == MagickTrue )
2333
LastKernelInfo(last)->next = clone;
2336
clone = DestroyKernelInfo(clone); /* kernel has repeated - junk the clone */
2341
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2345
+ C a l c M e t a K e r n a l I n f o %
2349
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2351
% CalcKernelMetaData() recalculate the KernelInfo meta-data of this kernel only,
2352
% using the kernel values. This should only ne used if it is not posible to
2353
% calculate that meta-data in some easier way.
2355
% It is important that the meta-data is correct before ScaleKernelInfo() is
2356
% used to perform kernel normalization.
2358
% The format of the CalcKernelMetaData method is:
2360
% void CalcKernelMetaData(KernelInfo *kernel, const double scale )
2362
% A description of each parameter follows:
2364
% o kernel: the Morphology/Convolution kernel to modify
2366
% WARNING: Minimum and Maximum values are assumed to include zero, even if
2367
% zero is not part of the kernel (as in Gaussian Derived kernels). This
2368
% however is not true for flat-shaped morphological kernels.
2370
% WARNING: Only the specific kernel pointed to is modified, not a list of
2373
% This is an internal function and not expected to be useful outside this
2374
% module. This could change however.
2376
static void CalcKernelMetaData(KernelInfo *kernel)
2381
kernel->minimum = kernel->maximum = 0.0;
2382
kernel->negative_range = kernel->positive_range = 0.0;
2383
for (i=0; i < (kernel->width*kernel->height); i++)
2385
if ( fabs(kernel->values[i]) < MagickEpsilon )
2386
kernel->values[i] = 0.0;
2387
( kernel->values[i] < 0)
2388
? ( kernel->negative_range += kernel->values[i] )
2389
: ( kernel->positive_range += kernel->values[i] );
2390
Minimize(kernel->minimum, kernel->values[i]);
2391
Maximize(kernel->maximum, kernel->values[i]);
2398
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2402
% M o r p h o l o g y A p p l y %
2406
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2408
% MorphologyApply() applies a morphological method, multiple times using
2409
% a list of multiple kernels.
2411
% It is basically equivelent to as MorphologyImageChannel() (see below) but
2412
% without any user controls. This allows internel programs to use this
2413
% function, to actually perform a specific task without posible interference
2414
% by any API user supplied settings.
2416
% It is MorphologyImageChannel() task to extract any such user controls, and
2417
% pass them to this function for processing.
2419
% More specifically kernels are not normalized/scaled/blended by the
2420
% 'convolve:scale' Image Artifact (setting), nor is the convolve bias
2421
% (-bias setting or image->bias) loooked at, but must be supplied from the
2422
% function arguments.
2424
% The format of the MorphologyApply method is:
2426
% Image *MorphologyApply(const Image *image,MorphologyMethod method,
2427
% const ssize_t iterations,const KernelInfo *kernel,
2428
% const CompositeMethod compose, const double bias,
2429
% ExceptionInfo *exception)
2431
% A description of each parameter follows:
2433
% o image: the source image
1009
% M o r p h o l o g y I m a g e C h a n n e l %
1013
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1015
% MorphologyImageChannel() applies a user supplied kernel to the image
1016
% according to the given mophology method.
1018
% The given kernel is assumed to have been pre-scaled appropriatally, usally
1019
% by the kernel generator.
1021
% The format of the MorphologyImage method is:
1023
% Image *MorphologyImage(const Image *image,MorphologyMethod method,
1024
% const long iterations,KernelInfo *kernel,ExceptionInfo *exception)
1025
% Image *MorphologyImageChannel(const Image *image, const ChannelType
1026
% channel,MorphologyMethod method,const long iterations,
1027
% KernelInfo *kernel,ExceptionInfo *exception)
1029
% A description of each parameter follows:
1031
% o image: the image.
2435
1033
% o method: the morphology method to be applied.
2442
1040
% o channel: the channel type.
2444
1042
% o kernel: An array of double representing the morphology kernel.
2446
% o compose: How to handle or merge multi-kernel results.
2447
% If 'UndefinedCompositeOp' use default for the Morphology method.
2448
% If 'NoCompositeOp' force image to be re-iterated by each kernel.
2449
% Otherwise merge the results using the compose method given.
2451
% o bias: Convolution Output Bias.
1043
% Warning: kernel may be normalized for the Convolve method.
2453
1045
% o exception: return any errors or warnings in this structure.
2458
/* Apply a Morphology Primative to an image using the given kernel.
2459
** Two pre-created images must be provided, no image is created.
2460
** It returns the number of pixels that changed betwene the images
2461
** for convergence determination.
2463
static size_t MorphologyPrimitive(const Image *image, Image
1048
% TODO: bias and auto-scale handling of the kernel for convolution
1049
% The given kernel is assumed to have been pre-scaled appropriatally, usally
1050
% by the kernel generator.
1055
/* Internal function
1056
* Apply the Low-Level Morphology Method using the given Kernel
1057
* Returning the number of pixels that changed.
1058
* Two pre-created images must be provided, no image is created.
1060
static unsigned long MorphologyApply(const Image *image, Image
2464
1061
*result_image, const MorphologyMethod method, const ChannelType channel,
2465
const KernelInfo *kernel,const double bias,ExceptionInfo *exception)
1062
const KernelInfo *kernel, ExceptionInfo *exception)
2467
1064
#define MorphologyTag "Morphology/Image"
2483
assert(image != (Image *) NULL);
2484
assert(image->signature == MagickSignature);
2485
assert(result_image != (Image *) NULL);
2486
assert(result_image->signature == MagickSignature);
2487
assert(kernel != (KernelInfo *) NULL);
2488
assert(kernel->signature == MagickSignature);
2489
assert(exception != (ExceptionInfo *) NULL);
2490
assert(exception->signature == MagickSignature);
1081
/* Only the most basic morphology is actually performed by this routine */
1084
Apply Basic Morphology to Image.
2492
1086
status=MagickTrue;
1090
GetMagickPixelPacket(image,&bias);
1091
SetMagickPixelPacketBias(image,&bias);
1092
/* Future: handle auto-bias from user, based on kernel input */
2496
1094
p_view=AcquireCacheView(image);
2497
1095
q_view=AcquireCacheView(result_image);
2499
1097
/* Some methods (including convolve) needs use a reflected kernel.
2500
* Adjust 'origin' offsets to loop though kernel as a reflection.
1098
* Adjust 'origin' offsets for this reflected kernel.
2502
1100
offx = kernel->x;
2503
1101
offy = kernel->y;
2504
1102
switch(method) {
1103
case ErodeMorphology:
1104
case ErodeIntensityMorphology:
1105
/* kernel is user as is, without reflection */
2505
1107
case ConvolveMorphology:
2506
1108
case DilateMorphology:
2507
1109
case DilateIntensityMorphology:
2508
1110
case DistanceMorphology:
2509
/* kernel needs to used with reflection about origin */
2510
offx = (ssize_t) kernel->width-offx-1;
2511
offy = (ssize_t) kernel->height-offy-1;
2513
case ErodeMorphology:
2514
case ErodeIntensityMorphology:
2515
case HitAndMissMorphology:
2516
case ThinningMorphology:
2517
case ThickenMorphology:
2518
/* kernel is used as is, without reflection */
1111
/* kernel needs to used with reflection */
1112
offx = (long) kernel->width-offx-1;
1113
offy = (long) kernel->height-offy-1;
2521
assert("Not a Primitive Morphology Method" != (char *) NULL);
1116
perror("Not a low level Morpholgy Method");
2526
if ( method == ConvolveMorphology && kernel->width == 1 )
2527
{ /* Special handling (for speed) of vertical (blur) kernels.
2528
** This performs its handling in columns rather than in rows.
2529
** This is only done fo convolve as it is the only method that
2530
** generates very large 1-D vertical kernels (such as a 'BlurKernel')
2532
** Timing tests (on single CPU laptop)
2533
** Using a vertical 1-d Blue with normal row-by-row (below)
2534
** time convert logo: -morphology Convolve Blur:0x10+90 null:
2536
** Using this column method
2537
** time convert logo: -morphology Convolve Blur:0x10+90 null:
2540
** Anthony Thyssen, 14 June 2010
2545
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2546
#pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2548
for (x=0; x < (ssize_t) image->columns; x++)
2550
register const PixelPacket
2553
register const IndexPacket
2554
*restrict p_indexes;
2556
register PixelPacket
2559
register IndexPacket
2560
*restrict q_indexes;
2568
if (status == MagickFalse)
2570
p=GetCacheViewVirtualPixels(p_view, x, -offy,1,
2571
image->rows+kernel->height, exception);
2572
q=GetCacheViewAuthenticPixels(q_view,x,0,1,result_image->rows,exception);
2573
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
2578
p_indexes=GetCacheViewVirtualIndexQueue(p_view);
2579
q_indexes=GetCacheViewAuthenticIndexQueue(q_view);
2580
r = offy; /* offset to the origin pixel in 'p' */
2582
for (y=0; y < (ssize_t) image->rows; y++)
2587
register const double
2590
register const PixelPacket
2593
register const IndexPacket
2594
*restrict k_indexes;
2599
/* Copy input image to the output image for unused channels
2600
* This removes need for 'cloning' a new image every iteration
2603
if (image->colorspace == CMYKColorspace)
2604
q_indexes[y] = p_indexes[r];
2606
/* Set the bias of the weighted average output */
2611
result.index = bias;
2614
/* Weighted Average of pixels using reflected kernel
2616
** NOTE for correct working of this operation for asymetrical
2617
** kernels, the kernel needs to be applied in its reflected form.
2618
** That is its values needs to be reversed.
2620
k = &kernel->values[ kernel->height-1 ];
2622
k_indexes = p_indexes;
2623
if ( ((channel & SyncChannels) == 0 ) ||
2624
(image->matte == MagickFalse) )
2625
{ /* No 'Sync' involved.
2626
** Convolution is simple greyscale channel operation
2628
for (v=0; v < (ssize_t) kernel->height; v++) {
2629
if ( IsNan(*k) ) continue;
2630
result.red += (*k)*k_pixels->red;
2631
result.green += (*k)*k_pixels->green;
2632
result.blue += (*k)*k_pixels->blue;
2633
result.opacity += (*k)*k_pixels->opacity;
2634
if ( image->colorspace == CMYKColorspace)
2635
result.index += (*k)*(*k_indexes);
2640
if ((channel & RedChannel) != 0)
2641
q->red = ClampToQuantum(result.red);
2642
if ((channel & GreenChannel) != 0)
2643
q->green = ClampToQuantum(result.green);
2644
if ((channel & BlueChannel) != 0)
2645
q->blue = ClampToQuantum(result.blue);
2646
if ((channel & OpacityChannel) != 0
2647
&& image->matte == MagickTrue )
2648
q->opacity = ClampToQuantum(result.opacity);
2649
if ((channel & IndexChannel) != 0
2650
&& image->colorspace == CMYKColorspace)
2651
q_indexes[x] = ClampToQuantum(result.index);
2654
{ /* Channel 'Sync' Flag, and Alpha Channel enabled.
2655
** Weight the color channels with Alpha Channel so that
2656
** transparent pixels are not part of the results.
2659
alpha, /* alpha weighting of colors : kernel*alpha */
2660
gamma; /* divisor, sum of color weighting values */
2663
for (v=0; v < (ssize_t) kernel->height; v++) {
2664
if ( IsNan(*k) ) continue;
2665
alpha=(*k)*(QuantumScale*(QuantumRange-k_pixels->opacity));
2667
result.red += alpha*k_pixels->red;
2668
result.green += alpha*k_pixels->green;
2669
result.blue += alpha*k_pixels->blue;
2670
result.opacity += (*k)*k_pixels->opacity;
2671
if ( image->colorspace == CMYKColorspace)
2672
result.index += alpha*(*k_indexes);
2677
/* Sync'ed channels, all channels are modified */
2678
gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
2679
q->red = ClampToQuantum(gamma*result.red);
2680
q->green = ClampToQuantum(gamma*result.green);
2681
q->blue = ClampToQuantum(gamma*result.blue);
2682
q->opacity = ClampToQuantum(result.opacity);
2683
if (image->colorspace == CMYKColorspace)
2684
q_indexes[x] = ClampToQuantum(gamma*result.index);
2687
/* Count up changed pixels */
2688
if ( ( p[r].red != q->red )
2689
|| ( p[r].green != q->green )
2690
|| ( p[r].blue != q->blue )
2691
|| ( p[r].opacity != q->opacity )
2692
|| ( image->colorspace == CMYKColorspace &&
2693
p_indexes[r] != q_indexes[x] ) )
2694
changed++; /* The pixel was changed in some way! */
2698
if ( SyncCacheViewAuthenticPixels(q_view,exception) == MagickFalse)
2700
if (image->progress_monitor != (MagickProgressMonitor) NULL)
2705
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2706
#pragma omp critical (MagickCore_MorphologyImage)
2708
proceed=SetImageProgress(image,MorphologyTag,progress++,image->rows);
2709
if (proceed == MagickFalse)
2713
result_image->type=image->type;
2714
q_view=DestroyCacheView(q_view);
2715
p_view=DestroyCacheView(p_view);
2716
return(status ? (size_t) changed : 0);
2720
** Normal handling of horizontal or rectangular kernels (row by row)
2722
1120
#if defined(MAGICKCORE_OPENMP_SUPPORT)
2723
1121
#pragma omp parallel for schedule(dynamic,4) shared(progress,status)
2725
for (y=0; y < (ssize_t) image->rows; y++)
1123
for (y=0; y < (long) image->rows; y++)
2727
1128
register const PixelPacket
3258
1563
assert(exception != (ExceptionInfo *) NULL);
3259
1564
assert(exception->signature == MagickSignature);
3261
count = 0; /* number of low-level morphology primatives performed */
3262
1566
if ( iterations == 0 )
3263
return((Image *)NULL); /* null operation - nothing to do! */
3265
kernel_limit = (size_t) iterations;
3266
if ( iterations < 0 ) /* negative interations = infinite (well alomst) */
3267
kernel_limit = image->columns > image->rows ? image->columns : image->rows;
3269
verbose = ( GetImageArtifact(image,"verbose") != (const char *) NULL ) ?
3270
MagickTrue : MagickFalse;
3272
/* initialise for cleanup */
3273
curr_image = (Image *) image;
3274
work_image = save_image = rslt_image = (Image *) NULL;
3275
reflected_kernel = (KernelInfo *) NULL;
3277
/* Initialize specific methods
3278
* + which loop should use the given iteratations
3279
* + how many primatives make up the compound morphology
3280
* + multi-kernel compose method to use (by default)
1567
return((Image *)NULL); /* null operation - nothing to do! */
1569
/* kernel must be valid at this point
1570
* (except maybe for posible future morphology methods like "Prune"
3282
method_limit = 1; /* just do method once, unless otherwise set */
3283
stage_limit = 1; /* assume method is not a compount */
3284
rslt_compose = compose; /* and we are composing multi-kernels as given */
3286
case SmoothMorphology: /* 4 primative compound morphology */
3289
case OpenMorphology: /* 2 primative compound morphology */
1572
assert(kernel != (KernelInfo *)NULL);
1574
count = 0; /* interation count */
1575
changed = 1; /* if compound method assume image was changed */
1576
curr_kernel = (KernelInfo *)kernel; /* allow kernel and method */
1577
curr_method = method; /* to be changed as nessary */
1579
limit = (unsigned long) iterations;
1580
if ( iterations < 0 )
1581
limit = image->columns > image->rows ? image->columns : image->rows;
1583
/* Third-level morphology methods */
1584
grad_image=(Image *) NULL;
1585
switch( curr_method ) {
1586
case EdgeMorphology:
1587
grad_image = MorphologyImageChannel(image, channel,
1588
DilateMorphology, iterations, curr_kernel, exception);
1590
case EdgeInMorphology:
1591
curr_method = ErodeMorphology;
1593
case EdgeOutMorphology:
1594
curr_method = DilateMorphology;
1596
case TopHatMorphology:
1597
curr_method = OpenMorphology;
1599
case BottomHatMorphology:
1600
curr_method = CloseMorphology;
1603
break; /* not a third-level method */
1606
/* Second-level morphology methods */
1607
switch( curr_method ) {
1608
case OpenMorphology:
1609
/* Open is a Erode then a Dilate without reflection */
1610
new_image = MorphologyImageChannel(image, channel,
1611
ErodeMorphology, iterations, curr_kernel, exception);
1612
if (new_image == (Image *) NULL)
1613
return((Image *) NULL);
1614
curr_method = DilateMorphology;
3290
1616
case OpenIntensityMorphology:
3291
case TopHatMorphology:
1617
new_image = MorphologyImageChannel(image, channel,
1618
ErodeIntensityMorphology, iterations, curr_kernel, exception);
1619
if (new_image == (Image *) NULL)
1620
return((Image *) NULL);
1621
curr_method = DilateIntensityMorphology;
3292
1624
case CloseMorphology:
1625
/* Close is a Dilate then Erode using reflected kernel */
1626
/* A reflected kernel is needed for a Close */
1627
if ( curr_kernel == kernel )
1628
curr_kernel = CloneKernelInfo(kernel);
1629
RotateKernelInfo(curr_kernel,180);
1630
new_image = MorphologyImageChannel(image, channel,
1631
DilateMorphology, iterations, curr_kernel, exception);
1632
if (new_image == (Image *) NULL)
1633
return((Image *) NULL);
1634
curr_method = ErodeMorphology;
3293
1636
case CloseIntensityMorphology:
3294
case BottomHatMorphology:
3295
case EdgeMorphology:
3298
case HitAndMissMorphology:
3299
rslt_compose = LightenCompositeOp; /* Union of multi-kernel results */
3301
case ThinningMorphology:
3302
case ThickenMorphology:
3303
method_limit = kernel_limit; /* iterate the whole method */
3304
kernel_limit = 1; /* do not do kernel iteration */
3310
/* Handle user (caller) specified multi-kernel composition method */
3311
if ( compose != UndefinedCompositeOp )
3312
rslt_compose = compose; /* override default composition for method */
3313
if ( rslt_compose == UndefinedCompositeOp )
3314
rslt_compose = NoCompositeOp; /* still not defined! Then re-iterate */
3316
/* Some methods require a reflected kernel to use with primatives.
3317
* Create the reflected kernel for those methods. */
1637
/* A reflected kernel is needed for a Close */
1638
if ( curr_kernel == kernel )
1639
curr_kernel = CloneKernelInfo(kernel);
1640
RotateKernelInfo(curr_kernel,180);
1641
new_image = MorphologyImageChannel(image, channel,
1642
DilateIntensityMorphology, iterations, curr_kernel, exception);
1643
if (new_image == (Image *) NULL)
1644
return((Image *) NULL);
1645
curr_method = ErodeIntensityMorphology;
3319
1648
case CorrelateMorphology:
3320
case CloseMorphology:
3321
case CloseIntensityMorphology:
3322
case BottomHatMorphology:
3323
case SmoothMorphology:
3324
reflected_kernel = CloneKernelInfo(kernel);
3325
if (reflected_kernel == (KernelInfo *) NULL)
3327
RotateKernelInfo(reflected_kernel,180);
3333
/* Loop 1: iterate the compound method */
3336
while ( method_loop < method_limit && method_changed > 0 ) {
3340
/* Loop 2: iterate over each kernel in a multi-kernel list */
3341
norm_kernel = (KernelInfo *) kernel;
3342
this_kernel = (KernelInfo *) kernel;
3343
rflt_kernel = reflected_kernel;
3346
while ( norm_kernel != NULL ) {
3348
/* Loop 3: Compound Morphology Staging - Select Primative to apply */
3349
stage_loop = 0; /* the compound morphology stage number */
3350
while ( stage_loop < stage_limit ) {
3351
stage_loop++; /* The stage of the compound morphology */
3353
/* Select primative morphology for this stage of compound method */
3354
this_kernel = norm_kernel; /* default use unreflected kernel */
3355
primative = method; /* Assume method is a primative */
3357
case ErodeMorphology: /* just erode */
3358
case EdgeInMorphology: /* erode and image difference */
3359
primative = ErodeMorphology;
3361
case DilateMorphology: /* just dilate */
3362
case EdgeOutMorphology: /* dilate and image difference */
3363
primative = DilateMorphology;
3365
case OpenMorphology: /* erode then dialate */
3366
case TopHatMorphology: /* open and image difference */
3367
primative = ErodeMorphology;
3368
if ( stage_loop == 2 )
3369
primative = DilateMorphology;
3371
case OpenIntensityMorphology:
3372
primative = ErodeIntensityMorphology;
3373
if ( stage_loop == 2 )
3374
primative = DilateIntensityMorphology;
3376
case CloseMorphology: /* dilate, then erode */
3377
case BottomHatMorphology: /* close and image difference */
3378
this_kernel = rflt_kernel; /* use the reflected kernel */
3379
primative = DilateMorphology;
3380
if ( stage_loop == 2 )
3381
primative = ErodeMorphology;
3383
case CloseIntensityMorphology:
3384
this_kernel = rflt_kernel; /* use the reflected kernel */
3385
primative = DilateIntensityMorphology;
3386
if ( stage_loop == 2 )
3387
primative = ErodeIntensityMorphology;
3389
case SmoothMorphology: /* open, close */
3390
switch ( stage_loop ) {
3391
case 1: /* start an open method, which starts with Erode */
3392
primative = ErodeMorphology;
3394
case 2: /* now Dilate the Erode */
3395
primative = DilateMorphology;
3397
case 3: /* Reflect kernel a close */
3398
this_kernel = rflt_kernel; /* use the reflected kernel */
3399
primative = DilateMorphology;
3401
case 4: /* Finish the Close */
3402
this_kernel = rflt_kernel; /* use the reflected kernel */
3403
primative = ErodeMorphology;
3407
case EdgeMorphology: /* dilate and erode difference */
3408
primative = DilateMorphology;
3409
if ( stage_loop == 2 ) {
3410
save_image = curr_image; /* save the image difference */
3411
curr_image = (Image *) image;
3412
primative = ErodeMorphology;
3415
case CorrelateMorphology:
3416
/* A Correlation is a Convolution with a reflected kernel.
3417
** However a Convolution is a weighted sum using a reflected
3418
** kernel. It may seem stange to convert a Correlation into a
3419
** Convolution as the Correlation is the simplier method, but
3420
** Convolution is much more commonly used, and it makes sense to
3421
** implement it directly so as to avoid the need to duplicate the
3422
** kernel when it is not required (which is typically the
3425
this_kernel = rflt_kernel; /* use the reflected kernel */
3426
primative = ConvolveMorphology;
3431
assert( this_kernel != (KernelInfo *) NULL );
3433
/* Extra information for debugging compound operations */
3434
if ( verbose == MagickTrue ) {
3435
if ( stage_limit > 1 )
3436
(void) FormatMagickString(v_info,MaxTextExtent,"%s:%.20g.%.20g -> ",
3437
MagickOptionToMnemonic(MagickMorphologyOptions,method),(double)
3438
method_loop,(double) stage_loop);
3439
else if ( primative != method )
3440
(void) FormatMagickString(v_info, MaxTextExtent, "%s:%.20g -> ",
3441
MagickOptionToMnemonic(MagickMorphologyOptions, method),(double)
3447
/* Loop 4: Iterate the kernel with primative */
3451
while ( kernel_loop < kernel_limit && changed > 0 ) {
3452
kernel_loop++; /* the iteration of this kernel */
3454
/* Create a destination image, if not yet defined */
3455
if ( work_image == (Image *) NULL )
3457
work_image=CloneImage(image,0,0,MagickTrue,exception);
3458
if (work_image == (Image *) NULL)
3460
if (SetImageStorageClass(work_image,DirectClass) == MagickFalse)
3462
InheritException(exception,&work_image->exception);
3467
/* APPLY THE MORPHOLOGICAL PRIMITIVE (curr -> work) */
3469
changed = MorphologyPrimitive(curr_image, work_image, primative,
3470
channel, this_kernel, bias, exception);
3471
kernel_changed += changed;
3472
method_changed += changed;
3474
if ( verbose == MagickTrue ) {
3475
if ( kernel_loop > 1 )
3476
fprintf(stderr, "\n"); /* add end-of-line from previous */
3477
(void) fprintf(stderr, "%s%s%s:%.20g.%.20g #%.20g => Changed %.20g",
3478
v_info,MagickOptionToMnemonic(MagickMorphologyOptions,
3479
primative),(this_kernel == rflt_kernel ) ? "*" : "",
3480
(double) (method_loop+kernel_loop-1),(double) kernel_number,
3481
(double) count,(double) changed);
3483
/* prepare next loop */
3484
{ Image *tmp = work_image; /* swap images for iteration */
3485
work_image = curr_image;
3488
if ( work_image == image )
3489
work_image = (Image *) NULL; /* replace input 'image' */
3491
} /* End Loop 4: Iterate the kernel with primative */
3493
if ( verbose == MagickTrue && kernel_changed != changed )
3494
fprintf(stderr, " Total %.20g",(double) kernel_changed);
3495
if ( verbose == MagickTrue && stage_loop < stage_limit )
3496
fprintf(stderr, "\n"); /* add end-of-line before looping */
3499
fprintf(stderr, "--E-- image=0x%lx\n", (unsigned long)image);
3500
fprintf(stderr, " curr =0x%lx\n", (unsigned long)curr_image);
3501
fprintf(stderr, " work =0x%lx\n", (unsigned long)work_image);
3502
fprintf(stderr, " save =0x%lx\n", (unsigned long)save_image);
3503
fprintf(stderr, " union=0x%lx\n", (unsigned long)rslt_image);
3506
} /* End Loop 3: Primative (staging) Loop for Coumpound Methods */
3508
/* Final Post-processing for some Compound Methods
1649
/* A Correlation is actually a Convolution with a reflected kernel.
1650
** However a Convolution is a weighted sum with a reflected kernel.
1651
** It may seem stange to convert a Correlation into a Convolution
1652
** as the Correleation is the simplier method, but Convolution is
1653
** much more commonly used, and it makes sense to implement it directly
1654
** so as to avoid the need to duplicate the kernel when it is not
1655
** required (which is typically the default).
1657
if ( curr_kernel == kernel )
1658
curr_kernel = CloneKernelInfo(kernel);
1659
RotateKernelInfo(curr_kernel,180);
1660
curr_method = ConvolveMorphology;
1661
/* FALL-THRU into Correlate (weigthed sum without reflection) */
1663
case ConvolveMorphology:
1664
/* Scale or Normalize kernel, according to user wishes
1665
** before using it for the Convolve/Correlate method.
3510
** The removal of any 'Sync' channel flag in the Image Compositon
3511
** below ensures the methematical compose method is applied in a
3512
** purely mathematical way, and only to the selected channels.
3513
** Turn off SVG composition 'alpha blending'.
1667
** FUTURE: provide some way for internal functions to disable
1668
** user bias and scaling effects.
3516
case EdgeOutMorphology:
3517
case EdgeInMorphology:
3518
case TopHatMorphology:
3519
case BottomHatMorphology:
3520
if ( verbose == MagickTrue )
3521
fprintf(stderr, "\n%s: Difference with original image",
3522
MagickOptionToMnemonic(MagickMorphologyOptions, method) );
3523
(void) CompositeImageChannel(curr_image,
3524
(ChannelType) (channel & ~SyncChannels),
3525
DifferenceCompositeOp, image, 0, 0);
3527
case EdgeMorphology:
3528
if ( verbose == MagickTrue )
3529
fprintf(stderr, "\n%s: Difference of Dilate and Erode",
3530
MagickOptionToMnemonic(MagickMorphologyOptions, method) );
3531
(void) CompositeImageChannel(curr_image,
3532
(ChannelType) (channel & ~SyncChannels),
3533
DifferenceCompositeOp, save_image, 0, 0);
3534
save_image = DestroyImage(save_image); /* finished with save image */
3540
/* multi-kernel handling: re-iterate, or compose results */
3541
if ( kernel->next == (KernelInfo *) NULL )
3542
rslt_image = curr_image; /* just return the resulting image */
3543
else if ( rslt_compose == NoCompositeOp )
3544
{ if ( verbose == MagickTrue ) {
3545
if ( this_kernel->next != (KernelInfo *) NULL )
3546
fprintf(stderr, " (re-iterate)");
3548
fprintf(stderr, " (done)");
3550
rslt_image = curr_image; /* return result, and re-iterate */
3552
else if ( rslt_image == (Image *) NULL)
3553
{ if ( verbose == MagickTrue )
3554
fprintf(stderr, " (save for compose)");
3555
rslt_image = curr_image;
3556
curr_image = (Image *) image; /* continue with original image */
3559
{ /* add the new 'current' result to the composition
3561
** The removal of any 'Sync' channel flag in the Image Compositon
3562
** below ensures the methematical compose method is applied in a
3563
** purely mathematical way, and only to the selected channels.
3564
** Turn off SVG composition 'alpha blending'.
3566
** The compose image order is specifically so that the new image can
3567
** be subtarcted 'Minus' from the collected result, to allow you to
3568
** convert a HitAndMiss methd into a Thinning method.
3570
if ( verbose == MagickTrue )
3571
fprintf(stderr, " (compose \"%s\")",
3572
MagickOptionToMnemonic(MagickComposeOptions, rslt_compose) );
3573
(void) CompositeImageChannel(curr_image,
3574
(ChannelType) (channel & ~SyncChannels), rslt_compose,
3576
rslt_image = DestroyImage(rslt_image);
3577
rslt_image = curr_image;
3578
curr_image = (Image *) image; /* continue with original image */
3580
if ( verbose == MagickTrue )
3581
fprintf(stderr, "\n");
3583
/* loop to the next kernel in a multi-kernel list */
3584
norm_kernel = norm_kernel->next;
3585
if ( rflt_kernel != (KernelInfo *) NULL )
3586
rflt_kernel = rflt_kernel->next;
3588
} /* End Loop 2: Loop over each kernel */
3590
} /* End Loop 1: compound method interation */
3594
/* Yes goto's are bad, but it makes cleanup lot more efficient */
3596
if ( curr_image != (Image *) NULL &&
3597
curr_image != rslt_image &&
3598
curr_image != image )
3599
curr_image = DestroyImage(curr_image);
3600
if ( rslt_image != (Image *) NULL )
3601
rslt_image = DestroyImage(rslt_image);
3603
if ( curr_image != (Image *) NULL &&
3604
curr_image != rslt_image &&
3605
curr_image != image )
3606
curr_image = DestroyImage(curr_image);
3607
if ( work_image != (Image *) NULL )
3608
work_image = DestroyImage(work_image);
3609
if ( save_image != (Image *) NULL )
3610
save_image = DestroyImage(save_image);
3611
if ( reflected_kernel != (KernelInfo *) NULL )
3612
reflected_kernel = DestroyKernelInfo(reflected_kernel);
3617
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3621
% M o r p h o l o g y I m a g e C h a n n e l %
3625
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3627
% MorphologyImageChannel() applies a user supplied kernel to the image
3628
% according to the given mophology method.
3630
% This function applies any and all user defined settings before calling
3631
% the above internal function MorphologyApply().
3633
% User defined settings include...
3634
% * Output Bias for Convolution and correlation ("-bias")
3635
% * Kernel Scale/normalize settings ("-set 'option:convolve:scale'")
3636
% This can also includes the addition of a scaled unity kernel.
3637
% * Show Kernel being applied ("-set option:showkernel 1")
3639
% The format of the MorphologyImage method is:
3641
% Image *MorphologyImage(const Image *image,MorphologyMethod method,
3642
% const ssize_t iterations,KernelInfo *kernel,ExceptionInfo *exception)
3644
% Image *MorphologyImageChannel(const Image *image, const ChannelType
3645
% channel,MorphologyMethod method,const ssize_t iterations,
3646
% KernelInfo *kernel,ExceptionInfo *exception)
3648
% A description of each parameter follows:
3650
% o image: the image.
3652
% o method: the morphology method to be applied.
3654
% o iterations: apply the operation this many times (or no change).
3655
% A value of -1 means loop until no change found.
3656
% How this is applied may depend on the morphology method.
3657
% Typically this is a value of 1.
3659
% o channel: the channel type.
3661
% o kernel: An array of double representing the morphology kernel.
3662
% Warning: kernel may be normalized for the Convolve method.
3664
% o exception: return any errors or warnings in this structure.
3668
MagickExport Image *MorphologyImageChannel(const Image *image,
3669
const ChannelType channel,const MorphologyMethod method,
3670
const ssize_t iterations,const KernelInfo *kernel,ExceptionInfo *exception)
3685
/* Apply Convolve/Correlate Normalization and Scaling Factors.
3686
* This is done BEFORE the ShowKernelInfo() function is called so that
3687
* users can see the results of the 'option:convolve:scale' option.
3689
curr_kernel = (KernelInfo *) kernel;
3690
if ( method == ConvolveMorphology || method == CorrelateMorphology )
3692
1670
artifact = GetImageArtifact(image,"convolve:scale");
3693
if ( artifact != (const char *)NULL ) {
1671
if ( artifact != (char *)NULL ) {
3694
1677
if ( curr_kernel == kernel )
3695
1678
curr_kernel = CloneKernelInfo(kernel);
3696
if (curr_kernel == (KernelInfo *) NULL) {
3697
curr_kernel=DestroyKernelInfo(curr_kernel);
1681
flags = ParseGeometry(artifact, &args);
1682
ScaleKernelInfo(curr_kernel, args.rho, flags);
1684
/* FALL-THRU to do the first, and typically the only iteration */
1687
/* Do a single iteration using the Low-Level Morphology method!
1688
** This ensures a "new_image" has been generated, but allows us to skip
1689
** the creation of 'old_image' if no more iterations are needed.
1691
** The "curr_method" should also be set to a low-level method that is
1692
** understood by the MorphologyApply() internal function.
1694
new_image=CloneImage(image,0,0,MagickTrue,exception);
1695
if (new_image == (Image *) NULL)
1696
return((Image *) NULL);
1697
if (SetImageStorageClass(new_image,DirectClass) == MagickFalse)
1699
InheritException(exception,&new_image->exception);
1700
new_image=DestroyImage(new_image);
3698
1701
return((Image *) NULL);
3700
ScaleGeometryKernelInfo(curr_kernel, artifact);
3704
/* display the (normalized) kernel via stderr */
3705
artifact = GetImageArtifact(image,"showkernel");
3706
if ( artifact == (const char *) NULL)
3707
artifact = GetImageArtifact(image,"convolve:showkernel");
3708
if ( artifact == (const char *) NULL)
3709
artifact = GetImageArtifact(image,"morphology:showkernel");
3710
if ( artifact != (const char *) NULL)
3711
ShowKernelInfo(curr_kernel);
3713
/* Override the default handling of multi-kernel morphology results
3714
* If 'Undefined' use the default method
3715
* If 'None' (default for 'Convolve') re-iterate previous result
3716
* Otherwise merge resulting images using compose method given.
3717
* Default for 'HitAndMiss' is 'Lighten'.
3719
compose = UndefinedCompositeOp; /* use default for method */
3720
artifact = GetImageArtifact(image,"morphology:compose");
3721
if ( artifact != (const char *) NULL)
3722
compose = (CompositeOperator) ParseMagickOption(
3723
MagickComposeOptions,MagickFalse,artifact);
3725
/* Apply the Morphology */
3726
morphology_image = MorphologyApply(image, channel, method, iterations,
3727
curr_kernel, compose, image->bias, exception);
3729
/* Cleanup and Exit */
1703
changed = MorphologyApply(image,new_image,curr_method,channel,curr_kernel,
1706
if ( GetImageArtifact(image,"verbose") != (const char *) NULL )
1707
fprintf(stderr, "Morphology %s:%ld => Changed %lu\n",
1708
MagickOptionToMnemonic(MagickMorphologyOptions, curr_method),
1713
/* At this point the "curr_method" should not only be set to a low-level
1714
** method that is understood by the MorphologyApply() internal function,
1715
** but "new_image" should now be defined, as the image to apply the
1716
** "curr_method" to.
1719
/* Repeat the low-level morphology until count or no change reached */
1720
if ( count < (long) limit && changed > 0 ) {
1721
old_image = CloneImage(new_image,0,0,MagickTrue,exception);
1722
if (old_image == (Image *) NULL)
1723
return(DestroyImage(new_image));
1724
if (SetImageStorageClass(old_image,DirectClass) == MagickFalse)
1726
InheritException(exception,&old_image->exception);
1727
old_image=DestroyImage(old_image);
1728
return(DestroyImage(new_image));
1730
while( count < (long) limit && changed != 0 )
1732
Image *tmp = old_image;
1733
old_image = new_image;
1735
changed = MorphologyApply(old_image,new_image,curr_method,channel,
1736
curr_kernel, exception);
1738
if ( GetImageArtifact(image,"verbose") != (const char *) NULL )
1739
fprintf(stderr, "Morphology %s:%ld => Changed %lu\n",
1740
MagickOptionToMnemonic(MagickMorphologyOptions, curr_method),
1743
old_image=DestroyImage(old_image);
1746
/* We are finished with kernel - destroy it if we made a clone */
3730
1747
if ( curr_kernel != kernel )
3731
1748
curr_kernel=DestroyKernelInfo(curr_kernel);
3732
return(morphology_image);
3735
MagickExport Image *MorphologyImage(const Image *image, const MorphologyMethod
3736
method, const ssize_t iterations,const KernelInfo *kernel, ExceptionInfo
3742
morphology_image=MorphologyImageChannel(image,DefaultChannels,method,
3743
iterations,kernel,exception);
3744
return(morphology_image);
1750
/* Third-level Subtractive methods post-processing */
1752
case EdgeOutMorphology:
1753
case EdgeInMorphology:
1754
case TopHatMorphology:
1755
case BottomHatMorphology:
1756
/* Get Difference relative to the original image */
1757
(void) CompositeImageChannel(new_image, channel, DifferenceCompositeOp,
1760
case EdgeMorphology: /* subtract the Erode from a Dilate */
1761
(void) CompositeImageChannel(new_image, channel, DifferenceCompositeOp,
1763
grad_image=DestroyImage(grad_image);