Search code examples
pythonwand

Can you crop multiple areas from the same image with Wand?


I have two images and would like to extract multiple areas from the first image and overlay them on the second image. Is there a way to crop multiple areas from an image without loading the first image in again with Python Wand? Something like the opposite of +repage in ImageMagick.

bg_img = Image(filename = 'second_image.jpg')

fg_img = Image(filename = 'first_image.jpg')
left = 50
top = 600
width = 30
height = 30
fg_img.crop(left, top, width=width, height=height)

bg_img.composite(fg_img, left, top)

fg_img = Image(filename = 'first_image.jpg')
left = 500
top = 600
width = 100
height = 30
fg_img.crop(left, top, width=width, height=height)

bg_img.composite(fg_img, left, top)

bg_img.save(filename='second_image_plus_overlays.png')

Solution

  • You can do that in Python Wand by cloning the input.

    Input:

    enter image description here

    from wand.image import Image
    from wand.display import display
    
    with Image(filename='lena.jpg') as img:
        with img.clone() as copy1:
            copy1.crop(left=50, top=100, width=100, height=50)
            copy1.save(filename='lena_crop1.jpg')
            display(copy1)
        with img.clone() as copy2:
            copy2.crop(left=100, top=50, width=50, height=100)
            copy2.save(filename='lena_crop2.jpg')
            display(copy2)
    

    Result 1:

    enter image description here

    Result 2:

    enter image description here