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)
    
    
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值