使用OpenCV计算黑色像素 [英] Count the black pixels using OpenCV

查看:1125
本文介绍了使用OpenCV计算黑色像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 opencv 2.4.0 C ++工作

我正在尝试做一个练习,说我应该加载RGB图像,将其转换为灰度并保存新图像。下一步是将灰度图像制作成二进制图像并存储该图像。我有这么多工作。

I'm trying to do an exercise that says I should load an RGB image, convert it to gray scale and save the new image. The next step is to make the grayscale image into a binary image and store that image. This much I have working.

我的问题在于计算二进制图像中黑色像素的数量。

My problem is in counting the amount of black pixels in the binary image.

到目前为止我已经在网上搜索并查看了这本书。我发现似乎最有用的方法是。

So far I've searched the web and looked in the book. The method that I've found that seems the most useful is.

int TotalNumberOfPixels = width * height;
int ZeroPixels = TotalNumberOfPixels - cvCountNonZero(cv_image);

但我不知道如何存储这些值并在中使用它们cvCountNonZero()。当我将想要的图像传递给此函数时,我收到错误。

But I don't know how to store these values and use them in cvCountNonZero(). When I pass the the image I want counted from to this function I get an error.

int main()
{
    Mat rgbImage, grayImage, resizedImage, bwImage, result;

    rgbImage = imread("C:/MeBGR.jpg");
    cvtColor(rgbImage, grayImage, CV_RGB2GRAY);

    resize(grayImage, resizedImage, Size(grayImage.cols/3,grayImage.rows/4),
           0, 0, INTER_LINEAR);

    imwrite("C:/Jakob/Gray_Image.jpg", resizedImage);
    bwImage = imread("C:/Jakob/Gray_Image.jpg");
    threshold(bwImage, bwImage, 120, 255, CV_THRESH_BINARY);
    imwrite("C:/Jakob/Binary_Image.jpg", bwImage);
    imshow("Original", rgbImage);
    imshow("Resized", resizedImage);
    imshow("Resized Binary", bwImage);

    waitKey(0);
    return 0;
}

到目前为止,这段代码非常基本但是它现在应该做到的。稍后会进行一些调整以清理它:)

So far this code is very basic but it does what it's supposed to for now. Some adjustments will be made later to clean it up :)

推荐答案

您可以使用 countNonZero 计算非黑色像素数(> 0)在图像中。如果要计算黑色(== 0)像素的数量,则需要从图像中的像素数(图像宽度*高度)中减去非黑色像素的数量。

You can use countNonZero to count the number of pixels that are not black (>0) in an image. If you want to count the number of black (==0) pixels, you need to subtract the number of pixels that are not black from the number of pixels in the image (the image width * height).

此代码应该有效:

int TotalNumberOfPixels = bwImage.rows * bwImage.cols;
int ZeroPixels = TotalNumberOfPixels - countNonZero(bwImage);
cout<<"The number of pixels that are zero is "<<ZeroPixels<<endl;

这篇关于使用OpenCV计算黑色像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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