gpt4 book ai didi

python - 如何使用PIL贴面膜?

转载 作者:行者123 更新时间:2023-12-04 23:14:03 30 4
gpt4 key购买 nike

我正在尝试使用 PIL paste()功能。我也想戴上面具,但我不断收到此错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


canvases[0].paste(mnist_images[i],
box=tuple(map(lambda p: int(round(p)), positions[i])), mask=mask)

该代码无需掩码即可工作。 Mask 是一个 numpy 数组。我还没有看到带掩码的示例,文档也不清楚。

https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.paste

If a mask is given, this method updates only the regions indicated by the mask. You can use either "1", "L", or "RGBA" images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.



我没有 RGBA 所以我如何使用 "1""L" ?

最佳答案

面具也必须是 PIL Image .这没有明确提及 in the docs ,但它确实指出:

You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values will mix the two images together, including their alpha channels if they have them.



所以这暗示他们需要是 PIL Image s。来自 Pillow concepts page :

The mode of an image defines the type and depth of a pixel in the image. The current release supports the following standard modes:

1 (1-bit pixels, black and white, stored with one pixel per byte)
L (8-bit pixels, black and white)
...



解决方法是简单地将您的面具变成 PIL Image
mask = Image.fromarray(mask)

但是,请注意,对于二进制掩码,PIL 预计掩码内部只有 0 和 255,如上面所述(两者之间的值将混合)。所以如果你的面具是 NumPy 的 bool键入,然后您会想要执行以下操作:
mask = Image.fromarray(np.uint8(255*mask))

例如:
>>> import numpy as np
>>> import cv2
>>> from PIL import Image
>>> img = Image.fromarray(np.uint8(255*np.random.rand(400, 400, 3)))
>>> sub_img = Image.fromarray(np.uint8(255*np.ones((200, 200, 3))))
>>> mask = Image.fromarray(np.uint8(255*(np.random.rand(200, 200) > 0.7)))
>>> img.paste(sub_img, (0, 0), mask)

Masked paste

我在这里粘贴了白色 sub_imgimg在左上角,并从粘贴操作中屏蔽了大约 70% 的像素,因此该区域中只有大约 30% 的像素实际上显示为白色。

关于python - 如何使用PIL贴面膜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47723154/

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