Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the black pixels using OpenCV

Tags:

c++

image

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

like image 981
Jakob Avatar asked Oct 03 '13 19:10

Jakob


People also ask

How do you count white pixels in OpenCV?

Counting PixelsNumPy provides a function sum() that returns the sum of all array elements in the NumPy array. This sum() function can be used to count the number of pixels on the basis of the required criteria.

How do I get the pixel value of an image in OpenCV?

Figure 5: In OpenCV, pixels are accessed by their (x, y)-coordinates. The origin, (0, 0), is located at the top-left of the image. OpenCV images are zero-indexed, where the x-values go left-to-right (column number) and y-values go top-to-bottom (row number). Here, we have the letter “I” on a piece of graph paper.


1 Answers

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;
like image 100
Ove Avatar answered Oct 10 '22 12:10

Ove