Python – Combines two warpAffine, moves and rotates images

Combines two warpAffine, moves and rotates images… here is a solution to the problem.

Combines two warpAffine, moves and rotates images

I currently use the following code sequence to first move the image and then rotate the same image:

M = np.float32([[1,0,20],[0,1,10]])
shifted = cv2.warpAffine(img,M,(y_size,x_size),flags=cv2. INTER_LANCZOS4)
center_of_rot = (500, 500)
M = cv2.getRotationMatrix2D(center_of_rot, 1.23, 1.0)
rotated = cv2.warpAffine(shifted, M, (y_size, x_size),flags=cv2. INTER_LANCZOS4)

I

think it’s possible to somehow multiply two matrices and do only one operation instead of warpAffine twice, I’m looking for some guidance because my math sucks.

Thanks!

Solution

You must multiply the matrices together. Add the third row [0,0,1] to the 2×3 matrix. This is called homogeneous coordinates.

M = np.float32([[1,0,20],[0,1,10],[0,0,1]]) // shift matrix
center_of_rot = (500, 500)
Rot = cv2.getRotationMatrix2D(center_of_rot, 1.23, 1.0)
Rot = np.vstack([Rot, [0,0,1]])
TransfomMatrix = np.matmul(M, Rot)
rotated = cv2.warpPerspective(img, TransformMatrix, (y_size, x_size),flags=cv2. INTER_LANCZOS4) //  note - warpPerspective is used here, because the matrix is now 3x3 not 3x2

Related Problems and Solutions