python-3.x - 当我使用 PIL 将裁剪粘贴到另一个图像时,它会引发 ValueError

标签 python-3.x python-imaging-library

我正准备将 2.jpg 的一小部分粘贴到 1.jpg

from PIL import Image
body = Image.open("1.jpg")
head = Image.open("2.jpg")
headbox = (0,0,30,30)

head.crop(headbox).save("head.jpg")
body.paste("head.jpg", (0,0)).save("out.jpg")

然后它抛出一个错误
  ****************************************, line 8, in <module>
    body.paste("head.jpg", (0,0)).save("out.jpg")
  File "C:\Users\liton\Anaconda3\lib\site-packages\PIL\Image.py", line 1401, in paste
    "cannot determine region size; use 4-item box"
ValueError: cannot determine region size; use 4-item box

我使用 pycharm 和 python 3.7,但没有看到任何语法错误。所以代码怎么了

最佳答案

您应该将图像对象传递给“body.paste”,但是,您只是传递了一个字符串(图像名称)。所以首先你需要使用'Image.open'打开你的图像,然后将它传递给'body.paste'。此外,'body.paste' 不返回任何值,因此您不能直接使用 'save' 方法。以下代码将解决您的问题:

from PIL import Image
body = Image.open("1.jpg")
head = Image.open("2.jpg")
headbox = (0,0,30,30)

head.crop(headbox).save("head.jpg")
head_crop = Image.open("./head.jpg")
body.paste(head_crop, (0,0))
body.save("out.jpg")

关于python-3.x - 当我使用 PIL 将裁剪粘贴到另一个图像时,它会引发 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077897/

相关文章:

python - 在 Python 中 issubclass() 意外地提示 "Protocols with non-method members"

python - (Python) 使用 PIL 或 PyPNG 在图像中设置特定调色板

Python:将两个PNG文件合并为图层

python - 使用 pyautogui 和 opencv 进行截图

python - 尝试运行简单的 PIL python 示例,无法将 jpeg 转换为 float

python - PIL.ImageTk.PhotoImage 的更快替代方案是什么?

python - 如何使用opencv构建人脸检测程序并启动计时器来记录人脸停留在屏幕上的时间?

python - 乘以包含 NaN 的 Pandas 系列行

Python 3.5 : subclasses of int don't call the __index__ method?

python - Mp3 下载 urllib.request.urlopen() 超时