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