python图片切割得到的子图片

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

from PIL import Image
import os
import shutil

def cut(vx,vy):
    #存放原始图片地址
    for file in os.listdir(data_base_dir): #file为current_dir当前目录下图片名
        im = Image.open(data_base_dir+'/'+file)
        width=im.size[0]
        height=im.size[1]
        if file.endswith(".jpg"): #如果file以jpg结尾
            write_name = file
        #偏移量
        dx = 30
        dy = 30
        n = 1
        #左上角切割
        x1 = 0
        y1 = 0
        x2 = vx
        y2 = vy
        #纵向
        tarDir = "/mnt/NIvsCG/temp/train/"+file+'/'
        os.makedirs(tarDir)
        while x2 <= width:
            #横向切
            while y2 <= height:
                name = write_name +'_'+ str(n) + ".jpg"
                #print n,x1,y1,x2,y2
                im2 = im.crop((y1, x1, y2, x2))
                im2.save(name)
                shutil.move('./'+name, tarDir+name)
                y1 = y1 + dy
                y2 = y1 + vy
                n = n + 1
            x1 = x1 + dx
            x2 = x1 + vx
            y1 = 0
            y2 = vy
        print("图片切割成功,切割得到的子图片数为"+':'+str(n-1))
if __name__=="__main__":   
    data_base_dir = "/mnt/NIvsCG/datasets/train"
    #切割图片的面积 vx,vy
    #大
    res = cut(240,240)
    #中
    #res = cut(id,120,120)
    #小
    #res = cut(id,80,80)
    print(res)

你可能感兴趣的:(python图片切割得到的子图片)