C++ 使用 OpenCV 计算黑色像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19167348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count the black pixels using OpenCV
提问by Jakob
I'm working in opencv 2.4.0
and C++
我在工作opencv 2.4.0
和C++
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.
我正在尝试做一个练习,说我应该加载一个 RGB 图像,将其转换为灰度并保存新图像。下一步是将灰度图像制成二值图像并存储该图像。我有这么多工作。
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()
. When I pass the the image I want counted from to this function I get an error.
但我不知道如何存储这些值并在cvCountNonZero()
. 当我将想要计算的图像传递给此函数时,出现错误。
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 :)
到目前为止,这段代码是非常基本的,但它现在做了它应该做的事情。稍后将进行一些调整以清理它:)
回答by Ove
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).
您可以使用countNonZero
来计算图像中非黑色 (>0) 的像素数。如果要统计黑色(==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;