Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to put each half of an image on the other half

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

Starting with this:

Original

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading