Created
August 19, 2017 10:25
-
-
Save dsalaj/aa6f6c1ad0e046c8aeb4eb4c4aa55065 to your computer and use it in GitHub Desktop.
Resize and pad images
This file contains 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 os | |
import cv2 | |
dir_files = os.listdir('raw_data') | |
extensions = [filename[-4:] for filename in dir_files] | |
for ext in extensions: | |
assert ext == '.jpg' | |
max_width = 0 | |
max_heigth = 0 | |
for filename in dir_files: | |
img = cv2.imread('raw_data/' + filename, cv2.IMREAD_COLOR) | |
height, width = img.shape[:2] | |
if height > max_heigth: | |
max_heigth = height | |
if width > max_width: | |
max_width = width | |
for filename in dir_files: | |
img = cv2.imread('raw_data/' + filename, cv2.IMREAD_COLOR) | |
height, width = img.shape[:2] | |
h_diff = max_heigth - height | |
w_diff = max_width - width | |
t, b, l, r = (0, 0, 0, 0) | |
if h_diff > 0: | |
if h_diff % 2 == 0: | |
t = int(h_diff / 2) | |
b = int(h_diff / 2) | |
elif h_diff % 2 == 1: | |
t = int(h_diff / 2) | |
b = int(h_diff / 2) + 1 | |
else: | |
raise Exception("impossible") | |
if w_diff > 0: | |
if w_diff % 2 == 0: | |
l = int(w_diff / 2) | |
r = int(w_diff / 2) | |
elif w_diff % 2 == 1: | |
l = int(w_diff / 2) | |
r = int(w_diff / 2) + 1 | |
else: | |
raise Exception("impossible") | |
pad_img = cv2.copyMakeBorder(img, t, b, l, r, borderType=cv2.BORDER_REFLECT_101) | |
cv2.imwrite('output/'+str(filename), pad_img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment