Projective transformation in OpenCV

The affine transformations (translation, scaling, rotation, etc.) described above are all object transformations in two-dimensional space. If rotation occurs in three-dimensional space, then this transformation is a projection transformation. Projection transformation needs to first calculate the projection transformation matrix

 cv2.getPerspectiveTransform(src, dst)

Among them, src and dst are both 4×2 two-dimensional matrices ( ndarray ), each row is a coordinate, representing four points of upper left, upper right, lower left and lower right respectively, the data type is 32-bit floating point type, the function’s The return value is the projection transformation matrix, which is a 3×3 matrix. That is to say, src gets dst after the transformation matrix

Once the transformation matrix is ​​obtained, the projection transformation can be performed by using

 cv2.warpPerspective(src, M, dsize[, dst[, flags[, borderMode[, borderValue]]]])

in,

  • src : original image
  • M : a 3×3 transformation matrix
  • dsize : the size of the output image

Example

 import cv2 import numpy as np imgname = "lenna.png" image = cv2.imread(imgname, cv2.IMREAD_COLOR) height, width = image.shape[:2] src = np.array([[0, 0], [width-5, 0], [0, height-5], [width-5, height-5]], np.float32) dst = np.array([[100,100], [width/3, 10], [100, height-5], [width-5, height-5]], np.float32) M = cv2.getPerspectiveTransform(src, dst) dst = cv2.warpPerspective(image, M, (width, height), borderValue=125) cv2.imshow("dst image", dst) cv2.imshow("original image", image) cv2.waitKey(0) cv2.destroyAllWindows()

This article is reprinted from https://xugaoxiang.com/2022/07/16/opencv-projective-transform/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment