OpenCV Android Kmeans 无法按预期工作

OpenCV4Android Kmean doesn't work as expected

此代码应提供 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 行和 clusterCount 列数的中心 Mat。

但在 java 中 Core.kmeans 返回 4 列和簇行数。

centers.reshape(3);

所以现在重塑函数不适用于中心,因为行数取决于簇大小。在 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);

终于成功了:-

我使用 bitmapToMat 函数将位图转换为 Mat,returns RGBA 图像。所以中心有 4 列而不是 3 列。

如果您要将位图转换为 Mat,并且需要 BGR 图像,请执行此操作

    Mat imageMat = new Mat();
    Utils.bitmapToMat(bitmap, imageMat);

    Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_BGRA2BGR);

干杯