c++ - 获取 OpenCV Mat 中唯一像素值的列表

标签 c++ arrays opencv matrix computer-vision

对于 OpenCV Mat,是否有等效于 np.unique()bincount() 的方法?我正在使用 C++,所以不能只转换为 numpy 数组。

最佳答案

不,没有!不过您可以编写自己的代码:

std::vector<float> unique(const cv::Mat& input, bool sort = false)

Find the unique elements of a single channel cv::Mat.

Parameters:

input: It will be treated as if it was 1-D.

sort: Sorts the unique values (optional).

此类功能的实现非常简单,但是,以下仅适用于单 channel CV_32F:

#include <algorithm>
#include <vector>

std::vector<float> unique(const cv::Mat& input, bool sort = false)
{
    if (input.channels() > 1 || input.type() != CV_32F) 
    {
        std::cerr << "unique !!! Only works with CV_32F 1-channel Mat" << std::endl;
        return std::vector<float>();
    }

    std::vector<float> out;
    for (int y = 0; y < input.rows; ++y)
    {
        const float* row_ptr = input.ptr<float>(y);
        for (int x = 0; x < input.cols; ++x)
        {
            float value = row_ptr[x];

            if ( std::find(out.begin(), out.end(), value) == out.end() )
                out.push_back(value);
        }
    }

    if (sort)
        std::sort(out.begin(), out.end());

    return out;
}

示例:

float data[][3] = {
  {  9.0,   3.0,  7.0 },
  {  3.0,   9.0,  3.0 },
  {  1.0,   3.0,  5.0 },
  { 90.0, 30.0,  70.0 },
  { 30.0, 90.0,  50.0 }
};

cv::Mat mat(3, 5, CV_32F, &data);

std::vector<float> unik = unique(mat, true);

for (unsigned int i = 0; i < unik.size(); i++)
    std::cout << unik[i] << " ";
std::cout << std::endl;

输出:

1 3 5 7 9 30 50 70 90 

关于c++ - 获取 OpenCV Mat 中唯一像素值的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24716932/

相关文章:

c++ - 如何使用 C++ 在 gtkmm:gtk::Listbox 中添加文本框

c++ - Visual Studio 2017 : ambiguous symbol size_t in linux projects

python - 'shuffled' NumPy 数组上的维度不匹配

c++ - 如何启用 OpenMP w/OpenCV 应用程序?

c - 使用 OpenCv 应用灰度

python-3.x - 使用opencv LineSegmentDetector查找图像的线条

c++ - 如何在wxWidgets中使用wxString、数字和其他字符串类型

c++ - 调试断言失败!表达式 : is_block_type_valid(header->_block_use). 对象不会初始化和推送错误

c++ - C++中的分页效果是什么?

arrays - 如何简单地折叠(求和)R 中数组中的某些行