如何从一个图像裁剪并使用PIL粘贴到另一个图像

Nic*_*ick 10 python crop paste python-imaging-library

大家好.这可能已被问过一百万次了,但我在这里遇到了一些麻烦.使用PIL,我试图从图像中复制一个矩形,然后将其粘贴到另一个图像中.这是我的代码.

import Image
ii = Image.open("ramza.png")
box = (70, 70, 30, 30)
region = ii.crop(box)
io = Image.open("template.png")
io.paste(region, box)
io.save("output.png")
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

ValueError:图像不匹配

你们中的任何人都知道解决这个问题吗?

sam*_*ias 15

PIL裁剪框定义为像素坐标的4元组:(left, upper, right, lower).

要修复代码以获得30x30的裁剪:

box = (70, 70, 100, 100)
Run Code Online (Sandbox Code Playgroud)

细分为:

x, y, w, h = (70, 70, 30, 30)
box = (x, y, x + w, y + h)
Run Code Online (Sandbox Code Playgroud)