使用PIL旋转图像出现边缘裁剪,如何保存无裁剪的旋转后图像?
PIL旋转图像避免裁剪的解决方案
PIL原生支持旋转后保留完整图像,无需引入额外依赖,仅需调整rotate()方法的参数即可实现无裁剪效果。
- 原理说明:
Image.rotate()方法默认expand参数为False,会固定保持原始图像的画布尺寸,旋转后超出画布的边缘内容会被自动裁剪;将参数设置为True时,PIL会自动计算旋转后内容的最小外接矩形尺寸,调整输出画布大小以容纳完整内容。
直角旋转(90/180/270度)实现代码
from PIL import Image # 读取本地原图 img = Image.open("original_image.jpg") # 旋转90度,开启expand自动适配画布尺寸 rotated_img = img.rotate(90, expand=True) # 保存无裁剪的旋转后图像 rotated_img.save("rotated_image.jpg")
任意角度旋转补充说明
如果需要旋转非直角角度(如30度、45度),还可搭配fillcolor参数设置空白区域的填充颜色,避免默认黑边影响效果:
# 旋转45度,空白区域填充为白色 rotated_45_img = img.rotate(45, expand=True, fillcolor=(255, 255, 255))
其他可选实现方案(OpenCV)
如果需要使用OpenCV实现相同效果,可参考以下代码:
import cv2 import numpy as np # 读取原图 img = cv2.imread("original_image.jpg") height, width = img.shape[:2] # 生成旋转矩阵:旋转中心为图像中心,旋转角度90度,缩放比例1 rotate_matrix = cv2.getRotationMatrix2D((width/2, height/2), 90, 1) # 计算旋转后所需的新画布尺寸 new_width = int(height * abs(rotate_matrix[0,1]) + width * abs(rotate_matrix[0,0])) new_height = int(height * abs(rotate_matrix[0,0]) + width * abs(rotate_matrix[0,1])) # 调整旋转矩阵的平移参数,避免内容偏移 rotate_matrix[0, 2] += (new_width / 2) - width/2 rotate_matrix[1, 2] += (new_height / 2) - height/2 # 执行旋转 rotated_img = cv2.warpAffine(img, rotate_matrix, (new_width, new_height)) # 保存结果 cv2.imwrite("rotated_image.jpg", rotated_img)
内容的提问来源于stack exchange,提问作者Freddie Moore
相关产品推荐
相关产品推荐

