Skip to content

Instantly share code, notes, and snippets.

@juliussin
Created November 9, 2020 03:22
Show Gist options
  • Save juliussin/cc9de05295659e096a63d8f61d079a43 to your computer and use it in GitHub Desktop.
Save juliussin/cc9de05295659e096a63d8f61d079a43 to your computer and use it in GitHub Desktop.
Perspective transform a point given the transformation matrix.
import cv2
import numpy as np
def point_perspective_transform(point, matrix):
"""
Perspective transform a point given the transformation matrix
:param point: [X, Y] point to be transformed
:param matrix: 3x3 transformation matrix
:return: [X, Y] transformed point
"""
matrix = np.asanyarray(matrix)
if matrix.shape != (3, 3):
raise ValueError('matrix shape should be (3, 3)')
x_temp = (matrix[0, 0] * point[0] + matrix[0, 1] * point[1] + matrix[0, 2]) / (
matrix[2, 0] * point[0] + matrix[2, 1] * point[1] + matrix[2, 2])
y_temp = (matrix[1, 0] * point[0] + matrix[1, 1] * point[1] + matrix[1, 2]) / (
matrix[2, 0] * point[0] + matrix[2, 1] * point[1] + matrix[2, 2])
return np.array([int(x_temp), int(y_temp)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment