![](/img/trans.png)
[英]Is there a faster alternative to PIL's Image.paste for multiple images?
[英]PIL Image.paste not pasting small images over a big image
我正在尝试创建一个完整的图像并希望将较小的图像粘贴到它上面。 这是我的代码示例。
from PIL import Image
imageWidth=5760
imageHeight=2880
image_sheet = Image.new("RGB", (imageWidth, imageHeight), (255, 255, 255))
这将创建一个图像 object,其规格如 arguments 中所述。现在我想在此图像上粘贴尺寸为 512*512 的图像。例如,
image=np.zeros((512,512))
image_sheet.paste(image,box=(0,0)) # I am trying to paste image of size 512*512 at upper left location of (0,0) as per the documentation
我收到此错误:
File "C:\Users\SSHUB\Anaconda3\envs\dl_torch\lib\site-packages\PIL\Image.py", line 1537, in paste
raise ValueError("cannot determine region size; use 4-item box")
ValueError: cannot determine region size; use 4-item box
如果我使用像这样的 4 项框image_sheet.paste(image,box=(0,0,512,512))
,我会收到以下错误:
File "C:\Users\SSHUB\Anaconda3\envs\dl_torch\lib\site-packages\PIL\Image.py", line 1559, in paste
self.im.paste(im, box)
TypeError: color must be int or tuple
我正在使用枕头 9.0.1。 请指导如何解决此问题。
您不能将 Numpy 数组粘贴到PIL Image
中。 您需要先将 Numpy 数组制作成PIL Image
:
from PIL import Image
import numpy as np
imageWidth=5760
imageHeight=2880
image_sheet = Image.new("RGB", (imageWidth, imageHeight), (255, 255, 255))
# Make little image to paste
image=np.zeros((512,512), dtype=np.uint8)
image_sheet.paste(Image.fromarray(image), ...)
另外,注意dtype
:!! 例子:
image=np.zeros((512,512))
print(image.dtype)
'float64' !!!! which is UNACCEPTABLE to PIL
或者,您可以直接在 PIL 中制作小图像:
image_sheet.paste(Image.new("RGB", (512,512), 'red'), ...)
Image.paste()
只接受另一个Image
实例或像素颜色(可以是字符串、integer 或元组,具体取决于图像的模式)。
您传入了一个 numpy 数组,它不是图像,也不是有效的像素颜色。 首先将其设为图像,例如使用Image.fromarray()
:
image_sheet.paste(Image.fromarray(image))
也许将image_sheet.mode
作为第二个参数传递给Image.fromarray()
。 我省略了Image.paste()
的box
参数,因为默认值为(0, 0)
。
Image.paste()
方法的实现方式,如果你不传入图像,它假设你传入的是像素颜色,在这种情况下你必须指定一个 4 值框,因此第一个错误信息。 当你给它一个 4 值的盒子时,它才会告诉你你传入的不是像素颜色!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.