import os import csv import random def generate_csv(image_folder, mask_folder, output_csv): # List all image files in the folder img_files = [f for f in os.listdir(image_folder) if f.endswith('.png')] # Ensure reproducibility by setting a random seed random.seed(42) random.shuffle(img_files) # Split the list into 70% training and 30% testing split_index = int(len(img_files) * 0.7) train_files = img_files[:split_index] test_files = img_files[split_index:] # Open the CSV file for writing with open(output_csv, 'w', newline='') as csvfile: fieldnames = ['imgs', 'labels', 'split', 'fold'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() # Write the CSV header # Helper function to write rows to the CSV def write_rows(files, split_type): for img_filename in files: base_filename = os.path.splitext(img_filename)[0] # Get the base filename without extension mask_filename = os.path.join(mask_folder, f"{base_filename}_mask.png") # Construct mask filename img_filepath = os.path.join(image_folder, img_filename) # Full path to the image file # Ensure the mask file exists before writing to CSV if os.path.exists(mask_filename): writer.writerow({ 'imgs': img_filepath, 'labels': mask_filename, 'split': split_type, 'fold': 0 }) else: print(f"Warning: Mask file not found for image {img_filename}, skipping.") # Write training data write_rows(train_files, 'training') # Write testing data write_rows(test_files, 'test') # Example usage image_folder = '/home/abdelrahman.elsayed/ROSE/images' # Folder with image files mask_folder = '/home/abdelrahman.elsayed/ROSE/masks' # Folder with mask files output_csv = '/home/abdelrahman.elsayed/ROSE/data_split.csv' # Output CSV file path generate_csv(image_folder, mask_folder, output_csv)