边缘提取
图像取边缘是基于像素梯度方法实现的,原理是把图像的灰度看成2维曲面,边缘是曲面的突变部分,利用求梯度找到变化最大的位置,该位置认为是边缘。
算法
在OpenCV 中集成了边缘算子,主要有canny、sobel、Laplacian、Prewitt、Roberts
数字图像处理常采用差分替代微分,构造的算子也是从微分转为差分进行计算的。用灰度图来说,图像的灰度变化呈现在人的眼睛中就是形状、区域。从数学观点来看,变化的极大值或极小值就是边缘,这意味着求边缘需要求导数。
对一副数字图像
f
(
x
,
y
)
f(x,y)
f(x,y),如果分别在
x
,
y
x,y
x,y方向求微分,则有
∂
f
∂
x
,
∂
f
∂
y
\frac{\partial {f}}{\partial x},\frac{\partial {f}}{\partial y}
∂x∂f,∂y∂f. 将上述微分用差分取代。
x
x
x方向
△
f
x
=
f
(
x
+
1
,
y
)
−
f
(
x
,
y
)
\triangle f_x=f(x+1,y)-f(x,y)
△fx=f(x+1,y)−f(x,y) 和
y
y
y方向
△
f
y
=
f
(
x
,
y
+
1
)
−
f
(
x
,
y
)
\triangle f_y=f(x,y+1)-f(x,y)
△fy=f(x,y+1)−f(x,y)分别用矩阵表示成:
x
方
向
算
子
=
[
0
0
0
0
−
1
1
0
0
0
]
,
y
方
向
算
子
=
[
0
1
0
0
−
1
0
0
0
0
]
x方向算子=\begin{bmatrix}0 &0 &0 \\0 & -1 &1 \\0 & 0 &0\\ \end{bmatrix},y方向算子= \begin{bmatrix}0 &1 &0 \\0 & -1 &0 \\0 & 0 &0\\ \end{bmatrix}
x方向算子=⎣⎡0000−10010⎦⎤,y方向算子=⎣⎡0001−10000⎦⎤
在上述基础上,一些研究者改进了这种求导方法,我们看看sobel算子构造:
G
x
=
[
−
1
0
1
−
2
0
2
−
1
0
1
]
,
G
y
=
[
−
1
−
2
−
1
0
0
0
1
2
1
]
G_x=\begin{bmatrix}-1 &0&1 \\-2 & 0 &2 \\-1 & 0 &1\\ \end{bmatrix},Gy=\begin{bmatrix}-1 &-2 &-1 \\0 &0 &0 \\1 & 2 &1\\ \end{bmatrix}
Gx=⎣⎡−1−2−1000121⎦⎤,Gy=⎣⎡−101−202−101⎦⎤
![](https://img-blog.csdnimg.cn/27ebed4ef7b649b4939fe812e53f3a21.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ0NDYwNDI=,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/aa7663540cba42cdada906e1c08c74fe.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTQ0NDYwNDI=,size_16,color_FFFFFF,t_70)
上述是一阶微分做的边缘提取,于是又发展出二阶微分算子,这就是Laplacian算子
△
f
=
∂
2
f
∂
x
2
+
∂
2
f
∂
y
2
\triangle f=\frac{\partial ^2{f}}{\partial x^2}+\frac{\partial ^2{f}}{\partial y^2}
△f=∂x2∂2f+∂y2∂2f。
对于二维图像:
△
f
=
f
(
x
+
1
,
y
)
+
f
(
x
−
1
,
y
)
+
f
(
x
,
y
+
1
)
+
f
(
x
,
y
−
1
)
−
4
f
(
x
,
y
)
\triangle f=f(x+1,y)+f(x-1,y)+f(x,y+1)+f(x,y-1)-4f(x,y)
△f=f(x+1,y)+f(x−1,y)+f(x,y+1)+f(x,y−1)−4f(x,y)
表示成矩阵形式:
L
=
[
0
1
0
1
−
4
1
0
1
0
]
L=\begin{bmatrix}0 &1 &0 \\1 & -4 &1 \\0 & 1 &0\\ \end{bmatrix}
L=⎣⎡0101−41010⎦⎤
此算子对奇异点或边界点更为敏感,常用于图像锐化处理。
有了上述矩阵模板,用该模板在图像上遍历计算它们的阿达玛积作为中心点的灰度值,opencv已经将这些封装成函数,直接调用即可。
用法
用前面介绍的知识,实战一下增强认识
1.sobel算子效果
//使用sobel算子
#include<opencv.h>
using namespace cv;
void main()
{
Mat src = imread("image.jpg", 0);
Mat imageSobel;
Sobel(src, imageSobel, CV_8UC1, 1,1);
imshow("src", src);
imshow("edge", imageSobel);
waitKey(3);
}
原图 sobel算子处理后
2.Canny算子
#include<opencv.h>
using namespace cv;
void main()
{
Mat src = imread("6.jpg", 0);
Mat imageCanny;
Canny(src, imageCanny, 190, 230, 3);
imshow("src", src);
imshow("edge", imageCanny);
waitKey(3);
}
原图 Canny算子处理后
3.二阶微分算子laplace效果
#include<opencv.h>
using namespace cv;
void main()
{
Mat src = cv::imread("1.jpg", 0);
Mat edge_img;
Laplacian(src, edge_img, CV_8U, 3);
imshow("src", src);
imshow("edge", edge_img);
waitKey(3);
}
原图 Laplace处理效果