此代码应提供 3 行的中心垫和 clusterCount 列数
Mat reshaped_image = imageMat.reshape(1, imageMat.cols()*imageMat.rows());
Mat reshaped_image32f = new Mat();
reshaped_image.convertTo(reshaped_image32f, CvType.CV_32F, 1.0 / 255.0);
Mat labels = new Mat();
TermCriteria criteria = new TermCriteria(TermCriteria.COUNT, 100, 1);
Mat centers = new Mat();
int clusterCount = 5, attempts = 1;
Core.kmeans(reshaped_image32f, clusterCount, labels, criteria, attempts, Core.KMEANS_PP_CENTERS, centers);
我在 C 中尝试了相同的代码,得到了 3 行的中心 Mat 和 clusterCount 列数。
但在 java 中,Core.kmeans 返回 4 列和簇行数。
centers.reshape(3);
所以现在 reshape 函数不适用于中心,因为行数取决于簇大小。在 C 中,行数总是恒定的,即 3。
所以在java中它给出了错误
the number of rows of the matrix cannot be divided by new number of rows
有人能找出问题所在吗?我什至试过this这与我的代码相似,但有同样的错误。
引用C代码:
cv::Mat reshaped_image = image.reshape(1, image.cols * image.rows);
cv::Mat reshaped_image32f;
reshaped_image.convertTo(reshaped_image32f, CV_32FC1, 1.0 / 255.0);
cv::Mat labels;
int cluster_number = 5;
cv::TermCriteria criteria(cv::TermCriteria::COUNT, 100, 1);
cv::Mat centers;
cv::kmeans(reshaped_image32f, cluster_number, labels, criteria, 1, cv::KMEANS_PP_CENTERS, centers);
最佳答案
终于成功了:-
我使用返回 RGBA 图像的 bitmapToMat 函数将位图转换为 Mat。所以中心有 4 列而不是 3 列。
如果您要将位图转换为 Mat,并且需要 BGR 图像,请执行此操作
Mat imageMat = new Mat();
Utils.bitmapToMat(bitmap, imageMat);
Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_BGRA2BGR);
干杯
关于android - OpenCV Android Kmeans 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29235599/