sobel算子matlab代码
时间: 2023-12-27 09:04:00 浏览: 71
MATLAB的sobel算子
以下是Sobel算子的Matlab代码示例:
1. Sobel算子实现图像边缘检测
```
% 读取图像
img = imread('test.jpg');
% 将图像转为灰度图
grayImg = rgb2gray(img);
% Sobel算子进行边缘检测
sobelX = [-1 0 1; -2 0 2; -1 0 1];
sobelY = [-1 -2 -1; 0 0 0; 1 2 1];
imgX = conv2(double(grayImg), double(sobelX), 'same');
imgY = conv2(double(grayImg), double(sobelY), 'same');
imgSobel = sqrt(imgX.^2 + imgY.^2);
% 显示结果
figure, imshow(uint8(imgSobel));
```
2. Sobel算子实现图像锐化
```
% 读取图像
img = imread('test.jpg');
% 将图像转为灰度图
grayImg = rgb2gray(img);
% Sobel算子进行锐化
sobelX = [-1 0 1; -2 0 2; -1 0 1];
sobelY = [-1 -2 -1; 0 0 0; 1 2 1];
imgX = conv2(double(grayImg), double(sobelX), 'same');
imgY = conv2(double(grayImg), double(sobelY), 'same');
imgSharp = grayImg - imgX - imgY;
% 显示结果
figure, imshow(uint8(imgSharp));
```
3. Sobel算子实现图像边缘检测并进行二值化
```
% 读取图像
img = imread('test.jpg');
% 将图像转为灰度图
grayImg = rgb2gray(img);
% Sobel算子进行边缘检测
sobelX = [-1 0 1; -2 0 2; -1 0 1];
sobelY = [-1 -2 -1; 0 0 0; 1 2 1];
imgX = conv2(double(grayImg), double(sobelX), 'same');
imgY = conv2(double(grayImg), double(sobelY), 'same');
imgSobel = sqrt(imgX.^2 + imgY.^2);
% 将结果进行二值化
imgBinary = imbinarize(imgSobel, graythresh(imgSobel));
% 显示结果
figure, imshow(imgBinary);
```
阅读全文