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

Question:

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

Asked By: ati

||

Answers:

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:

Answered By: arsho

Actually, you can use ImageChops.offset to do that very simply:

from PIL import Image, ImageChops

# Open image
im = Image.open('...')

# Roll image by half its width in x-direction, and not at all in y-direction
ImageChops.offset(im, xoffset=int(im.width/2), yoffset=0).save('result.png')

Other libraries/packages, such as ImageMagick, refer to this operation as "rolling" an image, because the pixels that roll off one edge roll into the opposite edge.

Here’s a little animation showing what it is doing:

enter image description here

Answered By: Mark Setchell