繁体   English   中英

如何计算python中彩色图片的黑白像素数? 如何使用 numpy 计算总像素

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

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

import numpy as np
import matplotlib.pyplot as plt

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

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

您不想在图像上运行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}")

在此处输入图像描述

Output

white: 10000
black: 100

如果您的意思是想要黑色或白色像素的计数,您可以将上面的两个数字相加,或者在一个 go 中测试两者,如下所示:

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]

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

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

PS记住图像的维度

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM