How can I translate an image by 5 pixels in one of the four directions using PIL and python. I have seen that we can use im.transform(size, AFFINE, data)
but I don't know how to.
Image.transform(size, method, data)
with method=Image.AFFINE
returns a copy of an image where an affine transformation matrix (given as 6-tuple (a, b, c, d, e, f)
via data
) has been applied. For each pixel (x, y)
, the output will be calculated as (ax+by+c, dx+ey+f)
. So if you want to apply a translation, you only have to look at the c
and f
values of your matrix.
from PIL import Image
img = Image.new('RGB', (100, 100), 'red')
a = 1
b = 0
c = 0 #left/right (i.e. 5/-5)
d = 0
e = 1
f = 0 #up/down (i.e. 5/-5)
img = img.transform(img.size, Image.AFFINE, (a, b, c, d, e, f))
img.save('image.png')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With