一种十分简单的边缘检测算法

untitled

某天某人在路上走着,思索着如何分辨图像中不同的物体,想到了一种十分简陋的算法(相比于其他专业的算法)。

原理

检测一个像素与周围两个像素的差值,如果差值超过阈值则检测出来(原理就是这么简单😂)。

image-20211025225219662

很快啊,就把这个代码写出来了,但是效果不太理想,主要是图像中的噪点太多了。我发现这些噪点大多都有孤立分布的特点,于是写了个降噪函数。检测哪些点周围的亮点少于指定个数就把那个点变成暗点。

于是噪点少了,但也有一个很严重的问题是,图像的边缘也变窄消失了,于是又编写了一个增强函数,原理与降噪函数相反。

在参数调的较好的情况下可以获得一个不错的效果。

原图

Aston Martin Supercars_Ultra HD

效果图

untitled1

结尾附上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
a=imread('file.jpg');%读入文件名称
t=15;%检测阈值,当一个像素与其他像素差多大时检测出来
s=size(a);
b=zeros(s(1)-1,s(2)-1,3);
d=zeros(s(1)-1,s(2)-1,3);
b1=zeros(s(1)-1,s(2)-1,2);
for i=1:s(1)-1
for j=1:s(2)-1
for k=1:3
b(i,j,k)=a(i,j,k)-a(i+1,j,k);%横向比较
d(i,j,k)=a(i,j,k)-a(i,j+1,k);%纵向比较
end
end
end
for i=1:s(1)-1
for j=1:s(2)-1
b1(i,j,1)=b(i,j,1)+b(i,j,2)+b(i,j,3);%RGB差值求和
b1(i,j,2)=d(i,j,1)+d(i,j,2)+d(i,j,3);
end
end
c=zeros(s(1)-1,s(2)-1);
for i=1:s(1)-1
for j=1:s(2)-1
if b1(i,j,1)>t || b1(i,j,2)>t
c(i,j)=255;
else
c(i,j)=0;
end
end
end
%% 去除噪点,将周围小于5的亮位变暗,两轮
e=decrease(c,5,3);
%% 图像增强,将周围大于6的空位点亮,两轮
e=increase(e,5,4);
%%
imshow(e)
%% 降噪函数
function result=decrease(data,value,times)
result=data;
s=size(data);
for t=1:times
for i=2:s(1)-1
for j=2:s(2)-1
if data(i,j)==255
if data(i-1,j-1)+data(i,j-1)+data(i+1,j-1)+data(i-1,j)+data(i+1,j)+data(i-1,j+1)+data(i,j+1)+data(i+1,j+1)<255*value
result(i,j)=0;
end
end
end
end
data=result;
end
end
%% 图像增强函数
function result=increase(data,value,times)
result=data;
s=size(data);
for t=1:times
for i=2:s(1)-1
for j=2:s(2)-1
if data(i,j)==0
if data(i-1,j-1)+data(i,j-1)+data(i+1,j-1)+data(i-1,j)+data(i+1,j)+data(i-1,j+1)+data(i,j+1)+data(i+1,j+1)>255*value
result(i,j)=255;
end
end
end
end
data=result;
end
end