c++ - 如何保存到白色像素的 vector 坐标?

标签 c++ opencv

我想遍历一个二值化的 cv::Mat 并保存所有值为 255 的像素坐标。

cv::Mat bin;                                                    
std::vector<cv::Point2i> binVec;
int h = 0;
int white = 254;    //Just for comparison with pointer of Matrix value
for (int i = 0; i < bin.rows; i++, h++) {
    for (int j = 0; j < bin.cols; j++, h++) {
        int* p = bin.ptr<int>(h);   //Pointer to bin Data, should loop through Matrix
        if (p >= &white)            //If a white pixel has been found, push i and j in binVec
            binVec.push_back(cv::Point2i(i, j));
    }
}

此代码段无效,我不知道为什么。

Exception thrown at 0x76C6C42D in example.exe: Microsoft C++ exception: cv::Exception at memory location 0x0019E4F4.

Unhandled exception at 0x76C6C42D in example.exe: Microsoft C++ exception: cv::Exception at memory location 0x0019E4F4.

那么如何计算h并让指针起作用呢?

最佳答案

您可以避免扫描图像。要将所有白色像素的坐标保存在 vector 中,您可以这样做:

Mat bin;
// fill bin with some value

std::vector<Point> binVec;
findNonZero(bin == 255, binVec);

您可以使用 Point而不是 Point2i ,因为它们是相同的:

typedef Point2i Point;

如果你真的想使用 for 循环,你应该这样做:

const uchar white = 255;
for (int r = 0; r < bin.rows; ++r) 
{
    uchar* ptr = bin.ptr<uchar>(r);
    for(int c = 0; c < bin.cols; ++c) 
    {
        if (ptr[c] == 255) {
            binVec.push_back(Point(c,r));
        }
    }
}

请记住:

  • 你的二进制图像可能是CV_8UC1 , 而不是 CV_32SC1 , 所以你应该使用 uchar而不是 int .
  • bin.ptr<...>(i)为您提供指向第 i 行开头的指针,因此您应该将其从内部循环中取出。
  • 您应该比较,而不是地址
  • Pointx为参数(cols) 和 y (),当你经过 i 时()和j ()。所以你需要交换它们。
  • 这个循环可以进一步优化,但对于你的任务,我强烈推荐 findNonZero方法,所以我不在这里显示。

关于c++ - 如何保存到白色像素的 vector 坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34721692/

相关文章:

c++ - 使用 Win32 监视打开的程序

c++ - 在 Windows 1809 中操作系统/可见剪切区域

c++ - 为 UWP 构建 OpenCV

c++ - CascadeClassifier::detectMultiScale 不适用于 C++

c++ - llvm 在 C++ 中提取结构元素和结构大小

c++ - 1 [main] 972 exception::handle: Exception: STATUS_ACCESS_VIOLATION 说明及修复方法

c++ - 制作免费的静态函数有什么好处吗?

c++ - openCV cvSaveImage() 增加图像的大小

python - 使用OpenCV和flask进行图像流传输-为什么需要imencode?

Python OpenCV 如何在转换后保存图像