if 语句在尝试检测像素的颜色时始终返回 false



所以我正在重新开始使用 pygame 处理一个项目,我正在尝试使 50x50 图像的背景透明(最初为黑色),但我无法更改像素的颜色

这是我现在的代码:

image2BCleared = Image.open("C:/Users/UserName/Desktop/PythonGame/image_player.png")
imageArray = numpy.array(image2BCleared)
width, height = image2BCleared.size
transparent = (0, 0, 0, 0)
newDataItem = (0,0,0,0)
for i in range(0, width):
for j in range(0, height):
newDataItem = imageArray[i][j]
if newDataItem.all == (0, 0, 0, 255):
imageArray[i][j] = transparent
print(imageArray[i][j])
dirpath = os.getcwd()
im = Image.fromarray(imageArray)
im.save("img2.png", "PNG")

当我运行程序时,打印语句没有输出。

出于某种原因,尽管数组上的内容相同,但它总是转到"else"语句事件(我使用了这段代码):

imageArray = numpy.array(image2BCleared)
width, height = image2BCleared.size
newData = []
counterI = 0
counterJ = 0
for item in imageArray:
if item.all == (0, 0, 0, 225):
newData.append((255, 255, 255, 0))
print("true")
else:
newData.append(item)
print(newData)

输出:

[array([[  0,   0,   0, 255],
[  0,   0,   0, 255],
[  0,   0,   0, 255],
[  0,   0,   0, 255],
[  0,   0,   0, 255],
#fowllowed by other pixels from different colors but nothing transparent

基本上"newData"有很多包含(0,0,0,255)的插槽。 我对图像处理不是很熟悉,所以这可能是一些非常基本的错误,但我真的没有看到任何逻辑问题(将图片转换为像素数组,将像素与某个值进行比较,如果颜色==(0,0,0,255)将透明像素添加到newData,否则将像素添加到newData)

任何帮助将不胜感激

您正在访问 numpy 数组的 .all 属性。 All 实际上是 Numpy 数组类的一种方法,您可以将其用作:

my_array = np.array([1, 2, 3])
my_array.all()

如果my_array的所有元素都是布尔 True,这将返回 true。

因此,您的代码将方法对象与元组进行比较,因此它们当然不相等。

相反,试试这个。 项是一个数组。 您正在尝试与元组进行比较。 您需要将一个转换为另一个或比较元素。

以下任何一种都应该有效,这是我按偏好顺序给出的。 请注意,在使用 np.array() 方法的地方,您可以向其传递元组 (0, 0, 00, 255) 或列表 [0, 0, 0, 255]。

all(item == (0, 0, 0, 255))
(item == (0, 0, 0, 255)).all()
tuple(item) == (0, 0, 0, 255)
all(item == np.array((0, 0, 0, 255)))
(item == np.array([0, 0, 0, 255])).all()
all([a==b for (a,b) in zip(item, (0, 0, 0, 255))])
all([item[i] == (0, 0, 0, 255)[i] for i in range(4)])

编辑:

再添加一个编辑,因为问题的标题可能会引导人们在这里遇到不同的问题。 如果希望两个对象匹配,但它们不匹配,请尝试以下步骤。

使用 type(
  1. object_1) 和 type(object_2) 检查每个类型以验证它们是否相同。 您可以单独打印这些结果进行比较,也可以打印 type(object_1) == type(object_2) 的结果。

  2. 如果它们是可迭代的(例如列表、元组、数组、字典等),则迭代它们并检查每个条目是否匹配。 您可以使用以下方法并排打印两个数组的内容:

    for a, b in zip(object_1, object_2):
    print(a, b)
    

最新更新