c++ - OpenCV:读取矩阵值

标签 c++ opencv matrix background-image pixel

我想计算只有黑白的背景图像中的白点数。我有这样的代码:

int count = 0; 
for ( int j = 0; j < Image.rows; j ++ )
    {
    for ( int i = 0; i < Image.cols; i ++ )
        {
            if ( Image.at<int>(i,j) >= 150 )
            {
                count ++ ;
            }
        }
    }

由于某种原因,上面的代码不起作用,它只是停止了 react 。我检查了一下,“if ( Image.at(i,j) >= 150 ) ” 行导致了问题。我的“图像”是“cv::Mat”,类型为“CV_8UC3”。有人可以帮助我吗?谢谢你。

最佳答案

除了我对 Robin 的回答的评论之外,您的错误是您尝试将 CV_8UC3 类型的图像作为整数访问。如果您想检查灰度级,请执行以下操作(请注意“unsigned char”而不是“int”,如 Robin 的回答)。

cv::Mat greyscale;
cv::cvtColor(image,grayscale,CV_RGB2GRAY);
// either, most elegant:
int count = cv::countNonZero(greyscale >= 150);
// or, copied from Robin's answer:
int count = 0;
for(int i = 0; i < greyscale.rows; ++i) {
    const unsigned char* row = greyscale.ptr<unsigned char>(i);
    for(int j = 0; j < greyscale.cols; j++) {
        if (row[j] >= 150)
            ++count;
    }
}

关于c++ - OpenCV:读取矩阵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12070139/

相关文章:

c++ - 从 std::function 调用签名推断模板参数

c++ - 找到一组点的中心以顺时针排序?

C++——DirectWrite : Load font from file at runtime

python - 将大型 csv 转换为稀疏矩阵以在 sklearn 中使用

loops - 使用 Stata 中变量的唯一观测值创建向量

c++ - 链接 cmake、icc 和 pthreads (linux)

c++ - 同时多次运行一个进程

python:使用引用图像和来自相机的当前图像查找相机偏移角度

android - 使用 HOGDescriptor(适用于 Android 的 OpenCV)对图像进行梯度和角度可视化

algorithm - 人工神经网络的雅可比矩阵计算