简体   繁体   中英

Count the black pixels using OpenCV

I'm working in opencv 2.4.0 and 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.

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.

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. 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).

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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