街道距离: d=|x1-x2|+|y1-y2| 棋盘距离: d=max(|x1-x2|,|y1-y2|),两个像素点X方向,y方向距离的最大值
代码:
void visionagin::Mydistancetransform()
{
Mat data = (Mat_<uchar>(5, 5) << 1, 1, 1, 1, 1,
1, 1, 1, 1, 1,
1, 1, 0, 1, 1,
1, 1, 1, 1, 1,
1, 1, 1, 1, 1);
Mat dststreet, dstouji, dstchess;
distanceTransform(data, dststreet, 1, 3, CV_8U);//计算街道距离
distanceTransform(data, dstouji, 2, 5, CV_8U);//计算欧几里得距离
distanceTransform(data, dstchess, 3, 3, CV_8U);//计算棋盘距离
cout << dststreet << endl;
cout << dstouji << endl;
cout << dstchess << endl;
Mat src=imread("C:\\Users\\86176\\Downloads\\visionimage\\rice.jfif");
if (src.empty())
{
cout << "open failed !" << endl;
}
imshow("原图", src);
Mat temp1,temp2, gry;
cvtColor(src, gry, COLOR_BGR2GRAY);
threshold(gry, temp1, 50, 255, THRESH_BINARY);//黑底白图
threshold(gry, temp2, 50, 255,THRESH_BINARY_INV);//白底黑图
imshow("黑底白图", temp1);
imshow("白底黑图", temp2);
Mat res1, res2;
distanceTransform(temp1, res1, 1, 3,CV_32F);//cv_32F显示更清晰
distanceTransform(temp2, res2, 1, 5,CV_8U);
imshow("黑底白图res1", res1);
imshow("白底黑图res2", res2);
}
结果:
原图及二值化后的图像:
距离变换后的结果: