0

背景:

我已经使用gSLICr计算了图像的 SLIC 超像素,它给出了图像超像素的“每像素图”作为索引(0 到超像素的数量-1)。

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

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

来自 Matlab 背景,我会使用以下方法来做到这一点regionprops

segments = vl_slic(myImage, regionSize, regularizer);
stats = regionprops(segments, 'Centroid');
centroids = cat(1, stats.Centroid);

我不知道这是如何使用 OpenCV 完成的。

问题:

(i) 如何将const int*数组转换为cv::Mat

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

4

1 回答 1

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 ...

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

于 2016-09-02T14:20:28.423 回答