Fork me on GitHub

至简

Be simple

为了寻找你,我把自己搬进鸟的眼睛,经常盯着路过的风。


图像划片


代码

纯记录,以备日后查看。

# -*- coding: utf-8 -*-

import imghdr
import os
import shutil
from PIL import Image

def dir_del(path:str):
    files = os.listdir(path)
    #os.chdir(path)
    for file in files:
        cur_path = os.path.join(path, file)
        if os.path.isdir(cur_path):
            dir_del(cur_path)
        else:
            os.remove(cur_path)
    #os.chdir("..")
    shutil.rmtree(path)

def mk_dir(path:str):
    # 去除首位空格
    path=path.strip()
    # 去除尾部 \ 符号
    path=path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists=os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path) 
        return True
    else:
        # 如果目录存在则删除
        #os.remove(path)#拒绝访问
        dir_del(path)
        os.makedirs(path)
        return False

def splitImg(imgPath:str, genPath:str, w:int, h:int):
    mk_dir(genPath)
    file_list = os.listdir(imgPath)
    for file_tmp in file_list:
        #利用os.path.join()方法取得路径全名,并存入cur_path变量,
        #否则每次只能遍历一层目录
        cur_path = os.path.join(imgPath, file_tmp)
        #判断是否是文件夹
        if os.path.isdir(cur_path):
            #是文件夹
            pass
        else:
            img_type_list = {'jpg','bmp','png','jpeg','rgb','tif'}
            #print(type(img_type_list)) #set
            if imghdr.what(cur_path) in img_type_list:
                img = Image.open(cur_path)
                print(img.size)
                c, r = img.size
                horNum = int(c / w + 0.5)
                verNum = int(r / h + 0.5)
                imgW = int(c / horNum + 0.5)
                imgH = int(r / verNum + 0.5)
                for colN in range(horNum):
                    for rowN in range(verNum):
                        #left up right down
                        left = colN * imgW
                        up = rowN * imgH
                        if(horNum - 1 == colN):
                            right = c
                        else:
                            right = (colN + 1) * imgW
                        if(verNum - 1 == rowN):
                            down = r
                        else:
                            down = (rowN + 1) * imgH
                        
                        cropped = img.crop((left, up, right, down))
                        imgName = cur_path.split("\\")[-1].split(".")[0]
                        imgName += "_" + str(rowN) + "_" + str(colN) + ".jpg"
                        cropped.save(genPath + "\\" + imgName)
    
def main():
    imgPath = "C:\\Users\\dongyuncheng6\\Desktop\\大玻璃"
    genPath = "C:\\Users\\dongyuncheng6\\Desktop\\大玻璃\\crop"
    splitW = 800
    splitH = 800
    splitImg(imgPath, genPath, splitW, splitH)
    print("Done!")

if __name__ == '__main__':
    main()