Created
March 30, 2020 12:09
-
-
Save nihadguluzade/6ea474d279d9affc9eb769b93ea8b2ae to your computer and use it in GitHub Desktop.
Resize the images in data set and write their names to the text file.
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
# Creates txt file containing file names from the data set located in DATASET_DIR and | |
# crops the images according to IMAGE_WIDTH and IMAGE_HEIGHT | |
import os | |
import numpy | |
import shutil | |
from PIL import Image | |
# Resize images to 128x128, channel 3 because colored | |
IMAGE_WIDTH, IMAGE_HEIGHT = 128, 128 | |
IMAGE_CHANNELS = 3 | |
DRIVE_DIR = '/content/drive/My Drive/Colab Notebooks/datasets/sperm_datasets/SpermDataset/' # Google Drive path | |
DATASET_DIR = DRIVE_DIR + 'My_dataset/' # dataset path | |
DATA_TXT_NAME = 'data.txt' # dataset txt name | |
CROPPED_FOLDER = 'cropped/' # where cropped images will be stored | |
TXT_FILE = open(DATA_TXT_NAME, "w") | |
TXT_PATH = DRIVE_DIR + DATA_TXT_NAME | |
cropped_full_path = os.path.join(DRIVE_DIR, CROPPED_FOLDER) | |
save_dir = cropped_full_path | |
if not os.path.exists(cropped_full_path): | |
os.mkdir(cropped_full_path) | |
print(f"{CROPPED_FOLDER} created.") | |
else: | |
print(f"{CROPPED_FOLDER} exists.") | |
# write data names to txt file | |
for filename in os.listdir(DATASET_DIR): | |
filename = filename + '.jpg' | |
print(filename) | |
TXT_FILE.write(filename) | |
TXT_FILE.write("\n") | |
TXT_FILE.close() | |
shutil.move(DATA_TXT_NAME, TXT_PATH) # move file to drive | |
# Iterating over the images inside the directory and resizing them using | |
# Pillow's resize method | |
print('resizing and saving...') | |
for filename in os.listdir(DATASET_DIR): | |
path = os.path.join(DATASET_DIR, filename) | |
if not (os.path.isdir(path)): | |
image = Image.open(path).resize((IMAGE_WIDTH, IMAGE_HEIGHT), Image.ANTIALIAS) | |
new_file_name = os.path.join(save_dir, filename) | |
new_file_name = new_file_name + '.jpg' | |
print(new_file_name) | |
image.save(new_file_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment