Skip to content

Instantly share code, notes, and snippets.

@ryul99
Created April 9, 2020 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryul99/8d51fe5f343bceb7176cbc669a8d2456 to your computer and use it in GitHub Desktop.
Save ryul99/8d51fe5f343bceb7176cbc669a8d2456 to your computer and use it in GitHub Desktop.
Padding Image with Python
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