Skip to content

Instantly share code, notes, and snippets.

@nihadguluzade
Created March 30, 2020 12:09
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 nihadguluzade/6ea474d279d9affc9eb769b93ea8b2ae to your computer and use it in GitHub Desktop.
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.
# 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