代码:
void visionagin::Mydistancetransform()
{
Mat data = (Mat_(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);
}
原图及二值化后的图像:
图像连通域分析:
代码:
void visionagin::Myconnectedcompents()
{
Mat src= imread("C:\\Users\\86176\\Downloads\\visionimage\\rice.jfif");
imshow("原图", src);
Mat gry, res_thre, res_conect;
cvtColor(src, gry, COLOR_BGR2GRAY);
threshold(gry, res_thre, 50, 255, THRESH_BINARY);
int nums=connectedComponents(res_thre, res_conect, 8, CV_16U);
cout << "total is " << nums << endl;
RNG rng(12345);
vectorcolor;
for (int i = 0; i < nums; ++i)
{
Vec3b color_value = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));//为每个连通域生成随机颜色
color.push_back(color_value);
}
Mat temp = Mat::zeros(src.size(),src.type());//与原图像大小,类型一致的画布
int width = temp.cols;
int height = temp.rows;
for (int j = 0; j < height; j++)
{
for (int k = 0; k < width; ++k)
{
int label = res_conect.at(j, k);//每个连通域的label
if (label == 0)//黑色
{
continue;
}
else
{
temp.at(j, k) = color[label];//除了黑色背景,都改成随机颜色
}
}
}
imshow("res_con_picture", temp);
代码:
void visionagin::Myconnectedcompents2()
{
Mat src = imread("C:\\Users\\86176\\Downloads\\visionimage\\rice.jfif");
imshow("原图", src);
Mat gry, res_thre, res_conect, stats, center;
cvtColor(src, gry, COLOR_BGR2GRAY);
threshold(gry, res_thre, 50, 255, THRESH_BINARY);
int nums = connectedComponentsWithStats(res_thre, res_conect, stats, center, 8, CV_16U);
cout << "total is " << nums << endl;
RNG rng(12345);
vectorcolor;
for (int i = 0; i < nums; ++i)
{
Vec3b color_value = Vec3b(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));//为每个连通域生成随机颜色
color.push_back(color_value);
}
Mat temp = Mat::zeros(src.size(), src.type());//与原图像大小,类型一致的画布
int width = temp.cols;
int height = temp.rows;
for (int i = 0; i < nums; ++i)
{
Point Center(center.at(i, 0), center.at(i, 1));
circle(src, Center, 2, Scalar(color[i]), 1);//画质心
int px(stats.at(i, 0));
int py(stats.at(i, 1));
int w = stats.at(i, 2);
int h = stats.at(i, 3);
rectangle(src, Rect(px, py, w, h), Scalar(color[i]), 2);
}
imshow("res_con_picture", src);
}