使用c++,将一个二值图像进行距离变化,设定变化距离为20
时间: 2024-02-20 10:59:19 浏览: 21
下面是使用 C++ 和 OpenCV 库中的 distanceTransform 函数对二值图像进行距离变换的示例代码,变化距离为20:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取二值图像
Mat src = imread("input.png", IMREAD_GRAYSCALE);
// 二值化
Mat bin;
threshold(src, bin, 0, 255, THRESH_BINARY);
// 计算距离变换
Mat dist;
distanceTransform(bin, dist, DIST_L2, 5);
// 将距离变换结果进行归一化
normalize(dist, dist, 0, 1.0, NORM_MINMAX);
// 将距离变换结果乘以设定的变换距离
dist *= 20;
// 将距离变换结果转化为灰度图像
dist.convertTo(dist, CV_8UC1, 255);
// 显示距离变化结果
imshow("Distance Transform", dist);
waitKey(0);
destroyAllWindows();
return 0;
}
```
在这段代码中,我们首先读入一个二值图像,然后使用 threshold 函数将其转化为黑白图像。接着,我们调用 distanceTransform 函数,计算黑白图像中每个像素到最近白色像素的距离,这个距离被保存在 dist 中。我们将距离变换结果归一化到 0 到 1 的范围内,然后将其乘以设定的变换距离 20。最后,我们将 dist 转化为灰度图像,并将其显示出来。