【问题标题】:How to count number of white and black pixels in color picture in python? How to count total pixels using numpy如何计算python中彩色图片中白色和黑色像素的数量?如何使用numpy计算总像素
【发布时间】:2020-03-07 06:08:19
【问题描述】:

我想计算图片的黑色像素和白色像素的百分比,它是彩色的

import numpy as np
import matplotlib.pyplot as plt

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

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

【问题讨论】:

  • 您要单独统计还是合并统计?

标签: python numpy opencv image-processing


【解决方案1】:
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)

黑色的也是 0

【讨论】:

  • 感谢您的回答!如何确保其正常工作?如何调试?
【解决方案2】:

保留 white_count 和 black_count 的变量,然后遍历图像矩阵。每当遇到 255 时,增加 white_count,每当遇到 0 时,增加 black_count。自己试试,如果不成功我会在这里贴代码:)

P.S 请记住图像的维度

【讨论】:

    【解决方案3】:

    您不想在图像上运行 for 循环 - 这对狗来说很慢 - 不要不尊重狗。使用 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}")
    

    输出

    white: 10000
    black: 100
    

    如果您的意思是想要黑色或白色像素的计数,您可以将上面的两个数字相加,或者像这样一次性测试两个数字:

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

    如果您需要百分比,请记住像素总数很容易计算:

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

    关于测试,它与任何软件开发一样——习惯于生成测试数据并使用它:-)

    【讨论】:

      【解决方案4】:

      您可以使用 PIL 图像中的 getcolors() 函数,该函数返回一个元组列表,其中包含在图像中找到的颜色和每个颜色的数量。我正在使用以下函数返回一个字典,其中颜色为键,计数器为值。

      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
      

      【讨论】:

        猜你喜欢
        • 2015-02-13
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-27
        • 1970-01-01
        相关资源
        最近更新 更多