我想实现基于颜色强度分割图像的K-means聚类,实际上我不知道在应用Core.kmeans函数后如何获得分割图像和ROI。我按照here中的问题中的步骤进行了操作,但是没有回答如何从这一点开始。任何帮助将不胜感激。
提前致谢。
我使用的代码基于不同的来源,实际上它不起作用
//convert to lab with three channels
Mat imgLab = new Mat();
Mat imgMat = new Mat();
Imgproc.cvtColor(imgMat, imgLab, Imgproc.COLOR_RGB2Lab, 3);
// separate channels
List<Mat> lab_planes = new ArrayList<Mat>(3);
Core.split(imgMat, lab_planes);
Mat channel = lab_planes.get(2);
channel = Mat.zeros(imgLab.rows(), imgLab.cols(), CvType.CV_8UC1);
// use only AB channels in Lab color space
lab_planes.set(2, channel);
Core.merge(lab_planes,imgLab);
Mat samples = imgLab.reshape(1, imgLab.cols() * imgLab.rows());
Mat samples32f = new Mat();
samples.convertTo(samples32f, CvType.CV_32F, 1.0 / 255.0);
Mat labels = new Mat();
TermCriteria criteria = new TermCriteria(TermCriteria.EPS + TermCriteria.MAX_ITER, 100, 1);
Mat centers = new Mat();
//Mat clusteredLab = new Mat();
int nColors = 3; //number of clusters (k)
int attempt = 3; //number of attempts
// repeat the clustering 3 times to avoid local minima
Core.kmeans(samples32f, nColors, labels, criteria, attempt, Core.KMEANS_PP_CENTERS, centers);
centers.convertTo(centers, CvType.CV_8UC1);
centers.reshape(3);
//the rest of code for RGB image not Lab
List<Mat> clusters = new ArrayList<Mat>();
for (int i = 0; i < centers.rows(); i++) {
clusters.add(Mat.zeros(samples.size(), samples.type()));
}
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (int i = 0; i < centers.rows(); i++) counts.put(i, 0);
int rows = 0;
for (int y = 0; y < samples.rows(); y++) {
for (int x = 0; x < samples.cols(); x++) {
int label = (int) labels.get(rows, 0)[0];
int r = (int) centers.get(label, 2)[0];
int g = (int) centers.get(label, 1)[0];
int b = (int) centers.get(label, 0)[0];
counts.put(label, counts.get(label) + 1);
clusters.get(label).put(y, x, b, g, r);
rows++;
}
}
return clusters;
}