Skip to content Skip to sidebar Skip to footer

Merging Perspective Corrected Image With Transparent Background Template Image Using Pillow [pil, Python]

Problem: I have multiple book cover images. I made a template of 'book'-like template with a 3D perspective. And all I have to do now its take each of book cover images, correct a

Solution 1:

You don't really need to write any Python, you can just do it in the Terminal with ImageMagick using a "Perspective Transform" like this:

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

Looking at the parameters to the perspective transform, you can hopefully see there are 4 pairs of coordinates, one pair for each corner of the transform showing how the source location gets mapped in the output image.

So, the top-left corner of the cover (0,0) gets mapped to the top-left of the empty area in the template (96,89). The top right of the cover (width,0) gets mapped to the top-right of the empty area of the template (325,63). The bottom-right of the cover (width,height) gets mapped to the bottom-right of the empty area on the template (326,522). The bottom-left of the cover (0,height) gets mapped to the bottom-left corner of the empty area of the template (96,491).

If you are using the old v6 ImageMagick, replace magick with convert.


Note that, if you really want to do it in Python, there is a Python binding called wandhere. I am not very experienced with wand but this seems to be equivalent:

#!/usr/bin/env python3from 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')

Keywords: Python, ImageMagick, wand, image processing, perspective transform, distort.

Post a Comment for "Merging Perspective Corrected Image With Transparent Background Template Image Using Pillow [pil, Python]"