OpenCV:读取矩阵值 [英] OpenCV: read matrix value

查看:230
本文介绍了OpenCV:读取矩阵值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计算仅黑白图像的背景图像中白点的数量.我有这样的代码:

I want to count the number of white points in a background image which is only black and white. I have a code like this:

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 ++ ;
            }
        }
    }

由于某种原因,以上代码不起作用,只是停止了反应.我检查了一下,这行"if(Image.at(i,j)> = 150)"引起了问题.我的图片"是"cv :: Mat",类型为"CV_8UC3".有没有人可以帮助我?谢谢你.

For some reason, the above code doesn't work, it just stops reacting. I checked, and the line" if ( Image.at(i,j) >= 150 ) " causes the problem. My "Image" is a "cv::Mat", with "CV_8UC3" type. Is there someone can help me? Thank you.

推荐答案

除了我对Robin的回答的评论外,您的错误还在于您尝试以int形式访问CV_8UC3类型的图像.如果要检查灰度,请执行以下操作(注意,如Robin的回答所示,请注意"unsigned char"而不是"int").

In addition to my comment to Robin's answer, your error is that you try to access an image of CV_8UC3 type as ints. If you want to check grey levels, do something like this (note the "unsigned char" instead of "int", as in Robin's answer).

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;
    }
}

这篇关于OpenCV:读取矩阵值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆