Python实现任意尺寸图片均匀切割的代码示例

Finn
Finn
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍使用Python对任意尺寸图片进行均匀切割的方法。通过遍历图片目录,利用PIL库读取图像尺寸,设定固定裁剪宽度(如256像素),以滑动窗口方式将大图分割为多个小块并保存。代码适用于Windows环境,支持自定义输入输出路径,常用于机器学习数据预处理场景。

该代码示例的运行环境为Windows系统。

使用时,请将代码中的源图片路径和目标保存路径替换为你本地的实际路径即可。

import numpy as np
import matplotlib
import os
 
def img_seg(dir):
  files = os.listdir(dir)
  for file in files:
    a, b = os.path.splitext(file)
    img = Image.open(os.path.join(dir + "\\" + file))
    hight, width = img.size
    w = 256
    id = 1
    i = 0
    while (i + w <= hight):
      j = 0
      while (j + w <= width):
        new_img = img.crop((i, j, i + w, j + w))
        #rename = "D:\\labelme\\images\\"
        rename = "D:\\labelme\\annotations\\"
        new_img.save(rename + a + "_" + str(id) + b)
        id += 1
        j += w
      i = i + w
 
 
if __name__ == '__main__':
  #path = "D:\\labelme\\data\\images\\train"
  path = "D:\\labelme\\data\\dataset_png"
  img_seg(path)

以上便是关于使用Python实现任意大小图片均匀切割的完整示例分享,希望能为你的项目提供参考,也欢迎继续支持本站获取更多内容。

相关标签:

本站声明

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

Python 相关产品和应用

全部下载

专题列表