python-3.ximagemagickimagemagick-convert

How to distort an image using wand


I'm trying to the same that was asked in this old question but in python using wand.

so far I have done the following:

from wand.image import Image
from wand.display import display

# Paths to your input images
background_path = 'background.png'
source_path = 'source.jpg'
output_path = 'output.jpg'

# Open the background image
with Image(filename=background_path) as background:
    # Open the source image (source)
    with Image(filename=source_path) as source:
        # Define the distortion points
        distortion_points = (
            0, 0, 0, 0,
            265, 0, 540, 85,
            265, 333, 594, 426,
            0, 333, 342, 446
        )

        # Apply the perspective distortion to the blank image
        source.distort('perspective', distortion_points)

        # Composite the background image onto the distorted source
        background.composite(source, 317, 99)

        # Save the resulting image
        background.save(filename=output_path)

display(Image(filename='output.jpg'))

The flower image is distorted and the pixel aren't aligned.

Any idea on how to achieve the same only in python?

EDIT:

This is the current status

current result Current result

expected result Expected result

background image Background image

source image

Source image

Thanks


Solution

  • I think you need to do it more like this:

    #!/usr/bin/env python3
    
    from wand.image import Image
    from wand.display import display
    
    # Paths to your input images
    background_path = 'background.jpg'
    source_path = 'source.jpg'
    output_path = 'output.jpg'
    
    # Open the background image
    with Image(filename=background_path) as background:
        # Open the source image (source)
        with Image(filename=source_path) as source:
            # Define the distortion points
            distortion_points = (
                0, 0, 317, 99,
                265, 0, 540, 85,
                265, 333, 594, 426,
                0, 333, 342, 446
            )
            # See https://docs.wand-py.org/en/0.6.7/guide/distortion.html
            source.virtual_pixel = 'transparent'
            source.artifacts['distort:viewport'] = f'{background.width}x{background.height}+0+0'
    
            # Apply the perspective distortion to the blank image
            source.distort('perspective', distortion_points)
    
            # Composite the distorted source onto the background
            background.composite(source, 0, 0)
    
            # Save the resulting image
            background.save(filename=output_path)
    
    display(Image(filename='output.jpg'))
    

    enter image description here


    Note, on macOS, I had to set MAGICK_HOME to enable wand to find ImageMagick libraries using:

    export MAGICK_HOME=$(brew --repository)