반응형
from PIL import Image
import matplotlib.pyplot as plt
from pathlib import Path
def resize_and_crop_image(img, resize_dims, crop):
img = img.resize(resize_dims, resample=Image.BILINEAR)
img = img.crop(crop)
return img
# current working directory
cwd = Path.cwd()
# add path
cfg_path = cwd.parent / 'config/CVTpro/data.json'
cfg = read_json(path=str(cfg_path))
# Image resize and crop
ori_dims = (cfg['original_image']['w'], cfg['original_image']['h'])
resize_dims = (cfg['image']['w'], cfg['image']['h'] + cfg['image']['top_crop'])
crop = (0, cfg['image']['top_crop'], resize_dims[0], resize_dims[1])
img_aug_params = {'scale_width': resize_dims[0] / ori_dims[0],
'scale_height': resize_dims[1] / ori_dims[1],
'resize_dims': resize_dims,
'crop': crop}
# initialize path
root = Path('/home/dooseop/DATASET/nuscenes/samples')
# find all the files or directories
directories = list(root.glob('*'))
# create a new directory
new_path = root.parent / 'samples_new'
if (new_path.exists() is not True):
new_path.mkdir(parents=True, exist_ok=True)
# 'nuscenes/samples/FOLDER_NAME
for _, dir in enumerate(directories):
# splits into
FOLDER_NAME = dir.parts[-1]
if (FOLDER_NAME == 'LIDAR_TOP'):
continue
# check files in current dir
files = list(dir.glob('*'))
# create target folder
new_dir = new_path / FOLDER_NAME
if (new_dir.exists() is not True):
new_dir.mkdir(parents=True, exist_ok=True)
# copy from dir to new_dir
for _, file in enumerate(tqdm(files, desc=f'{FOLDER_NAME}')):
# file name, suffix, stem
file_name = file.name
file_suffix = file.suffix
file_stem = file.stem
# Surround Image
img = Image.open(file)
img = resize_and_crop_image(img, resize_dims=img_aug_params['resize_dims'],
crop=img_aug_params['crop'])
new_file_path = new_dir / file_stem
# add suffix
img.save(new_file_path.with_suffix('.png'))
'Python' 카테고리의 다른 글
Resize and crop images in a specific directory (0) | 2023.04.25 |
---|---|
Fast JPEG image loading by TurboJPEG (0) | 2023.04.25 |
Python에서 Warning 문구 제거하기 (0) | 2023.04.20 |
Pandas 명령어 모음 (0) | 2023.04.19 |
python에서 evaluate과 tqdm 같이 사용하기 (0) | 2023.04.12 |