如何使用面膜贴?

2024-06-08 08:08:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用PILpaste()函数。我也想戴上面具,但我一直有个错误:

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数组。我还没有看到一个带有mask的示例,文档也不清楚。

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"


Tags: orthe函数imagealphaisvalueas
1条回答
网友
1楼 · 发布于 2024-06-08 08:08:45

掩码也必须是PILImage。这里没有明确提到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 Images

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)
...

解决方法是简单地将掩码转换为PILImage

mask = Image.fromarray(mask)

但是,请注意,对于二进制掩码,PIL希望掩码中只有0和255,正如上面所述(两者之间的值将混合)。所以,如果你的面具是一个核型的,那么你需要做如下的事情:

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_img粘贴到左上角的img上,并屏蔽了粘贴操作中约70%的像素,因此区域中只有约30%的像素实际显示为白色。

相关问题 更多 >