一、说在前面
需求:有一张长为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(c