What is affine transformation ?
Affine transformation is the linear transformation plus translation of an image , Represented by a picture , namely
from image1 reach image2 There are three operations in the transformation of
* rotate ( linear transformation )
* Zoom operation ( linear transformation )
* translation ( Vector plus )
If there's no number one 3 Translation operations , So it's a linear transformation . The first two notes have arranged the rotation of the image , Methods of zooming and panning , Next, we will introduce the matrix representation and usage of affine transformation .
Matrix form of radiation change
The transformation of the image needs to operate on every pixel of the image , Suppose the coordinates of one of the pixels are (x,y), We express it in matrix form :
We usually use Matrix to represent affine transformation .
matrix A,B Is the transformation matrix
The matrix coordinates of the points after affine transformation are T, We already know that radiation transformation is linear transformation plus translation , In matrix terms
It can also be written as
Available by calculation
Use code
Let's take a look at the code for image panning
import cv2 import numpy as np img = cv2.imread('Rachel.jpg', 0) rows, cols =
img.shape M = np.float32([[1, 0, 200], [0, 1, 100]]) dst = cv2.warpAffine(img,
M, (cols, rows)) cv2.imshow('img', dst) k = cv2.waitKey(0) if k == ord('s'):
cv2.imwrite('Rachel3.jpg', dst) cv2.destroyAllWindows()
You can see the 7 That's ok M = np.float32([[1, 0, 200], [0, 1, 100]])
Bring the value of this two-dimensional matrix into T, The coordinates of the points after affine transformation are (x+200,y+100), Pan the entire image (200,100)
Look at the code of image rotation again
import cv2 img = cv2.imread('Rachel.jpg', 0) rows, cols = img.shape M =
cv2.getRotationMatrix2D((cols / 2, rows / 2), 90, 1) dst = cv2.warpAffine(img,
M, (cols, rows)) # affine transformation , talk later cv2.imshow('Rachel', dst) cv2.waitKey(0)
cv2.destroyAllWindows()
Most of the same , It's just one of them M Matrix difference
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), 90, 1) # The first parameter is the coordinates of the center point
cv2.getRotationMatrix2D This function is used to generate the matrix needed for image rotation
So how to transform any graph by affine transformation ?
We need three points mapped one by one on the source image and the target image to define the affine transformation
Sample code :
img = cv2.imread('Rachel.jpg') rows, cols, ch = img.shape pts1 =
np.float32([[0, 0], [cols - 1, 0], [0, rows - 1]]) pts2 = np.float32([[cols *
0.2, rows * 0.1], [cols * 0.9, rows * 0.2], [cols * 0.1, rows * 0.9]]) M =
cv2.getAffineTransform(pts1, pts2) dst = cv2.warpAffine(img, M, (cols, rows))
cv2.imshow('image', dst) k = cv2.waitKey(0) if k == ord('s'):
cv2.imwrite('Rachel1.jpg', dst) cv2.destroyAllWindows()
result :
Technology
Daily Recommendation