CustomConcept101-256x256 / split_tiled_imgs.py
keiphone's picture
Update split_tiled_imgs.py
9863bad
from PIL import Image
import os
from tqdm import tqdm
def split_and_save_tiled_image(image_path,global_idx,class_name,save_dir):
# Open the image
img = Image.open(image_path)
# Get the dimensions of the tiled image
width, height = img.size
assert height == 256
assert width % 256 == 0
tile_width = 256
num_tiles = width // tile_width
# Iterate through each tile
for i in range(num_tiles):
# Calculate the starting and ending x-coordinates for the tile
start_x = i * tile_width
end_x = start_x + tile_width
# Crop the tile from the original image
tile = img.crop((start_x, 0, end_x, height))
# Save the tile with its index as filename
filename = f"{global_idx}.{i}.{num_tiles}.{class_name}.jpg" # # id.n.N.ClassName.jpg
tile.save(os.path.join(save_dir,filename)) # You can choose the desired image format
global_idx += 1
return global_idx
if __name__ == "__main__":
# id.n.N.ClassName.jpg
load_dir = "./tiled_imgs_per_concept"
save_dir = "./customconcept256x256"
filenames = sorted(os.listdir(load_dir))
global_idx = 0
for filename in tqdm(filenames):
img_path = os.path.join(load_dir,filename)
class_name = filename.split('.')[0].split('_')[0] # filename can be "jacket1" or "person_1" or "lighthouse"
class_name = [c for c in class_name if c not in "0123456789"]
class_name = "".join(class_name)
# print(class_name)
global_idx = split_and_save_tiled_image(img_path,global_idx,class_name,save_dir)