Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate image using PIL [duplicate]

Tags:

python

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.

like image 919
RaviTej310 Avatar asked Dec 03 '22 14:12

RaviTej310


1 Answers

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')
like image 116
Squall Avatar answered Dec 18 '22 15:12

Squall