File size: 2,202 Bytes
818b5fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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/DIAS/images'  # Folder with image files
mask_folder = '/home/abdelrahman.elsayed/DIAS/masks'    # Folder with mask files
output_csv = '/home/abdelrahman.elsayed/DIAS/data_split.csv'  # Output CSV file path

generate_csv(image_folder, mask_folder, output_csv)