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,:]
Use PIL to load the image. The total number of pixels will be its width multiplied by its height.
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.
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.
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.
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}")
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With