距离变换
Opencv中distanceTransform方法用于计算图像中每一个非零点距离自己最近的零点的距离,方法输出的信息为距离而不是颜色值,图像上越亮的点,代表了离零点的距离越远。
可以用来细化轮廓,或者寻找物体的质心!
方法参数说明:
| void cv::distanceTransform(InputArray src, 输入图像
OutputArray dst, 输出图像
int distanceType, 计算距离的方法
int maskSize, 掩膜的大小,一般为3x3 或者 5x5
int dstType = CV_32F 选用默认值即可
)
|
distanceType类型介绍
DIST_USER |
User defined distance. |
DIST_L1 |
distance = |x1-x2| + |y1-y2| |
DIST_L2 |
the simple euclidean distance |
DIST_C |
distance = max(|x1-x2|,|y1-y2|) |
DIST_L12 |
L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) |
DIST_FAIR |
distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 |
DIST_WELSCH |
distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 |
DIST_HUBER |
distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 |
示例代码
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 | /**
距离变换
*/
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc,char** argv){
string path = "/home/kaijun/Documents/resource/opencv/img/shape.jpg";
// 读取原图
Mat src = imread(path,IMREAD_GRAYSCALE);
imshow("src",src);
// 将图片转成二值图像
Mat binary;
threshold(src,binary,0,255,THRESH_BINARY_INV|THRESH_OTSU);
imshow("binary",binary);
cout<<binary.type()<<binary.channels()<<endl;
// 距离变换
Mat distanceImg;
distanceTransform(binary,distanceImg,DIST_L2,3);
// 将数据归一化到0~1之间
normalize(distanceImg,distanceImg,0,1.0,NORM_MINMAX);
imshow("distance",distanceImg);
waitKey(0);
return 0;
}
|