OpenCV:计算超像素质心

时间:2015-09-30 01:15:45

标签: c++ opencv centroid superpixels

背景

我使用gSLICr计算了图像的SLIC超像素,它提供了每像素映射"图像超像素作为索引(0到超像素-1的数量)。

此映射是指向包含索引的整数const数组(regionprops)的指针。

我现在想用OpenCV来计算每个超像素的质心。

来自Matlab背景,我会使用segments = vl_slic(myImage, regionSize, regularizer); stats = regionprops(segments, 'Centroid'); centroids = cat(1, stats.Centroid);

来做到这一点
const int*

我不知道如何使用OpenCV完成此操作。

问题:

(i)如何将cv::Mat数组转换为var guesses = 5; function guess() { var elGuess = document.getElementById("remaining"); var elResult = document.getElementById("result"); if (guesses===0){ return; } guesses--; elGuess.textContent = guesses; if(guesses > 0) { var secret = Math.floor(Math.random() * 10 + 1); var elUserGuess = document.getElementById("number"); var userGuess = parseInt(elUserGuess.value); if(userGuess == secret) { elResult.textContent = "Congrats! You did it"; } else { elResult.textContent = "Sorry, please try again."; } } else { elResult.textContent = "Sorry, you ran out of guesses."; } } var elSubmit = document.getElementById("submit"); elSubmit.addEventListener("click", guess, false);

(ii)如何从(i)中的矩阵计算超像素质心?

1 个答案:

答案 0 :(得分:0)

由于第一个问题似乎得到了解答,我将重点关注第二个问题。我使用以下代码计算每个超像素的平均坐标(即空间质心):

/** \brief Compute the mean coordinates of each superpixel (i.e. spatial centroids).
 * \param[in] labels a matrix of type CV_32SC1 holding the labels for each pixel
 * \param[out] means the spatial centroids (or means in y and x axes) of the superpixels
 */
void getMeans(const cv::Mat &labels, std::vector<cv::Vec2f> &means) {

    // Count superpixels or get highest superpixel index:
    int superpixels = 0;
    for (int i = 0; i < labels.rows; ++i) {
        for (int j = 0; j < labels.cols; ++j) {
            if (labels.at<int>(i, j) > superpixels) {
                superpixels = labels.at<int>(i, j);
            }
        }
    }

    superpixels++;

    // Setup means as zero vectors.
    means.clear();
    means.resize(superpixels);
    for (int k = 0; k < superpixels; k++)
    {
        means[k] = cv::Vec2f(0, 0);
    }

    std::vector<int> counts(superpixels, 0);

    // Sum y and x coordinates for each superpixel:
    for (int i = 0; i < labels.rows; ++i) {
        for (int j = 0; j < labels.cols; ++j) {
            means[labels.at<int>(i, j)][0] += i; // for computing mean i (i.e. row or y axis)
            means[labels.at<int>(i, j)][1] += j; // for computing the mean j (i.e. column or x axis)

            counts[labels.at<int>(i, j)]++;
        }
    }

    // Obtain averages by dividing by the size (=number of pixels) of the superpixels.
    for (int k = 0; k < superpixels; ++k) {
        means[k] /= counts[k];
    }
}

// Do something with the means ...

如果您还需要平均颜色,该方法将需要图像作为参数,但其余代码可以很容易地适应计算平均颜色。