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

后端 未结 4 1270
-上瘾入骨i
-上瘾入骨i 2021-01-21 07:59

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         


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 08:31

    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
    

提交回复
热议问题