Python基于OpenCV实现图像批量旋转与缩放操作

温以宁
温以宁
发布时间:2026-10-11 | 2人浏览过
原创

本文介绍如何使用 Python 结合 OpenCV 编写一段通用批处理脚本,实现指定目录下图像文件的批量旋转与尺寸缩放。通过 argparse 封装命令行参数,用户只需一条指令即可完成多图片的统一转换与存储,大幅简化重复性图像处理流程。

Python 图像批量处理需求与方案

日常开发或数据预处理中,经常需要对大量图像进行统一缩放或旋转。相较于 C++ 等语言需要频繁管理内存与编译环境,使用 Python 配合 OpenCV 库能显著减少代码量并提升执行效率。本文将提供一套开箱即用的批处理脚本,通过命令行参数灵活控制输入目录、输出路径及具体操作,支持批量旋转(仅限 90°、180°、270°)与尺寸调整。

第 1 步:安装运行依赖

脚本依赖于 Python 标准库与第三方图像处理库。在本地环境中安装 opencv-python 后即可运行:

  • 操作系统:Windows / macOS / Linux
  • 依赖包:opencv-python
  • 安装命令:pip install opencv-python

第 2 步:获取核心批处理代码

将所有功能整合至单一文件中,便于后续维护与调用。以下为完整实现代码:

import os
import sys
import cv2
from inspect import currentframe, getframeinfo
import argparse
 
def get_image_list(path, image_suffix):
    image_list = []
    for x in os.listdir(path):
        if x.endswith(image_suffix):
            image_list.append(path + "/" + x)
    return image_list
 
def get_image_name(image_name):
    pos = image_name.rfind("/")
    return image_name[pos+1:] 
 
def image_rotate_clockwise(image_list, degrees, result_path):
    print("image rotation ...")
    os.makedirs(result_path, exist_ok=True)
 
    rotate_code = {90: cv2.ROTATE_90_CLOCKWISE, 180: cv2.ROTATE_180, 270: cv2.ROTATE_90_COUNTERCLOCKWISE}.get(degrees)
    if rotate_code is None:
        raise Exception(f"Unsupported rotat degrees: {degrees}, it only supports: 90, 180, 270. Error Line: {getframeinfo(currentframe()).lineno}")
 
    for name in image_list:
        print(f"\t{name}")
        mat = cv2.imread(name)
        mat = cv2.rotate(mat, rotateCode=rotate_code)
        cv2.imwrite(result_path + "/" + get_image_name(name), mat)
 
def image_resize(image_list, dst_width, dst_height, result_path):
    print("image resize ...")
    os.makedirs(result_path, exist_ok=True)
 
    # 根据目标尺寸与原图大小关系选择插值算法
    mat_sample = cv2.imread(image_list[0])
    h, w, _ = mat_sample.shape
    interpolation = cv2.INTER_AREA if (h > dst_height and w > dst_width) else cv2.INTER_CUBIC
 
    for name in image_list:
        print(f"\t{name}")
        mat = cv2.imread(name)
        mat = cv2.resize(mat, (dst_width, dst_height), interpolation=interpolation)
        cv2.imwrite(result_path + "/" + get_image_name(name), mat)
 
def parse_args():
    parser = argparse.ArgumentParser(description="image generic operations")
    parser.add_argument("--image_src_path", required=True, type=str, help="输入图片目录路径")
    parser.add_argument("--operation", required=True, type=str, choices=["rotate", "resize"], help="指定操作类型")
    parser.add_argument("--image_dst_path", required=True, type=str, help="结果图片保存路径")
    parser.add_argument("--degrees", default=90, type=int, choices=[90, 180, 270], help="顺时针旋转角度")
    parser.add_argument("--width", default=256, type=int, help="缩放后的图片宽度")
    parser.add_argument("--height", default=256, type=int, help="缩放后的图片高度")
    parser.add_argument("--image_suffix", default=".png", type=str, help="处理的图片后缀名")
    return parser.parse_args()
 
if __name__ == "__main__":
    args = parse_args()
    image_list = get_image_list(args.image_src_path, args.image_suffix)
 
    if args.operation == "rotate":
        image_rotate_clockwise(image_list, args.degrees, args.image_dst_path)
    elif args.operation == "resize":
        image_resize(image_list, args.width, args.height, args.image_dst_path)
 
    print("test finish")

第 3 步:执行命令行操作

脚本通过 argparse 接收参数,使用时需在终端中按以下规范传递参数:

  1. 设置目录与文件后缀:使用 --image_src_path 指定包含目标图片的文件夹,--image_suffix 设定需处理的文件扩展名(默认为 .png)。
  2. 选择处理方式:通过 --operation rotate 触发批量旋转,或 --operation resize 触发批量缩放。
  3. 配置变换参数:旋转时传入 --degrees(可选 90、180 或 270);缩放时传入 --width 和 --height(默认均为 256)。注:缩小时优先使用近邻采样以保清晰度,放大时使用双三次插值以保持平滑。
  4. 指定输出位置:使用 --image_dst_path 定义处理后图片的保存目录,脚本会自动创建该路径。
命令行参数配置与执行状态截图
命令行参数配置与执行状态示例

完成判断与注意事项

当终端打印 test finish 且输出目录中出现与输入文件数量一致的新图像时,表示批量处理已成功完成。需注意以下几点:

  • 建议首次运行前备份原始图像目录,虽然本脚本仅生成新文件不覆盖原图,但提前备份可降低误操作风险。
  • 脚本仅支持顺时针方向的 90°、180° 与 270° 旋转,其他角度需修改 rotate_code 映射逻辑或使用 cv2.getRotationMatrix2D 自定义矩阵。
  • 插值算法已内置自适应判断:若原图长宽均大于目标尺寸则采用 INTER_AREA 优化缩小效果,反之采用 INTER_CUBIC 防止放大失真。

总结

以上利用 Python 与 OpenCV 编写的命令行批处理工具,完美替代了繁琐的 C++ 图像转换流程。借助清晰的参数解析与高效的底层绘图接口,开发者可快速应对数据集增强、模型训练前的图像预处理等场景。以上就是 Python基于OpenCV实现图像批量旋转与缩放操作的详细内容,更多关于Python图像处理与自动化脚本的资料请关注本站其它相关文章!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表