MATLAB的几种边缘检测算子(Sobel、Prewitt、Laplacian)
clc;close all;clear all;warning off;%清除变量
rand('seed', 100);
randn('seed', 100);
format long g;% 读取图像
image = imread('lena.png');
% 转换为灰度图像
gray_image = rgb2gray(image);
% 转换为double类型以进行计算
gray_image = double(gray_image);% 定义Sobel算子
sobel_x = [-1 0 1; -2 0 2; -1 0 1];
sobel_y = [1 2 1; 0 0 0; -1 -2 -1];% 计算图像大小
[height, width] = size(gray_image);
% 初始化输出图像
edge_image = zeros(height, width);% 对图像进行卷积以检测边缘
for i = 2:height-1for j = 2:width-1% 提取3x3邻域neighborhood = gray_image(i-1:i+1, j-1:j+1);% 计算x和y方向的梯度gradient_x = sum(sum(sobel_x .* neighborhood));gradient_y = sum(sum(sobel_y .* neighborhood));% 计算梯度幅度gradient_magnitude = sqrt(gradient_x^2 + gradient_y^2);% 设置阈值,将梯度幅度大于阈值的像素点视为边缘if gradient_magnitude > 20edge_image(i, j) = 1;endend
end% 显示结果
figure;
imshow(image);
title('原图');figure;
imshow(edge_image);
title('Sobel边缘检测');% 定义Prewitt算子
prewitt_x = [-1 0 1; -1 0 1; -1 0 1] / 3;
prewitt_y = [-1 -1 -1; 0 0 0; 1 1 1] / 3;% 使用MATLAB内置函数conv2进行卷积
gradient_x = conv2(gray_image, prewitt_x, 'same');
gradient_y = conv2(gray_image, prewitt_y, 'same');% 计算梯度幅度
gradient_magnitude = sqrt(gradient_x.^2 + gradient_y.^2);% 设置阈值并进行二值化处理,得到边缘图像
edge_image = gradient_magnitude > 0.1; % 阈值可根据实际情况调整% 显示原图像% 显示边缘检测后的图像
figure;
imshow(edge_image);
title('Prewitt边缘检测');% 定义Laplacian算子
laplacian_mask = [0 1 0; 1 -4 1; 0 1 0];% 使用MATLAB内置函数conv2进行卷积
laplacian_image = conv2(gray_image, laplacian_mask, 'same');% Laplacian算子会增强图像中的噪声,因此通常需要先对图像进行平滑处理
% 这里我们可以使用Gaussian滤波进行平滑
smoothed_image = imgaussfilt(gray_image, 2); % 第二个参数是高斯核的标准差
laplacian_image_smoothed = conv2(smoothed_image, laplacian_mask, 'same');% 为了可视化,将Laplacian处理后的图像进行零均值化处理
laplacian_image_smoothed = laplacian_image_smoothed - mean(laplacian_image_smoothed(:));% 显示Laplacian边缘检测后的图像
figure;
imshow(laplacian_image_smoothed); % []使得imshow自动调整显示范围
title('Laplacian边缘检测');