Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of white and black pixels in color picture in python? How to count total pixels using numpy

I want to calculate persentage of black pixels and white pixels for the picture, its colorful one

import numpy as np
import matplotlib.pyplot as plt

image = cv2.imread("image.png")

cropped_image = image[183:779,0:1907,:]

like image 663
neji123 Avatar asked Nov 11 '19 14:11

neji123


People also ask

How do you count the number of pixels in an image in Python?

Use PIL to load the image. The total number of pixels will be its width multiplied by its height.

How do I find out how many pixels a picture is black?

For black images you get the total number of pixels (rows*cols) and then subtract it from the result you get from cv2. countNonZero(mat) . For other values, you can create a mask using cv2. inRange() to return a binary mask showing all the locations of the color/label/value you want and then use cv2.

How do I know how many pixels a picture is?

The width and height of the image in pixels. To find the total number of pixels, multiply the width and height together. In this case, 4700 pixels x 3133 pixels = 14,725,100 pixels. That's a lot of pixels.

Is 255 white or black?

The most common pixel format is the byte image, where this number is stored as an 8-bit integer giving a range of possible values from 0 to 255. Typically zero is taken to be black, and 255 is taken to be white. Values in between make up the different shades of gray.


1 Answers

You don't want to run for loops over images - it is dog slow - no disrespect to dogs. Use Numpy.

#!/usr/bin/env python3

import numpy as np
import random

# Generate a random image 640x150 with many colours but no black or white
im = np.random.randint(1,255,(150,640,3), dtype=np.uint8)

# Draw a white rectangle 100x100
im[10:110,10:110] = [255,255,255]

# Draw a black rectangle 10x10
im[120:130,200:210] = [0,0,0]

# Count white pixels
sought = [255,255,255]
white  = np.count_nonzero(np.all(im==sought,axis=2))
print(f"white: {white}")

# Count black pixels
sought = [0,0,0]
black  = np.count_nonzero(np.all(im==sought,axis=2))
print(f"black: {black}")

enter image description here

Output

white: 10000
black: 100

If you mean you want the tally of pixels that are either black or white, you can either add the two numbers above together, or test for both in one go like this:

blackorwhite = np.count_nonzero(np.all(im==[255,255,255],axis=2) | np.all(im==[0,0,0],axis=2)) 

If you want the percentage, bear mind that the total number of pixels is easily calculated with:

total = im.shape[0] * im.shape[1]

As regards testing, it is the same as any software development - get used to generating test data and using it :-)

like image 189
Mark Setchell Avatar answered Oct 16 '22 15:10

Mark Setchell