【问题标题】:How to count the number of pixels of a certain color in python?如何计算python中某种颜色的像素数?
【发布时间】:2015-04-19 00:24:03
【问题描述】:

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

【问题讨论】:

  • ...到目前为止你做了什么?

标签: python jes


【解决方案1】:

首先你需要安装枕头库。

sudo pip3 安装枕头

from PIL import *
im = Image.open("your picture")

for pixel in im.getdata():
    if pixel is (0,0,0):
        black += 1
    else:
        red += 1
print("black = " + black + "red = " + red)

【讨论】:

  • 这有助于我找到我的解决方案。谢谢:-)
【解决方案2】:

我将代码从 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))

【讨论】:

  • 当我尝试计算此 RGB 比例 (0,226,129) 的绿色像素数时出现此错误:TypeError: can only concatenate tuple (not "int") to tuple
【解决方案3】:

根据http://personal.denison.edu/~bressoud/cs110-f12/Supplements/JESHelp/7_Picture_Functions.html 的说法,JES 提供了可以满足您所有需求的简单功能,例如

black = makeColor(0, 0, 0)
red = makeColor(255, 0, 0)
numblacks = numreds = 0
for pixel in getPixels(picture):
    color = getColor(pixel)
    if color == black: numblacks += 1
    elif color == red: numreds += 1

应该可以轻松完成您需要的所有工作(在需要任何导入以使功能可用之后——我没有 JES,我以前也从未见过或使用过它;我所拥有的只是我找到的那个文档网络搜索)。

但是,这似乎非常简单,我想肯定还有更多的问题——我无法想象有人会“坚持三天”(!)。但如果我怀疑还有更多,必须是告诉我们的人——这段代码到底有什么问题(加上任何导入、定义、返回或打印,或者其他什么,你的确切分配需要)似乎是在使用 JES 的功能来轻松解决问题?!除非您帮助我们,否则我们无法帮助您!

【讨论】:

  • JES 似乎是一个教育工具包,而不是开源的。有人知道如何安装 JES 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多