| import os |
| import csv |
| import re |
|
|
| def get_image_names(folder_path): |
| """ |
| List image files whose numeric IDs fall into specified ranges. |
| """ |
| |
| files = os.listdir(folder_path) |
| files.sort() |
| |
| |
| image_files = [f for f in files if f.lower().endswith('.png')] |
| |
| selected_images = [] |
| |
| pattern = re.compile(r'image(\d+)\.png') |
| |
| for filename in image_files: |
| match = pattern.match(filename) |
| if match: |
| num = int(match.group(1)) |
| |
| if ( |
| (0 <= num <= 271) or |
| (335 <= num <= 365) or |
| (410 <= num <= 440) or |
| (580 <= num <= 619) |
| ): |
| selected_images.append(filename) |
| return selected_images |
|
|
|
|
| def save_image_names_to_csv(folder1_path, folder2_path, csv_filename): |
| """ |
| Save paired image names and class labels into a CSV. |
| """ |
| |
| folder1_image_names = get_image_names(folder1_path) |
| folder2_image_names = get_image_names(folder2_path) |
|
|
| print('The number of images in folder1:', len(folder1_image_names)) |
| print('The number of images in folder2:', len(folder2_image_names)) |
|
|
| |
| if len(folder1_image_names) != len(folder2_image_names): |
| raise ValueError("The folders have different numbers of selected images. Cannot zip them safely.") |
|
|
| |
| class_labels = [1] * len(folder1_image_names) |
|
|
| |
| data = list(zip(folder1_image_names, folder2_image_names, class_labels)) |
|
|
| |
| with open(csv_filename, 'w', newline='') as csv_file: |
| csv_writer = csv.writer(csv_file) |
| |
| |
| csv_writer.writerows(data) |
|
|
|
|
| def csv_to_txt(csv_filename, txt_filename): |
| """ |
| Convert a CSV file into a space-separated TXT file. |
| """ |
| with open(txt_filename, "w") as txt_file: |
| with open(csv_filename, "r") as csv_file: |
| reader = csv.reader(csv_file) |
| for row in reader: |
| txt_file.write(" ".join(row) + "\n") |
|
|
|
|
| if __name__ == "__main__": |
| |
| folder1_path = './mask/' |
| folder2_path = './img/' |
|
|
| |
| csv_filename = 'label6.csv' |
| txt_filename = 'label6.txt' |
|
|
| |
| save_image_names_to_csv(folder1_path, folder2_path, csv_filename) |
|
|
| |
| csv_to_txt(csv_filename, txt_filename) |
|
|
| print("Done: CSV and TXT files created successfully.") |
|
|
|
|