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边缘检测');
相关推荐
_168168ww31 分钟前
计算机大类常见单词
计算机视觉
CoovallyAIHub1 小时前
OCR战场再起风云:LightOnOCR-1B凭什么比DeepSeekOCR快1.7倍?(附演示开源地址)
深度学习·算法·计算机视觉
zhangrelay1 小时前
如何使用AI快速编程实现标注ROS2中sensor_msgs/msg/Image图像色彩webots2025a
人工智能·笔记·opencv·学习·计算机视觉·机器人视觉
武子康2 小时前
AI研究-120 DeepSeek-OCR 从 0 到 1:上手路线、实战要点
人工智能·深度学习·机器学习·ai·ocr·deepseek·deepseek-ocr
L.EscaRC2 小时前
【AI基础篇】Transformer架构深度解析与前沿应用
人工智能·深度学习·transformer
化作星辰2 小时前
四层神经网络案例(含反向传播)
人工智能·深度学习·神经网络
TYUT_xiaoming2 小时前
ubuntu22.04 GPU环境安装mindspore
linux·人工智能·深度学习
lybugproducer3 小时前
深度学习专题:模型训练的数据并行(三)
人工智能·深度学习·概率论
武子康4 小时前
AI研究-118 具身智能 Mobile-ALOHA 解读:移动+双臂模仿学习的开源方案(含论文/代码/套件链接)
人工智能·深度学习·学习·机器学习·ai·开源·模仿学习
tt5555555555554 小时前
《神经网络与深度学习》学习笔记一
深度学习·神经网络·学习