Documente Academic
Documente Profesional
Documente Cultură
Detection.
A Java Implementation – José Iguelmar Miranda
1
Introduction
The aim of this article is to present the Java implementation of the Canny’s filter for
edge detection (Canny, 1986).
Edge detection is one of the most common processes when analyzing digital images,
counting with a great variety of algorithms. Edges carry useful information about
object boundaries which can be used for image analysis, object identification and for
image filtering. Nevertheless, there is no precise and widely accepted mathematical
definition of an edge yet. This is so because the complexity of the image content and
by the interference of high-level vision mechanisms in the human perception of the
boundary of an object (Pitas, 2000). Edges, in the present approach, are transitions
regions between two homogeneous regions in a digital image having different values
for pixels intensity and generally define the borders between the object and its
background. This means that if one can detect the edges, then objects and some of
their features can be measured, like area, perimeter and shape. This is why the edge
detection process is qualified as an essential tool in image analysis.
12
Canny’s Filter for Edge Detection. 2009
Theoretical Aspects
There are some possible definitions for edges, applicable in differing situations. The
most common and generic is ideal step border (Fig. 1a). This is a one dimensional
example, where the edge is simply a change in grey level occurring at one specific
location (x = 125), along the horizontal or absciaaxes. The bigger the gray level difference in
the transition zone, the easier to detect edges. But, in real world, complexity happens.
For instance, the quantization process realized by a satellite, the scene sampling not
always can make a precise match between real object edges and the pixels that will
represent them. Commonly, happens what is shown in Fig. 1b. In this case, the
position of the edge is considered to be the center of the ramp connecting the low
grey level to the high one.
2 25
1 75
N ível de
cinza 1 25
75
25
0
0 25 75 12 5 17 5 225 25 0
x
Figure 1a. Ideal border example.
3
225
175
Nível de
cinza 125
75
25
0
0 25 75 125 175 225 250
x
An additional difficulty has to do with the ubiquitous problem of noise. Due to some
factors, like sun light intensity, camera model and lens, satellite movement, air
temperature, atmospheric effects, among others, it is unlike that two pixels with the
same gray level in the ground will have the same gray level in the digital image.
Noises are random and systematic. Random noises are only characterized by a
statistical distribution. Systematic noises are easier to detect and to remove. The net
effect of noises in the image is to produce a random variation in the gray level values
of the pixels, such that the ideal edge shown in Fig. 1 is not found in real images.
That said, it is not possible to ignore the presence of random noise in images. The
problem is that this noise cannot be identified and measured precisely, since one
cannot differentiate its contribution in the pixels gray level values. Happily,
sometimes, the random noise can be characterized by its effect in the image,
expressed as a probability distribution with specific values of mean and standard
deviation (Parker, 1997). So, before working with an image, it is necessary to filter
this kind of noise, normally using an edge detection process.
Since a border is defined as a change in the gray level, an operator that is sensible to
this change has a task to detect edge. Generally, edge operators can be classified in
three groups: (1) those based on partial derivatives, approximated by differences in
the discrete case, whose task is to identify spots where there are great intensity
12
Canny’s Filter for Edge Detection. 2009
changes; (2) those that model the border with a small dimension kernel; and (3)
those that use mathematical models for the borders, using partial differential
equations, or diffusion models, that search for the maxima and minima of a function.
The approach used here is a mix between (1) and (2).
1. Good detection – there should be a low probability of failing to mark real edge
points, and low probability of falsely marking nonedge points. This criterion
corresponds to maximizing signal-to-noise ratio.
2. Localization – the distance between the edge pixels as found by the edge
detector and the actual edge should be as small as possible.
3. Response – only one response to a single edge. Where there are two responses
to the same edge, one of them must be considered false.
The response of the filter to this edge, centered at HG, was given by a convolution
integral (Canny, 1986):
w
HG G ( x) f ( x)dx (1)
w
5
Where the filter has a finite impulse response bounded by [-w, w], and zero out of
this interval. To the noise, n(x), consider the root-mean-squared response (Canny,
1986):
1
w 2
H n n 0 f 2 ( x)dx )
(2
w
Where n02 is the mean-squared noise amplitude per unit length. So, the first criterion,
the output signal-to-noise ration, can be formalized as the quotient of these two
responses (Canny, 1986):
W
G( x) f ( x) dx
W
SNR )
(3
w
n0 f 2 ( x) dx
w
For the second criterion, Canny considered some measure that increased as
localization improved, using the root-mean-squared distance between the marked
edges from the center of the true edge. Edges marking happened in local maxima in
the response of the operator f(x), i.e., where its first derivative was zero. The reader
can obtain further details in Canny’s article, for finding the localization measure:
W
G ( x) f ( x)dx
W
Localização )
(4
w
2
n0 f ( x)dx
w
Canny showed that using only the first two criteria, the optimal detector for step
edges with noise is a truncated step (Fig. 2a), similar to using a difference of boxes
filter (Fig. 2c).
12
Canny’s Filter for Edge Detection. 2009
x - w/2 x + w/2
This filter, however, has a very high bandwidth and tends to exhibit many maxima in
its response to noisy step edges, which should be considered erroneous according to
the first criterion. The mean distance between adjacent maxima and the noise output
of f(x), called x max, will restrict the selection of f(x) according to a single criterion, the
third:
Where k is some fraction of the operator width, w. Due to the complexity of the
formulation, no analytical solution was found. A variant was developed, enabling the
edge detection. For small values of xmax, the Canny’s operator becomes close to the
action of a difference of boxes filter (Fig. 1c). For bigger values of xmax, it becomes
close to the action of a filter of the first derivative of a Gaussian function (Fig. 1b),
also known as derivative of Gaussian (DoG).
In two dimensions, an edge also has an orientation, meaning the direction of the
direction of the tangent to the contour that the edge defines in two directions. Canny
created a two-dimensional mask for this orientation by convolving a linear edge
detection function aligned normal to the edge direction with a projection function
parallel to the edge direction. In two dimensions, the Gaussian function is given by:
7
x2 y2
G ( x, y ) 2 exp 2
)
(6
2
Hence, the approximation of the Canny’s optimal filter for edge detection is G’ (first
derivative), and so by convolving the input image with G’ we obtain an image E that
has enhanced edges, even in the presence of noise, which has been incorporated into
the model of the edge image.
Fig. 3 shows the approximated effect of the DoG filter (Fig. 2a, and difference of
boxes, Fig. 2c) in the signal shown in Fig. 2a. The filtered signal with the difference of
boxes filter shows local maxima problems.
(a) (b)
Figure 3. Effects of the filters DoG and difference of boxes in the signal shown in Fig.
2a.
12
Canny’s Filter for Edge Detection. 2009
work. In the following sections, the reader is presented with the whole source code of
the application. You can add it to an IDE, like NetBeans or Eclipse, or simply compile
and execute through a DOS/Term prompt. Initially, it was developed to run in
Windows environment, using a DOS prompt. The filter implementation was
developed as a pure Java application, containing only the constructor, called from the
main() method. In Windows, the compilation is done calling:
To execute it:
Values of the standard deviation and thresholds must be tested by the user, till he
founds an output image with good result. At this point, we suggest the construction of
a graphical interface that allows dynamical change in these values, as of using the
JSlider.
Where:
3. inf, sup: low and high hysteresis threshold values. Any pixel in the image that
has a value greater than highTh is presumed to be an edge pixel, and is marked
as such. Then, pixels that are connected to this edge pixel and that have a value
greater than lowTh are also selected as edge pixels, and are marked too.
The constructor has four tasks: (1) read the input image to be filtered; (2) call the
canny method, that implements the Canny filter; (3) define the edge pixels, using the
parameters values (lowTh and highTh); and (4) shows the output (filtered) image. The
canny method implements the main steps of the algorithm, described as (Parker,
1997):
4. Convolve the image I with G along the rows to give the x component image Ix,
and down the columns to give the y component image Iy.
convolveImagemXY(imagem, funcGauss, width, componenteX,
componenteY);
5. Convolve Ix with Gx to give Ix’, the x component of I convolved with the
derivative of the Gaussian, and convolve Iy with Gy to give Iy’.
derivadaX = convolveDerivadaXY(componenteX, nr, nc,
derivadaGauss, width, 1);
derivadaY = convolveDerivadaXY(componenteY, nr, nc,
derivadaGauss, width, 0);
6. The magnitude of the result is computed at each pixel (x, y) as:
z = norma(derivadaX[j][i], derivadaY[j][i]);
M ( x, y) I x ( x, y ) 2 I y ( x, y ) 2
12
Canny’s Filter for Edge Detection. 2009
/*********************************************************************
FiltroCanny.java – implements the Canny filter.
PERMISSION TO COPY:
This program is free software, under the GNU General Public License
(GPL); permission to use, copy and modify this software and its
documentation for NON-COMMERCIAL purposes is granted, without fee, provided
that an acknowledgement to the authors, José Iguelmar Miranda & João
Camargo Neto, at www.cnptia.embrapa.br, appears in all copies.
*********************************************************************
Description:
Reference paper:
*********************************************************************/
// Generic packages
import java.io.File;
// AWT packages
import java.awt.image.WritableRaster;
1
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.GridLayout;
// Attributes
// Image scale and magnitude
static double ORI_SCALE = 40.0;
static double MAG_SCALE = 20.0;
// Parameters ok?
if (args.length != 4) {
String msga = "Uso: java -cp . FiltroCanny <imagem> <dp> <inf>
<sup>";
String msgb = "\n dp => standard deviation.";
String msgc = "\n inf => LOW threshold.";
String msgd = "\n sup => HIGH threshold.";
System.out.println(msga + msgb + msgc + msgd);
System.exit(0);
}
try {
dp = Double.parseDouble(args[1]);
} catch (NumberFormatException e) {
System.out.println("Valor do parametro <dp> invalido");
System.exit(0);
}
12
Canny’s Filter for Edge Detection. 2009
try {
inf = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println("Valor do parametro <inf> invalido");
System.exit(0);
}
try {
sup = Integer.parseInt(args[3]);
} catch (NumberFormatException e) {
System.out.println("Valor do parametro <sup> invalido");
System.exit(0);
}
// Create gridLayout de 1 x 1
getContentPane().setLayout(new GridLayout(1, 1));
img1 = new JLabel(new ImageIcon(imagem));
setSize(w, h);
getContentPane().add(new JScrollPane(img1));
}
12
Canny’s Filter for Edge Detection. 2009
n = 2*width + 1;
LARGURA = (int)width/2;
System.out.println("Suavizando com uma Gaussiana (largura = " +
n + ") ...\n");
magWR.setSample(j, i, 0, (int)z*MAG_SCALE);
}
z = (gauss(x,sigma)+gauss(x+0.5,sigma)+gauss(x-0.5,sigma))/3.0;
z = z/(Math.PI*2.0*sigma*sigma);
return z;
}
if (sigma == 0)
return 0.0;
expoente = Math.exp(((-x*x)/(2*sigma*sigma)));
return expoente;
}
nc = imagem.getWidth();
nr = imagem.getHeight();
12
Canny’s Filter for Edge Detection. 2009
i1 = (j+k)%nc;
i2 = (j-k+nc)%nc;
x += funcGauss[k]*imR.getSample(i1, i, 0) +
funcGauss[k]*imR.getSample(i2, i, 0);
}
compX[j][i] = x;
compY[j][i] = y;
}
}
nc = imagemMag.getWidth();
nr = imagemMag.getHeight();
12
Canny’s Filter for Edge Detection. 2009
nc = imagem.getWidth();
nr = imagem.getHeight();
WritableRaster imWR = imagem.getRaster();
Raster imR = imagem.getRaster();
Raster magR = imagemMag.getRaster();
// For each edge with magnitude above HIGH threshold, draw the edge
// pixels that are above the LOW threshold
for (int i = 0; i < nr; i++)
for (int j = 0; j < nc; j++)
if (magR.getSample(j, i, 0) >= sup)
trace(i, j, inf, imagem, imagemMag, imagemOrig);
imWR.setSample(j, i, 0, 255);
else
imWR.setSample(j, i, 0, 0);
}
nc = imagemMag.getWidth();
nr = imagemMag.getHeight();
histograma = new int[256];
Raster magR = imagemMag.getRaster();
// Image histogram
for (k = 0; k < 256; k++)
histograma[k] = 0;
count = histograma[255];
while (count < j) {
k--;
if (k < 0)
break;
count += histograma[k];
}
hi = k;
i = 0;
while (histograma[i] == 0)
i++;
inf = (int)(hi+i)/2;
}
int n, m;
int flag = 0;
12
Canny’s Filter for Edge Detection. 2009
if (imR.getSample(j, i, 0) == 0) {
imWR.setSample(j, i, 0, 255);
flag = 0;
for (n = -1; n <= 1; n++) {
for(m = -1; m <= 1; m++) {
if (i == 0 && m == 0)
continue;
if ((range(imagemMag, i+n, j+m) == 1) &&
(magR.getSample(j+m, i+n, 0)) >= inf)
if (trace(i+n,j+m,inf,imagem,imagemMag,imagemOrig) == 1) {
flag = 1;
break;
}
}
if (flag == 1)
break;
}
return 1;
}
return 0;
}
nc = imagem.getWidth();
nr = imagem.getHeight();
if ((i < 0) || (i >= nr))
return 0;
if ((j < 0) || (j >= nc))
return 0;
return 1;
}
}
1
2
Case Study
The following pictures show the application of the Canny’s filter for edge detection. In
all pictures, the threshold values were inf = 10 and sup = 20. Only the standard
deviation values were changed, showing a different behavior of the filter. The first
picture shows edge detection for simple objects.
Figure 4. (a) Input image; (b) standard deviation = 1.5; (c) standard deviation = 2.6
Fig. 4(a) shows the source image. In Fig. 4(b) the standard deviation value was 1.5,
and in Fig. 4(c), the standard deviation was 2.6. The first value of the standard
deviation allows the filter to detect edges of the objects, but has some side effects,
because a lot of noise, from the background, is by passing. Increasing the standard
deviation value, the noise is filtered, yielding a better result.
Fig. 5 shows a different image, with agricultural exploitation. In this image one can
see two center pivot (circle area), bare soil (white), sugar-cane and riparian
vegetation along some creeks. The first image was filtered with a standard deviation
of 1.5. As happened with the previous image, this standard deviation value allows the
present of noise, which, actually, are edges of small objects present in the image.
Visually, the result is not good. Increasing the standard deviation value permits to
filter the edges of the small objects, “cleaning” the final image, with a better visual
appeal. As one increases the standard deviation value, the output image becomes
much clean, but at the expense of obtaining an image with less edges.
12
Canny’s Filter for Edge Detection. 2009
Figure 5. (a) Input image; (b) standard deviation = 1.5; (c) standard deviation = 2.2
Fig. 6 is a medical image, with a set of globules. The first filter used a standard
deviation of 1.5, with result similar to the previous images. The second filter used a
standard deviation of 2.6, with a better visual output image. In this image, with only
simple objects, the result is better, as happened with Fig. 4. When the image presents
a different set of objects with more nuances, the filtering process must be conducted
with care to identify the targets.
Figure 6. (a) Input image; (b) standard deviation = 1.5; (c) standard deviation = 2.6
Bibliography
PARKER, J.R. Algorithms for image processing and computer vision. New
York, NY: John Wiley & Sons, 1997. 417p.
3
2
12