python实现将文件夹内的每张图片批量分割成多张实现将文件夹内的每张图片批量分割成多张
主要为大家详细介绍了python实现将文件夹内的每张图片批量分割成多张,具有一定的参考价值,感兴趣的小
伙伴们可以参考一下
一、说在前面一、说在前面
需求:有一张长为960,宽为96的图片,需要将其分割成10张96*96的图片并存放在另外一个文件夹下,通过手工分割耗
时且不规范,选择python写一个简单的程序完成。
二、源码二、源码
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 18:19:09 2018
@author: Administrator
"""
import os
from PIL import Image
# 切割图片
def splitimage(src, rownum, colnum, dstpath):
img = Image.open(src)
w, h = img.size
if rownum <= h and colnum <= w:
print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
print('图片切割')
s = os.path.split(src)
if dstpath == '':
dstpath = s[0]
fn = s[1].split('.')
basename = fn[0]
ext = fn[-1]
num = 0
rowheight = h // rownum
colwidth = w // colnum
for r in range(rownum):
for c in range(colnum):
box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), ext)
num = num + 1
print('共生成 %s 张小图片。' % num)
else:
print('error')
# 创建文件夹
def mkdir(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\")
# 判断路径是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
# 判断结果
if not isExists:
os.makedirs(path)
print (path+' 创建成功')
return True
else:
print (path + ' 目录已存在')
return False
folder = r'C:/Users/Administrator/Desktop/testresults' # 存放图片的文件夹
path = os.listdir(folder)
# print(path)
for each_bmp in path: # 批量操作
first_name, second_name = os.path.splitext(each_bmp)
each_bmp = os.path.join(folder, each_bmp)
评论3
最新资源