Java opencv使用connectedComponents函数如何给标记labelImage区域上色?
public class demo07_5 {
static {
//在使用OpenCV前必须加载Core.NATIVE_LIBRARY_NAME类,否则会报错
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
Mat src = Imgcodecs.imread("D:\\Eclipse\\workPlace\\test\\img\\text.png", CvType.CV_8UC1);
Mat binary = src.clone();
Mat dst = new Mat(src.size(),CvType.CV_8UC3);//与src等大小的3通道画板dst
Imgproc.threshold(src, binary, 128, 255, Imgproc.THRESH_OTSU);// 进行二值化
int connectivity = 4;// 使用四连通邻域
// int connectedComponents(InputArray image, OutputArray labels,int connectivity = 8, int ltype = CV_32S);
// image是threshold得到的二值图,得到的labels是32位 short int(短整型)元素的矩阵
// 假如image中有2个连通域,那么labels是只有0、1、2这三种数的矩阵(0标识背景,1、2标识2个连通域),返回值是3(三种数据)
// Imgproc.connectedComponents(src, binary, connectivity);
Mat labelImage = new Mat();
int nLabels = Imgproc.connectedComponents(binary, labelImage, connectivity);// 0,255的binary图变成0,1,2。。。不同区域标识的labelImage,采用四连通邻域
// labelImage是一个单通道的图像,值咋都是0 1 呢,如何获取标记的label呢?
// System.out.println(nLabels);
Vector<Color> colors = new Vector<Color>(nLabels);
colors.add(0, Color.black);//将标号为0的点置为背景色黑色
for(int label = 1 ; label < nLabels ; label++) {
colors.add(label, new Color((int)(Math.random() * 0x1000000)));//为每一个标记赋值一个颜色
}
int label ;
for(int r = 0;r < dst.rows();r++) {
for(int c = 0;c < dst.cols(); c++) {// 遍历每一个像素
//这里就不明白了,如何能获得不同的标记label并且上色呢?
label = labelImage.get(r,c)[0];
System.out.println(label);
double[] label = labelImage.get(r, c);
System.out.println(label[1]);
dst.put(r, c, colors.get(label).getRGB());// 根据不同的标识进行染色
}
}
HighGui.imshow("ConnectedComponents", dst);
HighGui.waitKey();
}
}