Last active
May 23, 2020 09:34
-
-
Save tommyjtl/4c636627a56a40534b66f61c840cef8e to your computer and use it in GitHub Desktop.
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
''' | |
requirements: | |
scikit-image==0.16.2 | |
tqdm==4.45.0 | |
''' | |
from PIL import Image, ImageFile | |
ImageFile.LOAD_TRUNCATED_IMAGES = True | |
import glob, random, os, time, re, time | |
from tqdm import tqdm | |
to_be_convert_path = input("Please enter the name the target converting directory: \n") | |
os.chdir(to_be_convert_path) | |
print(os.getcwd()) | |
parent_path = os.path.abspath(os.getcwd()) | |
all_subdirectories = next(os.walk('.'))[1] | |
newsize = (448, 448) | |
left, top, right, bottom = 0,0,0,0 | |
def process_image(filename, index, convertname): | |
try: | |
im = Image.open(filename) | |
# print(im.size) | |
w, h = im.size | |
if w > h: | |
converted_length = h | |
left = (w - h) / 2 | |
top = 0 | |
right = (w - h) / 2 + h | |
bottom = h | |
elif w < h: | |
converted_length = w | |
left = 0 | |
top = (h - w) / 2 | |
right = w | |
bottom = (h - w) / 2 + w | |
elif w == h: | |
converted_length = w | |
left = 0 | |
top = 0 | |
right = w | |
bottom = w | |
im1 = im.crop((left, top, right, bottom)) | |
im1 = im1.resize(newsize) | |
im1 = im1.save(convertname + "_converted_" + str(index) + ".jpg") | |
# print("Saving " + convertname + "_converted_" + str(index) + ".jpg") | |
except BaseException as e: | |
print(str(e)) | |
pass | |
if __name__ == '__main__': | |
print("Entering the project path:") | |
print(all_subdirectories) | |
file1 = open(to_be_convert_path + ".names", "w") | |
for i in all_subdirectories: | |
file1.write(i + "\n") | |
file1.close() | |
''' | |
for i in all_subdirectories: | |
if re.search("[\\u4e00-\\u9FFF]", i): | |
print("yes") | |
''' | |
count = 0 | |
for directory in all_subdirectories: | |
os.chdir(directory) | |
for names_file in glob.glob("*.jpg"): | |
count = count + 1 | |
os.chdir(parent_path) | |
print(str(count) +" files in total.\n") | |
with tqdm(total=count) as pbar: | |
for directory in all_subdirectories: | |
os.chdir(directory) | |
# print(directory) | |
# print(os.path.abspath(os.getcwd())) | |
index = 0 | |
for names_file in glob.glob("*.jpg"): | |
index = index + 1 | |
pbar.update(1) | |
process_image(names_file, index, directory) | |
os.remove(names_file) | |
# print(names_file) | |
os.chdir(parent_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment