使用PILLOW[PIL,Python]将透视校正图像与透明背景模板图像合并

2024-05-15 20:44:38 发布

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

问题:我有多张封面图片。我做了一个“书”样的3D透视模板。现在我所要做的就是拍摄每一张封面图片,纠正一个透视图(它总是不变的,因为模板总是不变的),并将我的透视图纠正后的图片与模板(背景/画布)合并

为便于理解,以下是在Adobe Photoshop中创建的示例: enter image description here

我尝试用红色箭头显示原始封面图像的顶点(在透视校正之前)。如您所见,右侧的两个顶点必须保持不变。左侧的其他两点必须始终进行校正

你能告诉我如何做到这一点吗

更新 我所拥有的:

1)覆盖自身enter image description here

2)具有透明背景的模板:enter image description here

我需要转换封面的透视图,并将其与模板图像合并


Tags: 图像模板示例画布图片箭头adobe透视图
1条回答
网友
1楼 · 发布于 2024-05-15 20:44:38

您实际上不需要编写任何Python,只需在终端中使用ImageMagick使用透视变换即可,如下所示:

magick cover.png -virtual-pixel none -distort perspective "0,0 96,89 %w,0 325,63 %w,%h 326,522 0,%h 96,491" template.png +swap -flatten result.png

enter image description here

查看透视变换的参数,您有望看到有4对坐标,变换的每个角对应一对坐标,显示源位置在输出图像中的映射方式

因此,封面的左上角(0,0)映射到模板(96,89)中空白区域的左上角。封面的右上角(宽度,0)映射到模板(325,63)空白区域的右上角。封面的右下角(宽度、高度)映射到模板(326522)上空白区域的右下角。封面的左下角(0,高度)映射到模板空白区域(96491)的左下角

如果您正在使用旧的v6ImageMagick,请将magick替换为convert


请注意,如果您确实想在Python中执行此操作,那么有一个名为wandhere的Python绑定。我对wand不是很有经验,但这似乎相当于:

#!/usr/bin/env python3

from itertools import chain
from wand.color import Color
from wand.image import Image

with Image(filename='cover.png') as cover, Image(filename='template.png') as template:
    w, h = cover.size
    cover.virtual_pixel = 'transparent'
    source_points = (
        (0, 0),
        (w, 0),
        (w, h),
        (0, h)
    )
    destination_points = (
        (96, 89),
        (325, 63),
        (326, 522),
        (96, 491)
    )
    order = chain.from_iterable(zip(source_points, destination_points))
    arguments = list(chain.from_iterable(order))
    cover.distort('perspective', arguments)

    # Overlay cover onto template and save
    template.composite(cover,left=0,top=0)
    template.save(filename='result.png')

关键词:Python、ImageMagick、魔杖、图像处理、透视变换、扭曲

相关问题 更多 >