简体   繁体   English

使用OpenCV计算黑色像素

[英]Count the black pixels using OpenCV

I'm working in opencv 2.4.0 and C++ 我在opencv 2.4.0C++

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. 我正在尝试做一个练习,说我应该加载RGB图像,将其转换为灰度并保存新图像。 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);

But I don't know how to store these values and use them in cvCountNonZero() . 但我不知道如何存储这些值并在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 :) 稍后会进行一些调整以清理它:)

You can use countNonZero to count the number of pixels that are not black (>0) in an image. 您可以使用countNonZero计算图像countNonZero黑色(> 0)的像素数。 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). 如果要计算黑色(== 0)像素的数量,则需要从图像中的像素数(图像宽度*高度)中减去非黑色像素的数量。

This code should work: 这段代码应该有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM