void CrelaxMyFriendDlg::OnBnClickedOk()
{
hdc = this->GetDC()->GetSafeHdc();
// TODO: 在此添加控件通知处理程序代码
string imAddr = "c:/Users/actorsun/Pictures/";
string imAddr1 = imAddr+"rice.png";
Mat relax1, positive;
relax1 = imread(imAddr1);
Mat relax;
cvtColor(relax1, relax, COLOR_BGR2GRAY);
threshold(relax, positive, 50, 255, THRESH_BINARY);
imshow(positive);
RNG rng(101);
Mat a, b;
int cout = connectedComponentsWithStats(positive, positive,a,b,8,CV_16U);
imshow("1", positive);
waitKey();
vector<Vec3b> colors;
for (int i = 0; i < cout; i++)
{
Vec3b vec(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
colors.push_back(vec);
}
Mat result(positive.rows,positive.cols,relax1.type());
for (int row = 0; row < relax1.rows; row++)
{
for (int col = 0; col < relax1.cols; col++)
{
int temp = positive.at<uint16_t>(row,col);
if (temp == 0)
continue;
result.at<Vec3b>(row, col) = colors[temp];
}
}
imshow("标记后的图", result);
waitKey();
return;
}
上面这个代码是MFC程序里面的一个函数,不能够直接运行,但是如果学过MFC相信没有问题完全能够看得懂。
上例当中,count=7.说明检测到7个连通域。