如何写图片旋转角度脚本

wen 实用脚本 29

本文目录导读:

如何写图片旋转角度脚本

  1. Python + Pillow (最常用)
  2. OpenCV 版本
  3. 批量处理脚本(支持多张图片)
  4. 交互式角度选择脚本
  5. 命令行脚本(带参数)
  6. 安装依赖
  7. 使用说明

Python + Pillow (最常用)

from PIL import Image
def rotate_image(input_path, output_path, angle):
    """
    旋转图片
    :param input_path: 输入图片路径
    :param output_path: 输出图片路径
    :param angle: 旋转角度(顺时针)
    """
    # 打开图片
    img = Image.open(input_path)
    # 旋转图片(expand=True 保持完整显示)
    rotated = img.rotate(angle, expand=True)
    # 保存图片
    rotated.save(output_path)
# 使用示例
rotate_image("input.jpg", "output.jpg", 90)  # 顺时针旋转90度

OpenCV 版本

import cv2
def rotate_image_opencv(input_path, output_path, angle):
    """
    使用OpenCV旋转图片
    """
    # 读取图片
    img = cv2.imread(input_path)
    height, width = img.shape[:2]
    # 获取旋转矩阵
    center = (width // 2, height // 2)
    rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0)
    # 计算新的边界尺寸
    cos = abs(rotation_matrix[0, 0])
    sin = 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 = cv2.warpAffine(img, rotation_matrix, (new_width, new_height))
    # 保存图片
    cv2.imwrite(output_path, rotated)
# 使用示例
rotate_image_opencv("input.jpg", "output.jpg", -45)  # 逆时针旋转45度

批量处理脚本(支持多张图片)

import os
from PIL import Image
import glob
def batch_rotate_images(input_dir, output_dir, angle):
    """
    批量旋转图片
    :param input_dir: 输入目录
    :param output_dir: 输出目录
    :param angle: 旋转角度
    """
    # 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    # 支持多种图片格式
    extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tiff']
    for ext in extensions:
        for file_path in glob.glob(os.path.join(input_dir, ext)):
            # 获取文件名
            filename = os.path.basename(file_path)
            output_path = os.path.join(output_dir, filename)
            # 旋转并保存
            try:
                img = Image.open(file_path)
                rotated = img.rotate(angle, expand=True)
                rotated.save(output_path)
                print(f"已处理: {filename}")
            except Exception as e:
                print(f"处理失败 {filename}: {str(e)}")
# 使用示例
batch_rotate_images("input_folder", "output_folder", 90)

交互式角度选择脚本

from PIL import Image
import tkinter as tk
from tkinter import filedialog, messagebox
class ImageRotator:
    def __init__(self, root):
        self.root = root
        self.root.title("图片旋转工具")
        self.root.geometry("300x200")
        # 创建界面元素
        self.label = tk.Label(root, text="选择角度:")
        self.label.pack(pady=10)
        self.angle_var = tk.StringVar(value="90")
        self.angle_entry = tk.Entry(root, textvariable=self.angle_var, width=10)
        self.angle_entry.pack()
        self.select_btn = tk.Button(root, text="选择图片", command=self.select_and_rotate)
        self.select_btn.pack(pady=20)
    def select_and_rotate(self):
        # 选择文件
        file_path = filedialog.askopenfilename(
            title="选择图片",
            filetypes=[("图片文件", "*.jpg *.jpeg *.png *.bmp")]
        )
        if not file_path:
            return
        try:
            # 获取角度
            angle = float(self.angle_var.get())
            # 旋转图片
            img = Image.open(file_path)
            rotated = img.rotate(angle, expand=True)
            # 保存文件
            save_path = filedialog.asksaveasfilename(
                defaultextension=".jpg",
                filetypes=[("JPEG", "*.jpg"), ("PNG", "*.png"), ("所有文件", "*.*")]
            )
            if save_path:
                rotated.save(save_path)
                messagebox.showinfo("成功", f"图片已保存到: {save_path}")
        except ValueError:
            messagebox.showerror("错误", "请输入有效的角度值")
        except Exception as e:
            messagebox.showerror("错误", f"处理失败: {str(e)}")
# 运行程序
if __name__ == "__main__":
    root = tk.Tk()
    app = ImageRotator(root)
    root.mainloop()

命令行脚本(带参数)

#!/usr/bin/env python3
import argparse
from PIL import Image
def main():
    parser = argparse.ArgumentParser(description='图片旋转工具')
    parser.add_argument('input', help='输入图片路径')
    parser.add_argument('output', help='输出图片路径')
    parser.add_argument('-a', '--angle', type=float, required=True,
                       help='旋转角度(度)')
    parser.add_argument('-e', '--expand', action='store_true',
                       help='扩展画布以显示完整图片')
    args = parser.parse_args()
    try:
        img = Image.open(args.input)
        rotated = img.rotate(args.angle, expand=args.expand)
        rotated.save(args.output)
        print(f"成功: 图片已旋转 {args.angle} 度")
    except Exception as e:
        print(f"错误: {str(e)}")
if __name__ == "__main__":
    main()

安装依赖

# 安装 Pillow
pip install Pillow
# 安装 OpenCV(可选)
pip install opencv-python

使用说明

  1. 基本使用:直接调用旋转函数
  2. 批量处理:使用 batch_rotate_images() 函数
  3. 命令行使用
    python script.py input.jpg output.jpg -a 90 -e
  4. 交互式使用:运行带 GUI 的脚本

选择适合你需求的版本即可,如果是简单任务,推荐使用 Pillow 版本;如果需要更多图像处理功能,可以选择 OpenCV 版本。

抱歉,评论功能暂时关闭!