# -*- coding: utf-8 -*-
import os
from PIL import Image
# Cut the 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('Picture cutting')
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('generates %s of small images. ' % (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)
# Upside down
# im.transpose(Image.FLIP_TOP_BOTTOM).save(os.path.join(dstpath, file_name+ '_updown' + file_type))
out1 = im.transpose(Image.FLIP_TOP_BOTTOM)
# Reverse left/right
out2 = im.transpose(Image.FLIP_LEFT_RIGHT)
# Rotate 90
out3 = im.transpose(Image.ROTATE_90)
# Rotate 180
out4 = im.transpose(Image.ROTATE_180)
# perform rotation 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' # Folder to store pictures in
path = os.listdir(folder)
for each_tif in path: # Batch operation
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)
Copy the code