Home > Net >  How to put each half of an image on the other half
How to put each half of an image on the other half

Time:11-27

I need to replace each half of an image with the other half:

Starting with this:

Original

Ending with this:

Desired

I have tried to use crop, but I want the image to keep the same dimensions, and this seems to just cut it.


im = Image.open("image.png")
w, h = im.size

im = im.crop((0,0,int(w/2),h))

im.paste(im, (int(w/2),0,w,h))

im.save('test.png')

CodePudding user response:

How to rotate the x direction of an image

You are nearly there. You need to keep the left and right portion of the image into two separate variables and then paste them in opposite direction on the original image.

from PIL import Image
output_image = 'test.png'
im = Image.open("input.png")
w, h = im.size
left_x = int(w / 2) - 2
right_x = w - left_x
left_portion = im.crop((0, 0, left_x, h))
right_portion = im.crop((right_x, 0, w, h))
im.paste(right_portion, (0, 0, left_x, h))
im.paste(left_portion, (right_x, 0, w, h))
im.save(output_image)
print(f"saved image {output_image}")

input.png:

input.png

output.png:

test.png

Explanation:

  • I used left_x = int(w / 2) - 2 as to keep the middle border line in the middle. You may change it as it fits to your case.

References:

  • enter image description here

  • Related