两个点:找到组件+标记它
找到它:int nComponents = connectedComponents(imThresh, imLabels);
标记转换:imLabels.convertTo(imLabels, CV_8U);
Mat imColorMap;
applyColorMap(imLabels, imColorMap, COLORMAP_JET);
上代码
// Read image as grayscale
Mat img = imread("D:/OpenCVPrj/WangYi/MOpenCV_class4/images/truth.png", IMREAD_GRAYSCALE);
//1.Threshold Image 阈值化
Mat imThresh;
threshold(img, imThresh, 127, 255, THRESH_BINARY);
imshow("image", imThresh);
//2.找到连通的组件 标记它
Mat imLabels;
//显示连通组件的个数
int nComponents = connectedComponents(imThresh, imLabels);
Mat imLabelsCopy = imLabels.clone();
Point minLoc, maxLoc;
double min, max;
//3.得到原始标签
//4.转换标签为CV_8U
//5.可视化->变成彩色的
minMaxLoc(imLabels, &min, &max, &minLoc, &maxLoc);
// Normalize the image so the min value is 0 and max value is 255.
//标签转换 标签越大,灰度级别越高
imLabels = 255 * (imLabels - min) / (max - min);
//标签转换为 8位
imLabels.convertTo(imLabels, CV_8U);
imshow("image", imLabels);
imLabels = imLabelsCopy.clone();
for (int i = 0; i < 6; i++) {
imshow("image", imLabels == i);
waitKey(0);
}
// Make a copy of the image
imLabels = imLabelsCopy.clone();
// First let's find the min and max values in imLabels
// The following line finds the min and max pixel values
// and their locations in an image.
double minValue, maxValue;
minMaxLoc(imLabels, &minValue, &maxValue, &minLoc, &maxLoc);
// Normalize the image so the min value is 0 and max value is 255.
imLabels = 255 * (imLabels - minValue) / (maxValue - minValue);
// Convert image to 8-bits
imLabels.convertTo(imLabels, CV_8U);
// Apply a color map
Mat imColorMap;
applyColorMap(imLabels, imColorMap, COLORMAP_JET);
// Display colormapped labels
imshow("image", imColorMap);
waitKey(0);
destroyAllWindows();