如何计算python中某种颜色的像素数?

mil*_*eep 7 python jes

我有两种颜色的图片,黑色和红色,我需要能够计算图片中有多少像素是红色,有多少是黑色.

Mat*_*ijs 8

我将代码从0xd3更正为实际工作:

from PIL import Image
im = Image.open('black.jpg')

black = 0
red = 0

for pixel in im.getdata():
    if pixel == (0, 0, 0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        black += 1
    else:
        red += 1
print('black=' + str(black)+', red='+str(red))
Run Code Online (Sandbox Code Playgroud)


小智 3

首先你需要安装枕头库。

\n\n
\n

sudo pip3 安装枕头

\n
\n\n
from PIL import *\nim = Image.open("your picture")\n\nfor pixel in im.getdata():\n    if pixel is \xef\xbc\x880,0,0\xef\xbc\x89\xef\xbc\x9a\n        black += 1\n    else\xef\xbc\x9a\n        red += 1\nprint("black = " + black + "red = " + red)\n
Run Code Online (Sandbox Code Playgroud)\n