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

和自甴很熟 提交于 2021-02-05 06:13:45

问题


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,:]


回答1:


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




回答2:


Keep variables for white_count and black_count and just iterate through the image matrix. Whenever you encounter 255 increase the white_count and whenever 0 increase the black_count. Try it yourself, if no success I'll post the code here :)

P.S keep the dimensionality of the image in mind




回答3:


white_pixels = np.logical_and(255==cropped_image[:,:,0],np.logical_and(255==cropped_image[:,:,1],255==cropped_image[:,:,2]))


num_white = np.sum(white_pixels)

and the same with 0 for the black ones




回答4:


You can use the getcolors() function from PIL image, this function return a list of tuples with colors found in image and the amount of each one. I'm using the following function to return a dictionary with color as key, and counter as value.

from PIL import Image

def getcolordict(im):
    w,h = im.size
    colors = im.getcolors(w*h)
    colordict = { x[1]:x[0] for x in colors }
    return colordict

im = Image.open('image.jpg')
colordict = getcolordict(im)

# get the amount of black pixels in image
# in RGB black is 0,0,0
blackpx = colordict.get((0,0,0))

# get the amount of white pixels in image
# in RGB white is 255,255,255
whitepx = colordict.get((255,255,255))  

# percentage
w,h = im.size
totalpx = w*h
whitepercent=(whitepx/totalpx)*100
blackpercent=(blackpx/totalpx)*100


来源:https://stackoverflow.com/questions/58803312/how-to-count-number-of-white-and-black-pixels-in-color-picture-in-python-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!