常用数据处理函数

按照路径进行批处理

from PIL import Image, ImageOps

from os import listdir
from os.path import isfile, join, isdir


def default_loader(path):
    return Image.open(path).convert('RGB')

def subdir(root):
  return [join(root, f) for f in listdir(root) if isdir(join(root, f))]

def subfile(root):
  if isdir(root):
    return [join(root, f) for f in listdir(root) if isfile(join(root, f))]
  else:
    return []


dir_root = '/home/songge/dataset/middlebury'
dir_save = '/home/songge/dataset/middlebury_crop3'
dir_sub1 = subdir(dir_root)
imagefiles = subfile(dir_sub1[0])

for left in imagefiles:
  right = dir_root + '/right/' + left.split('/')[-1]
  c = default_loader(left)
  origin_left = default_loader(left)
  origin_right = default_loader(right)
  h, w = origin_left.size
  border1 = (h - 2288, w - 1840, 0, 0)
  border2 = (h - 2288, 0, 0, w - 1840)
  border3 = (0, w - 1840, h - 2288, 0)
  border4 = (0, 0, h - 2288, w - 1840)
  left1 = ImageOps.crop(origin_left, border1).resize((572,460), Image.ANTIALIAS)
  left2 = ImageOps.crop(origin_left, border2).resize((572,460), Image.ANTIALIAS)
  left3 = ImageOps.crop(origin_left, border3).resize((572,460), Image.ANTIALIAS)
  left4 = ImageOps.crop(origin_left, border4).resize((572,460), Image.ANTIALIAS)
  right1 = ImageOps.crop(origin_right, border1).resize((572,460), Image.ANTIALIAS)
  right2 = ImageOps.crop(origin_right, border2).resize((572,460), Image.ANTIALIAS)
  right3 = ImageOps.crop(origin_right, border3).resize((572,460), Image.ANTIALIAS)
  right4 = ImageOps.crop(origin_right, border4).resize((572,460), Image.ANTIALIAS)
  left1.save(dir_save + r"/left/" +  left.split('/')[-1] + '_1',"PNG")
  left2.save(dir_save + r"/left/" +  left.split('/')[-1] + '_2',"PNG")
  left3.save(dir_save + r"/left/" +  left.split('/')[-1] + '_3',"PNG")
  left4.save(dir_save + r"/left/" +  left.split('/')[-1] + '_4',"PNG")
  right1.save(dir_save + r"/right/" + left.split('/')[-1] + '_1', "PNG")
  right2.save(dir_save + r"/right/" + left.split('/')[-1] + '_2', "PNG")
  right3.save(dir_save + r"/right/" + left.split('/')[-1] + '_3', "PNG")
  right4.save(dir_save + r"/right/" + left.split('/')[-1] + '_4', "PNG")

你可能感兴趣的:(常用数据处理函数)