import cv2 import numpy as np import random # 弧度转换 def rad(x): return x * np.pi / 180 # 图像透视变换 def transform(img, anglex=0, angley=0, anglez=0, fov=42): ''' 图像透视变换 :param img: 输入原始图像BGR图像 :param anglex: x方向旋转角度 :param angley: y方向旋转角度 :param anglez: z方向旋转角度 :param fov: :return: ''' w, h = img.shape[0:2] z = np.sqrt(w ** 2 + h ** 2) / 2 / np.tan(rad(fov / 2)) rx = np.array([[1, 0, 0, 0], [0, np.cos(rad(anglex)), -np.sin(rad(anglex)), 0], [0, -np.sin(rad(anglex)), np.cos(rad(anglex)), 0, ], [0, 0, 0, 1]], np.float32) ry = np.array([[np.cos(rad(angley)), 0, np.sin(rad(angley)), 0], [0, 1, 0, 0], [-np.sin(rad(angley)), 0, np.cos(rad(angley)), 0, ], [0, 0, 0, 1]], np.float32) rz = np.array([[np.cos(rad(anglez)), np.sin(rad(anglez)), 0, 0], [-np.sin(rad(anglez)), np.cos(rad(anglez)), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], np.float32) r = rx.dot(ry).dot(rz) # 四对点的生成 pcenter = np.array([h / 2, w / 2, 0, 0], np.float32) p1 = np.array([0, 0, 0, 0], np.float32) - pcenter p2 = np.array([w, 0, 0, 0], np.float32) - pcenter p3 = np.array([0, h, 0, 0], np.float32) - pcenter p4 = np.array([w, h, 0, 0], np.float32) - pcenter dst1 = r.dot(p1) dst2 = r.dot(p2) dst3 = r.dot(p3) dst4 = r.dot(p4) list_dst = [dst1, dst2, dst3, dst4] org = np.array([[0, 0], [w, 0], [0, h], [w, h]], np.float32) dst = np.zeros((4, 2), np.float32) # 投影至成像平面 for i in range(4): dst[i, 0] = list_dst[i][0] * z / (z - list_dst[i][2]) + pcenter[0] dst[i, 1] = list_dst[i][1] * z / (z - list_dst[i][2]) + pcenter[1] warpR = cv2.getPerspectiveTransform(org, dst) result = cv2.warpPerspective(img, warpR, (h, w), borderMode=cv2.BORDER_REPLICATE) return result if __name__ == '__main__': # 测试图片路径 path = r'./000000.jpg' image = cv2.imread(path) x = 0 y = 0 z = 0 fov = 20 while True: x = random.randint(70, 75) x = random.randint(70, 75) z = random.randint(70, 75) result = transform(image, anglex=x, angley=y, anglez=z, fov=fov) cv2.imshow('r', result) cv2.waitKey(1000)