如何计算python中彩色图片中白色和黑色像素的数量?如何使用numpy计算总像素 [英] How to count number of white and black pixels in color picture in python? How to count total pixels using numpy

查看:73
本文介绍了如何计算python中彩色图片中白色和黑色像素的数量?如何使用numpy计算总像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您不想在图像上运行 for 循环 - 它很慢 - 没有对狗的不尊重.使用 Numpy.

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}")

输出

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

这篇关于如何计算python中彩色图片中白色和黑色像素的数量?如何使用numpy计算总像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆