What is affine transformation? python implementation example



Software

Release date:2023/11/11         

In Japanese
Premise knowledge
python , tkinter
Matrix


■What is affine transformation?

Affine transformation is a process that uses a matrix to scale, rotate, or translation an image, and is expressed by the following formula.



<Scale>
Setting values for a and e will scale by that number. Below is a 2x example.



<Translation>
Below is the case where only 2 is moved.



<Rotate>
Taking the case of rotation by 90 degrees as an example, the calculation is simple and easy to understand.



<Reflection>
The X value is inverted.



<Shear>
Shear is the application of force in a parallel direction to any surface. This process is also called skew (distortion).


■Example of implementing affine transformation in python

It is also possible to scale and rotate at the same time. The affine transformation function "Image.NEAREST" defines the data interpolation method when enlarging an image, and uses a method called Nearest Neighbor.

import numpy as np
import tkinter as tk
from PIL import Image, ImageTk

app = tk.Tk()
img = Image.open('test.png')    # Get image file information. text.png can be set arbitrarily

affine = np.array([    # Scale and rotate
            [1, -0.5, 0],
            [0.5, 0.7, 0],
            [0, 0, 1]])

aff_inv = np.linalg.inv(affine)        # Affine transformation inverse matrix
aff_tuple = tuple(aff_inv.flatten())        # Convert affine inverse matrix to one dimension
img = img.transform((300,300),Image.AFFINE,aff_tuple,Image.NEAREST) # Affine transformation
tk_img = ImageTk.PhotoImage(img)

canvas = tk.Canvas(app, width=300, height=300)        # Creating an image display area
canvas.pack()
canvas.create_image(0, 0 , anchor = tk.NW, image=tk_img)        # Image display

app.mainloop()


<Result>
The left image is the original image, and the right image is the image after affine transformation. (Reference: How to display images using tkinter)










List of related articles



Software