# -*- coding:utf-8 -*- import cv2 import numpy as np # class wraper(): # def __init__(self): def rad(x):#弧度,角度数×﹙π/180°﹚ return x * np.pi / 180 def rotate_3(img, angle_vari=30): w, h = img.shape[0:2] fov = 42 # anglex = np.random.uniform(-angle_vari, angle_vari) # angley = np.random.uniform(-angle_vari, angle_vari) # anglez = np.random.uniform(-angle_vari + 10, angle_vari - 10) anglex = -60# plan angle angley = -3.5 # align left-right anglez = 5 #tan(FOV/ 2) = (实际视场宽度 / 2) / 实际视距 = (底片宽度 / 2) / 焦距 # 镜头与图像间的距离,21为半可视角,算z的距离是为了保证在此可视角度下恰好显示整幅图像 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), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_REFLECT,# 对称法,以图像边缘为轴进行对称填充 borderValue = 0) return result import os i = 0 if __name__ == '__main__': floor_dir = '/home/yao/Documents/webfloor/wood_floor_resize640' savePath = '/home/yao/Documents/webfloor/wraper_floor_crop2/' floor_list = [img for img in os.listdir(floor_dir)] n = len(floor_list) # im1 = '/home/yao/Documents/webfloor/wood_floor_resize1024/000008.jpg' for im in floor_list: imPath = os.path.join(floor_dir,im) img = cv2.imread(imPath) angle_vari = 60 # while True: result = rotate_3(img, angle_vari=angle_vari) tem = result.copy() # result[tem==0]=100 # result_resize = cv2.resize(result,()) cv2.imwrite('{}/floor_{}.jpg'.format(savePath,i), result) i += 1 # cv2.imwrite('0001.jpg' , result) print(result.shape) # cv2.imshow("result", result) # c = cv2.waitKey(0) # # exit(00)