如何使用Python实现图像透视变换?
Python实现图像透视变换(OpenCV/PIL两种方案)
核心思路
透视变换需要通过4组对应点计算变换矩阵,将倾斜/扭曲的图像映射为平面矩形。下面给出两种常用库的实现代码,适配你提到的需求。
方案1:使用OpenCV(推荐,矩阵计算更直观)
import cv2 import numpy as np # 1. 加载图像 img = cv2.imread('input.jpg') height, width = img.shape[:2] # 2. 定义源点与目标点(需替换为你图像的实际坐标) # 源点:目标倾斜区域的四个角(顺时针/逆时针顺序均可,需与目标点顺序对应) src_points = np.float32([[100, 50], [400, 60], [410, 380], [90, 370]]) # 目标点:输出图像的四个角落(生成正矩形) dst_points = np.float32([[0, 0], [width, 0], [width, height], [0, height]]) # 3. 计算透视变换矩阵 perspective_matrix = cv2.getPerspectiveTransform(src_points, dst_points) # 4. 应用变换 transformed_img = cv2.warpPerspective(img, perspective_matrix, (width, height)) # 保存/查看结果 cv2.imwrite('transformed_opencv.jpg', transformed_img) cv2.imshow('Original', img) cv2.imshow('Transformed', transformed_img) cv2.waitKey(0) cv2.destroyAllWindows()
注意事项
- 替换
src_points的坐标:可以用图像查看工具(如GIMP、Photoshop)获取目标区域的四个角坐标。 - 点的顺序必须对应:比如源点的左上、右上、右下、左下,要和目标点的顺序完全匹配。
方案2:使用PIL(Python Imaging Library)
from PIL import Image import numpy as np # 1. 加载图像 img = Image.open('input.jpg') width, height = img.size # 2. 定义对应点(同OpenCV的规则) src_points = np.float32([[100, 50], [400, 60], [410, 380], [90, 370]]) dst_points = np.float32([[0, 0], [width, 0], [width, height], [0, height]]) # 3. 计算透视变换系数(适配PIL的参数格式) matrix = np.linalg.lstsq(np.vstack([src_points.T, [1,1,1,1]]).T, np.vstack([dst_points.T, [1,1,1,1]]).T, rcond=None)[0].T coeffs = matrix.flatten()[:8] # 4. 应用透视变换(使用BICUBIC插值提升画质) transformed_img = img.transform((width, height), Image.PERSPECTIVE, coeffs, Image.BICUBIC) # 保存/查看结果 transformed_img.save('transformed_pil.jpg') transformed_img.show()
补充说明
- 如果不想依赖numpy,也可以手动推导透视变换的系数公式,但用numpy更高效省心。
Image.BICUBIC插值适合细节较多的图像,比默认线性插值的画质更平滑。
内容的提问来源于stack exchange,提问作者Scrapy
相关产品推荐
相关产品推荐

