python圖片處理裁剪大小、旋轉、鏡像

 

# -*- 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)
    
    
    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章