Created
April 9, 2020 05:57
-
-
Save ryul99/8d51fe5f343bceb7176cbc669a8d2456 to your computer and use it in GitHub Desktop.
Padding Image with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import glob | |
import os | |
import tqdm | |
from itertools import islice | |
from multiprocessing import Pool | |
import numpy as np | |
from pathlib import Path | |
path = r'/path/to/image/*.png' | |
wanted_multiple = (4, 4) # Height, Width / Pad image to image size be multiple of wanted_multiple | |
origin_size = (240, 426) # Height, Width | |
output_dir = 'output' | |
pad_mode = True # True: padding / False: remove padding with origin_size | |
def pad_image(_file): | |
img = cv2.imread(_file, cv2.IMREAD_UNCHANGED) | |
if pad_mode: | |
pad = ((0, (-1 * img.shape[0]) % wanted_multiple[0]), (0, (-1 * img.shape[1]) % wanted_multiple[1]), (0, 0)) | |
output_image = np.pad(img, pad, 'constant') | |
else: | |
output_image = img[:origin_size[0], :origin_size[1], :] | |
save_path = os.path.join(os.path.dirname(_file), output_dir, os.path.basename(_file)) | |
Path(os.path.dirname(save_path)).mkdir(parents=True, exist_ok=True) | |
cv2.imwrite(save_path, output_image) | |
if __name__ == '__main__': | |
num_process = 16 | |
files = glob.glob(path, recursive=True) | |
# iter_files = iter(files) | |
# files = [list(islice(iter_files, e)) for e in [len(files) // num_process] * (num_process + 1)] | |
# os.mkdir(os.path.join(os.path.dirname(path), output_dir)) | |
with Pool(processes=num_process) as p: | |
r = list(tqdm.tqdm(p.imap(pad_image, files), total=len(files))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment