# -*- coding: utf-8 -*-
import os
from PIL import Image
# 切割图片
def splitimage(src, dstpath):
img = Image.open(src)
w, h = img.size
print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
print('图片切割')
num = 1
row = 4
col = 3
rowheight = h // row
colwidth = w // col
for r in range(row):
for c in range(col):
box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
img.crop(box).save(os.path.join(dstpath, str(num)+'.tif'))
num = num + 1
print('共生成 %s 张小图片。' % (num-1))
newpath = os.listdir(dstpath)
for each_png in newpath:
print(each_png)
file_name, file_type = os.path.splitext(each_png)
currentPath = os.path.join(dstpath, each_png)
print('the fulll name of the file is :' + currentPath)
im = Image.open(currentPath)
#进行上下颠倒
# im.transpose(Image.FLIP_TOP_BOTTOM).save(os.path.join(dstpath, file_name+ '_updown' + file_type))
out1 = im.transpose(Image.FLIP_TOP_BOTTOM)
#进行左右颠倒
out2 = im.transpose(Image.FLIP_LEFT_RIGHT)
# 进行旋转90
out3 = im.transpose(Image.ROTATE_90)
# 进行旋转180
out4 = im.transpose(Image.ROTATE_180)
# 进行旋转270
out5 = im.transpose(Image.ROTATE_270)
newname1 = os.path.join(dstpath, file_name+ '_updown' + file_type)
out1.save(newname1)
newname2 = os.path.join(dstpath, file_name+ '_LR' + file_type)
out2.save(newname2)
newname3 = os.path.join(dstpath, file_name+ '_Rotate90' + file_type)
out3.save(newname3)
newname4 = os.path.join(dstpath, file_name+ '_Rotate180' + file_type)
out4.save(newname4)
newname5 = os.path.join(dstpath, file_name+ '_Rotate270' + file_type)
out5.save(newname5)
folder = r'./train' # 存放图片的文件夹
path = os.listdir(folder)
for each_tif in path: # 批量操作
first_name, second_name = os.path.splitext(each_tif)
each_tif = os.path.join(folder, each_tif)
print(each_tif)
print(first_name)
mkpath = r'./test'
splitimage(each_tif, mkpath)