python:将图片切割成4份扩充数据集

有时候图像过大,或者是图像的数量不够,可以把原始图像切割成四份扩充数据集。

import cv2
import os

if __name__ == "__main__":
    #图像文件原始路径
    path = r"C:\study_he\exp_result\high\train\high_image"  
    listdir = os.listdir(path)
    # 新建split文件夹用于保存
    newdir = os.path.join(path, 'split')
    if (os.path.exists(newdir) == False):
        os.mkdir(newdir)
    for i in listdir:
        if i.split('.')[1] == "png" or i.split('.')[1] == "JPG" or i.split('.')[1] == "jpg" :
            filepath = os.path.join(path, i)
            filename = i.split('.')[0]
            leftpath1 = os.path.join(newdir, filename) + "_left1.png"
            leftpath2 = os.path.join(newdir, filename) + "_left2.png"
            rightpath1 = os.path.join(newdir, filename) + "_right1.png"
            rightpath2 = os.path.join(newdir, filename) + "_right2.png"
            img = cv2.imread(filepath)
            [h, w] = img.shape[:2]
            print(filepath, (h, w))
            l1img = img[:int(h / 2), :int(w / 2), :]
            l2img=img[int(h /2+1):, :int(w / 2), :]
            r1img = img[:int(h / 2), int(w / 2 + 1):, :]
            r2img = img[int(h /2+1):, int(w / 2 + 1):, :]
            cv2.imwrite(leftpath1, l1img)
            cv2.imwrite(leftpath2, l2img)
            cv2.imwrite(rightpath1, r1img)
            cv2.imwrite(rightpath2, r2img)

你可能感兴趣的:(python:将图片切割成4份扩充数据集)