Path: blob/master/Face-Recognition-with-ArcFace/align/face_resize.py
3142 views
import os1import cv22from tqdm import tqdm345def mkdir(path):6if not os.path.exists(path):7os.mkdir(path)8910def process_image(img):1112size = img.shape13h, w = size[0], size[1]14scale = max(w, h) / float(min_side)15new_w, new_h = int(w / scale), int(h / scale)16resize_img = cv2.resize(img, (new_w, new_h))17if new_w % 2 != 0 and new_h % 2 == 0:18top, bottom, left, right = (min_side - new_h) / 2, (min_side - new_h) / 2, (min_side - new_w) / 2 + 1, (19min_side - new_w) / 220elif new_h % 2 != 0 and new_w % 2 == 0:21top, bottom, left, right = (min_side - new_h) / 2 + 1, (min_side - new_h) / 2, (min_side - new_w) / 2, (22min_side - new_w) / 223elif new_h % 2 == 0 and new_w % 2 == 0:24top, bottom, left, right = (min_side - new_h) / 2, (min_side - new_h) / 2, (min_side - new_w) / 2, (25min_side - new_w) / 226else:27top, bottom, left, right = (min_side - new_h) / 2 + 1, (min_side - new_h) / 2, (min_side - new_w) / 2 + 1, (28min_side - new_w) / 229pad_img = cv2.copyMakeBorder(resize_img, top, bottom, left, right, cv2.BORDER_CONSTANT,30value=[0, 0, 0])3132return pad_img333435def main(source_root):3637dest_root = "/media/pc/6T/jasonjzhao/data/MS-Celeb-1M_Resized"38mkdir(dest_root)39cwd = os.getcwd() # delete '.DS_Store' existed in the source_root40os.chdir(source_root)41os.system("find . -name '*.DS_Store' -type f -delete")42os.chdir(cwd)4344if not os.path.isdir(dest_root):45os.mkdir(dest_root)4647for subfolder in tqdm(os.listdir(source_root)):48if not os.path.isdir(os.path.join(dest_root, subfolder)):49os.mkdir(os.path.join(dest_root, subfolder))50for image_name in os.listdir(os.path.join(source_root, subfolder)):51print("Processing\t{}".format(os.path.join(source_root, subfolder, image_name)))52img = cv2.imread(os.path.join(source_root, subfolder, image_name))53if type(img) == type(None):54print("damaged image %s, del it" % (img))55os.remove(img)56continue57size = img.shape58h, w = size[0], size[1]59if max(w, h) > 512:60img_pad = process_image(img)61else:62img_pad = img63cv2.imwrite(os.path.join(dest_root, subfolder, image_name.split('.')[0] + '.jpg'), img_pad)646566if __name__ == "__main__":67min_side = 51268main(source_root = "/media/pc/6T/jasonjzhao/data/MS-Celeb-1M/database/base")6970