gpt4 book ai didi

python - 在 JES (Jython) 中计算颜色像素

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:49 24 4
gpt4 key购买 nike

我正在尝试提取预制图片中 R、G、B、黑色和白色值的总像素数。该图片有 100 个红色、100 个绿色、100 个蓝色、100 个黑色和 100 个白色。

我已经开始编写我的代码,但由于某种原因,我的代码似乎只计算 1 个像素。Jython 预定义了 16 种颜色,因此我使用红色、蓝色、绿色数据类型。

这是我到目前为止所拥有的:

def main():
file = pickAFile( )
pic = makePicture( file )

pxRed = 0
pxGreen = 0
pxBlue = 0
numR = 0
numG = 0
numB = 0

printNow("Now let's count some pixels...")

for px in getPixels( pic ):
r = getRed(px)
g = getGreen(px)
b = getBlue(px)
If px is (255,0,0): #error here
numR += 1
printNow("You have " + numR + " red pixels")
show(pic)

不确定为什么这不起作用..

最佳答案

您不需要单独获取颜色。您可以使用 getColor(px) 函数。

此外,Python 中没有函数 printNow(str)。因此,只要此函数不是您使用的任何包的一部分,您就需要使用 print(str)

函数getColor返回一个像Color(255,0,0)这样的对象来比较它,你不能只与元组比较,而是想使用JES 的distance 函数。因此,您需要创建一个 Color 对象进行比较,例如 red = makeColor(255,0,0) 并与此进行比较。 distance 函数的可能输出范围从 0(完全相同的颜色)到 ~441.7(黑色与白色相比)。

所以尝试这样:

red = makeColor(255,0,0)
green = makeColor(0,255,0)
blue = makeColor(0,0,255)

for px in getPixels( pic ):
color = getColor(px)
if distance(color, red) == 0:
numR += 1
elif distance(color, green) == 0:
numG += 1
elif distance(color, blue) == 0:
numB += 1

print("You have " + numR + " red pixels")
print("You have " + numG + " green pixels")
print("You have " + numB + " blue pixels")

我猜你数完后需要总数。如果您想在迭代时输出数字,只需将打印放回循环中即可。

关于python - 在 JES (Jython) 中计算颜色像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46175352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com