边缘检测算法的基本步骤
(1)滤波。边缘检测主要基于导数计算,但受噪声影响。但滤波器在降低噪声的同时也导致边缘强度的损失。 (2)增强。增强算法将邻域中灰度有显著变化的点突出显示。一般通过计算梯度幅值完成。
(3)检测。但在有些图象中梯度幅值较大的并不是边缘点。最简单的边缘检测是梯度幅值阈值判定。
(4)定位。精确确定边缘的位置。
Canny边缘检测算法
step1:用高斯滤波器平滑图象;
step2:用一阶偏导的有限差分来计算梯度的幅值和方向;
step3:对梯度幅值进行非极大值抑制;
step4:用双阈值算法检测和连接边缘。
效果图如下:
代码如下:
package tools;
import java.awt.*;
import java.awt.image.*;
public class EdgeDetector extends Component {
public EdgeDetector() {
threshold1 = 50;
threshold2 = 230;
setThreshold(128);
setWidGaussianKernel(15);
}
public void process() throws EdgeDetectorException {
if (threshold < 0 || threshold > 255)
throw new EdgeDetectorException("The value of the threshold is out of its valid range.");
if (widGaussianKernel < 3 || widGaussianKernel > 40)
throw new EdgeDetectorException("The value of the widGaussianKernel is out of its valid range.");
width = sourceImage.getWidth(this);
height = sourceImage.getHeight(this);
picsize = width * height;
data = new int[picsize];
magnitude = new int[picsize];
orientation = new int[picsize];
float f = 1.0F;
canny_core(f, widGaussianKernel);
thresholding_tracker(threshold1, threshold2);
for (int i = 0; i < picsize; i++)
if (data[i] > threshold)
data[i] = 0xff000000;
else
data[i] = -1;
edgeImage = pixels2image(data);
data = null;
magnitude = null;
orientation = null;
}
private void canny_core(float f, int i) {
boolean flag = false;
boolean flag1 = false;
derivative_mag = new int[picsize];
float af4[] = new float[i];
float af5[] = new float[i];
float af6[] = new float[i];
data = image2pixels(sourceImage);
int k4 = 0;
do {
if (k4 >= i)
break;
float f1 = gaussian(k4, f);
if (f1 <= 0.005F && k4 >= 2)
break;
float f2 = gaussian((float) k4 - 0.5F, f);
float f3 = gaussian((float) k4 + 0.5F, f);
float f4 = gaussian(k4, f * 0.5F);
af4[k4] = (f1 + f2 + f3) / 3F / (6.283185F * f * f);
af5[k4] = f3 - f2;
af6[k4] = 1.6F * f4 - f1;
k4++;
} while (true);
int j = k4;
float af[] = new float[picsize];