python - 使用 PIL 复制三角形图像区域

标签 python image-processing python-imaging-library affinetransform

我有两张 PIL 图像和两组相应的二维点组成一个三角形。

例如:

image1:
100x100 pixels
points = [(10,10), (20,20), (10,20)]

image2:
250x250 pixels
points = [(35,30), (75,19), (50,90)]

我想从 image1 复制三角形区域并将其变换以适合 image2 的相应三角形区域。有没有什么方法可以用 PIL 做到这一点,而不必逐个像素地复制并自己计算转换?

最佳答案

我能够通过仿射变换做到这一点(感谢 this question )。仿射变换后,目标三角形被绘制到蒙版上,然后粘贴到目标图像上。这是我想出的:

import Image
import ImageDraw
import numpy

def transformblit(src_tri, dst_tri, src_img, dst_img):
    ((x11,x12), (x21,x22), (x31,x32)) = src_tri
    ((y11,y12), (y21,y22), (y31,y32)) = dst_tri

    M = numpy.array([
                     [y11, y12, 1, 0, 0, 0],
                     [y21, y22, 1, 0, 0, 0],
                     [y31, y32, 1, 0, 0, 0],
                     [0, 0, 0, y11, y12, 1],
                     [0, 0, 0, y21, y22, 1],
                     [0, 0, 0, y31, y32, 1]
                ])

    y = numpy.array([x11, x21, x31, x12, x22, x32])

    A = numpy.linalg.solve(M, y)

    src_copy = src_img.copy()
    srcdraw = ImageDraw.Draw(src_copy)
    srcdraw.polygon(src_tri)
    src_copy.show()
    transformed = src_img.transform(dst_img.size, Image.AFFINE, A)

    mask = Image.new('1', dst_img.size)
    maskdraw = ImageDraw.Draw(mask)
    maskdraw.polygon(dst_tri, fill=255)

    dstdraw = ImageDraw.Draw(dst_img)
    dstdraw.polygon(dst_tri, fill=(255,255,255))
    dst_img.show()
    dst_img.paste(transformed, mask=mask)
    dst_img.show()


im100 = Image.open('test100.jpg')
im250 = Image.open('test250.jpg')

tri1 = [(10,10), (20,20), (10,20)]
tri2 = [(35,30), (75,19), (50,90)]

transformblit(tri1, tri2, im100, im250)

源 100x100 图像如下所示(白色三角形覆盖):

src_before

目标 250x250 图像如下所示(用白色填充的三角形区域):

dst_before

然后在转换和粘贴之后,目标图像看起来像这样:

dst_after

关于python - 使用 PIL 复制三角形图像区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6946653/

相关文章:

python - 通过线程向数据库中插入数据

c++ - IP 摄像机和 OPENCV

c# - 如何在 .net 中使用 imagemagick.net?

c - 在 openCV 中访问 mat 元素

python - 将 RGB 三元组列表排序为光谱

python - 是否有可能 "hint"字典键?

python - XPATH 在 python 中选择具有特定属性的根和所有后代元素

python-2.7 - 使用 PIL(枕头)将 EXIF 数据从 TIF(使用 exifread 读取)写入 JPEG 文件

python - PIL 值错误 : not enough image data?

python - 使用 Bonobo 写入绝对文件路径