RaviTej310 RaviTej310 - 6 months ago 29
Python Question

Use Python to invert and translate images

I have written the following code to loop through all the images in a folder, create its negative and save it under a new similar name.

How can I do the same thing to translate them by 5 pixels to the right?

Code:

from PIL import Image
import PIL.ImageOps
import glob

files = glob.glob('path/*.JPG') # Use *.* if you're sure all are images

for f in files:
print(1)
image = Image.open(f)
inverted_image = PIL.ImageOps.invert(image)
out = f[:f.rfind('.')]
inverted_image.save('%s-n.JPG'%out)


I searched for a translate function in ImageOps but could not find one. Is there any other way?

Answer

You could take the following approach. This creates a new image 5 pixels bigger and pastes your original image into the new image offset by 5 pixels:

from PIL import Image
import PIL.ImageOps
import glob

shift = 5
files = glob.glob('path/*.JPG') # Use *.* if you're sure all are images

for f in files:
    image = Image.open(f)
    inverted_image = PIL.ImageOps.invert(image)

    out = f[:f.rfind('.')]
    inverted_image.save('%s-n.JPG'%out)

    # Shift the image 5 pixels
    width, height = image.size
    shifted_image = Image.new("RGB", (width+shift, height))
    shifted_image.paste(image, (shift, 0))
    shifted_image.save('%s-shifted.JPG' % out)

If you want the inverted images shifted, change as follows:

    shifted_image.paste(inverted_image, (shift, 0))