MATLAB的几种边缘检测算子(Sobel、Prewitt、Laplacian)

MATLAB的几种边缘检测算子(Sobel、Prewitt、Laplacian)

Matlab 复制代码
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-1
    for 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 > 20
            edge_image(i, j) = 1;
        end
    end
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边缘检测');
相关推荐
ghie90908 小时前
基于MATLAB GUI的伏安法测电阻实现方案
开发语言·matlab·电阻
小途软件8 小时前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型
哥布林学者9 小时前
吴恩达深度学习课程五:自然语言处理 第一周:循环神经网络 (五)门控循环单元 GRU
深度学习·ai
薛不痒9 小时前
深度学习之优化模型(数据预处理,数据增强,调整学习率)
深度学习·学习
leo__52010 小时前
基于菲涅耳衍射积分的空心高斯光束传输数值模拟(MATLAB实现)
开发语言·matlab
格林威11 小时前
传送带上运动模糊图像复原:提升动态成像清晰度的 6 个核心方案,附 OpenCV+Halcon 实战代码!
人工智能·opencv·机器学习·计算机视觉·ai·halcon·工业相机
byzh_rc11 小时前
[认知计算] 专栏总结
线性代数·算法·matlab·信号处理
listhi52011 小时前
对LeNet-5的matlab实现,识别MINST手写数字集
开发语言·matlab
棒棒的皮皮11 小时前
【深度学习】YOLO模型速度优化Checklist
人工智能·深度学习·yolo·计算机视觉
FL1717131412 小时前
MATLAB的Sensitivity Analyzer
开发语言·matlab