本文目录导读:

我来介绍几种在Python中旋转图片角度的方法,主要使用PIL(Pillow)和OpenCV这两个库。
使用Pillow库
基本旋转
from PIL import Image
# 打开图片
image = Image.open('input.jpg')
# 旋转图片(逆时针旋转90度)
rotated_90 = image.rotate(90, expand=True)
# 旋转45度
rotated_45 = image.rotate(45, expand=True)
# 旋转180度
rotated_180 = image.rotate(180, expand=True)
# 保存旋转后的图片
rotated_90.save('rotated_90.jpg')
rotated_45.save('rotated_45.jpg')
rotated_180.save('rotated_180.jpg')
完整的Pillow旋转示例
from PIL import Image
import matplotlib.pyplot as plt
def rotate_image_pillow(image_path, angle, expand=True):
"""
使用Pillow旋转图片
:param image_path: 图片路径
:param angle: 旋转角度(逆时针)
:param expand: 是否扩展画布以适应旋转后的图片
:return: 旋转后的图片
"""
# 打开图片
img = Image.open(image_path)
# 旋转图片
rotated_img = img.rotate(angle, expand=expand, fillcolor='white')
return rotated_img
# 使用示例
if __name__ == '__main__':
# 旋转45度
rotated = rotate_image_pillow('input.jpg', 45)
rotated.save('rotated_45_degrees.jpg')
# 显示原图和旋转后的图片
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
original = Image.open('input.jpg')
plt.imshow(original)
plt.title('Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(rotated)
plt.title('Rotated 45 Degrees')
plt.axis('off')
plt.show()
使用OpenCV库
基本旋转
import cv2
import numpy as np
# 读取图片
image = cv2.imread('input.jpg')
# 获取图片尺寸
height, width = image.shape[:2]
# 计算旋转中心(通常是图片中心)
center = (width // 2, height // 2)
# 旋转90度
rotation_matrix = cv2.getRotationMatrix2D(center, 90, 1.0)
rotated_90 = cv2.warpAffine(image, rotation_matrix, (width, height))
# 旋转45度(需要调整输出尺寸)
rotation_matrix = cv2.getRotationMatrix2D(center, 45, 1.0)
rotated_45 = cv2.warpAffine(image, rotation_matrix, (width, height))
# 保存结果
cv2.imwrite('rotated_90_opencv.jpg', rotated_90)
cv2.imwrite('rotated_45_opencv.jpg', rotated_45)
完整的OpenCV旋转示例(带边框处理)
import cv2
import numpy as np
def rotate_image_opencv(image_path, angle, scale=1.0):
"""
使用OpenCV旋转图片
:param image_path: 图片路径
:param angle: 旋转角度
:param scale: 缩放比例
:return: 旋转后的图片
"""
# 读取图片
img = cv2.imread(image_path)
height, width = img.shape[:2]
# 计算旋转中心
center = (width // 2, height // 2)
# 获取旋转矩阵
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)
# 计算新的边界尺寸
cos = np.abs(rotation_matrix[0, 0])
sin = np.abs(rotation_matrix[0, 1])
new_width = int((height * sin) + (width * cos))
new_height = int((height * cos) + (width * sin))
# 调整旋转矩阵以考虑新的中心
rotation_matrix[0, 2] += (new_width / 2) - center[0]
rotation_matrix[1, 2] += (new_height / 2) - center[1]
# 执行旋转
rotated_img = cv2.warpAffine(img, rotation_matrix, (new_width, new_height))
return rotated_img
# 使用示例
if __name__ == '__main__':
# 旋转-90度(顺时针90度)
rotated = rotate_image_opencv('input.jpg', -90)
cv2.imwrite('rotated_minus_90.jpg', rotated)
# 旋转多个角度
for angle in [30, 45, 60, 90, 180]:
rotated = rotate_image_opencv('input.jpg', angle)
cv2.imwrite(f'rotated_{angle}_opencv.jpg', rotated)
使用scikit-image库
from skimage import io, transform
import matplotlib.pyplot as plt
# 读取图片
image = io.imread('input.jpg')
# 旋转图片(逆时针45度,自动调整尺寸)
rotated = transform.rotate(image, 45, resize=True)
# 显示结果
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(image)'Original Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(rotated)'Rotated 45 Degrees')
plt.axis('off')
plt.show()
# 保存图片
io.imsave('rotated_skimage.jpg', rotated)
批量处理多张图片
import os
from PIL import Image
def batch_rotate_images(input_folder, output_folder, angle):
"""
批量旋转文件夹中的所有图片
:param input_folder: 输入文件夹路径
:param output_folder: 输出文件夹路径
:param angle: 旋转角度
"""
# 创建输出文件夹
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 支持的图片格式
supported_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff']
# 遍历文件夹中的所有文件
for filename in os.listdir(input_folder):
file_path = os.path.join(input_folder, filename)
# 检查是否为图片文件
if os.path.isfile(file_path):
ext = os.path.splitext(filename)[1].lower()
if ext in supported_formats:
try:
# 打开并旋转图片
img = Image.open(file_path)
rotated_img = img.rotate(angle, expand=True)
# 保存到输出文件夹
output_path = os.path.join(output_folder, f"rotated_{filename}")
rotated_img.save(output_path)
print(f"已处理: {filename}")
except Exception as e:
print(f"处理 {filename} 时出错: {e}")
# 使用示例
batch_rotate_images('input_images', 'output_images', 90)
安装所需库
# 安装必要的库 pip install Pillow opencv-python scikit-image matplotlib
关键参数说明
-
旋转角度:
- 正数:逆时针旋转
- 负数:顺时针旋转
-
旋转中心:
- 默认为图片中心
- 可以自定义旋转点
-
图片尺寸调整:
expand=True(Pillow):自动调整画布大小,避免裁剪resize=True(skimage):自动调整尺寸
-
填充颜色:
- Pillow的
fillcolor参数设置旋转后空白区域的颜色 - OpenCV的
borderMode参数设置边界模式
- Pillow的
选择哪种方法取决于你的具体需求:
- Pillow:简单易用,适合大多数场景
- OpenCV:性能好,支持更多高级功能
- scikit-image:科学计算友好,自动处理边界
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播