实现PS中的边缘检测功能(MatLab版)
程序员文章站
2022-03-29 22:46:14
...
初学图像处理时老师布置的第一个任务,用了很多内置的函数,并不是很难实现。
说一下大概的步骤:
1.因为要处理的图像是jpg格式的,不是二维的形式存储的,所以先把RGB三个色域分离开。
%首先分离三个颜色
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
2.分别计算各色域的梯度。
这里注意一下,计算时用uint8会溢出,所以这里我们用一下强制转换(仅仅是计算需要,不能用im2double转换)
%用算子求出三个颜色的梯度值
Rx = imfilter(double(R),fspecial(way));
Ry = imfilter(double(R),fspecial(way)');
Gx = imfilter(double(G),fspecial(way));
Gy = imfilter(double(G),fspecial(way)');
Bx = imfilter(double(B),fspecial(way));
By = imfilter(double(B),fspecial(way)');
3.最后复合一下得到结果:
edge(:,:,1) = uint8(sqrt(Rx.^2+Ry.^2));
edge(:,:,2) = uint8(sqrt(Gx.^2+Gy.^2));
edge(:,:,3) = uint8(sqrt(Bx.^2+By.^2));
figure('NumberTitle','off','Name','获取边缘');
imshow(edge,[]);
%最后取负片,得到PS中的边缘效果
figure('NumberTitle','off','Name','PS边缘');
imshow(imcomplement(edge),[]);
title([way,'算子']);
执行命令运行一下:
>> im = imread('qie.jpg');
>> getEdge(im);
展示一下结果(效果还是相当不错的):
代码如下:
getEdge.m(程序的主代码)
%使用prewitt算子进行边缘检测
%传入的参数为(jpg图片)
%
%From:Yinggang Wang
%Create Date:2018.3.27
%Update:2018.3.30
function [] = getEdge(img)
way = 'prewitt';
%首先分离三个颜色
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
%用算子求出三个颜色的梯度值
Rx = imfilter(double(R),fspecial(way));
Ry = imfilter(double(R),fspecial(way)');
Gx = imfilter(double(G),fspecial(way));
Gy = imfilter(double(G),fspecial(way)');
Bx = imfilter(double(B),fspecial(way));
By = imfilter(double(B),fspecial(way)');
%输出调试内容(封装进函数,不需要注释掉即可)
showPic(Rx,Ry,'红图');
showPic(Gx,Gy,'绿图');
showPic(Bx,By,'蓝图');
%复合
figure('NumberTitle','off','Name','原图');
imshow(img,[]);
edge(:,:,1) = uint8(sqrt(Rx.^2+Ry.^2));
edge(:,:,2) = uint8(sqrt(Gx.^2+Gy.^2));
edge(:,:,3) = uint8(sqrt(Bx.^2+By.^2));
figure('NumberTitle','off','Name','获取边缘');
imshow(edge,[]);
%最后取负片,得到PS中的边缘效果
figure('NumberTitle','off','Name','PS边缘');
imshow(imcomplement(edge),[]);
title([way,'算子']);
showPic.m(用于调试不同色域的处理效果)
%展示某个图像用某种滤波器滤波后的x,y,以及两个方向上复合后的图
function [] = showPic(x,y,name)
figure('NumberTitle','off','Name',name);
subplot(1,3,1);
imshow(x,[]);
title('x');
subplot(1,3,2);
imshow(y,[]);
title('y');
subplot(1,3,3);
imshow(sqrt(x.^2+y.^2),[]);
title('取模');