Reputation: 81
I need to replace each half of an image with the other half:
Starting with this:
Ending with this:
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')
Upvotes: 2
Views: 539
Reputation: 207375
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:
Upvotes: 2
Reputation: 13651
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
:
output.png
:
Explanation:
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:
Upvotes: 3