import subprocess import os from pathlib import Path from PIL import Image import numpy as np input_folder = Path("./original_images/") output_folder = Path("./data/train/") output_folder.mkdir(parents=True, exist_ok=True) folders = os.listdir(input_folder) for folder in folders: folder_path = input_folder.joinpath(folder) images = os.listdir(folder_path) for image in images: output = output_folder.joinpath(f'{folder}') output.mkdir(parents=True, exist_ok=True) output = output.joinpath(f'{folder}_{image}') output = str(output.absolute()) input = folder_path.joinpath(image) input = str(input.absolute()) if os.path.isfile(input) == False or '.json' in image: continue image_input = Image.open(input) background_color = (23, 35, 35, 255) new_color = (0, 0, 0, 255) data = np.array(image_input) data[(data == background_color).all(axis=-1)] = new_color image_input = Image.fromarray(data, 'RGBA') new_image = Image.new('RGB', image_input.size) new_image.paste(image_input, mask=image_input.split()[3]) bbox = new_image.getbbox() new_image = new_image.crop(bbox) new_image.save(output)