kanishka526's picture
Upload 3334 files
3a3548c verified
Raw
History Blame Contribute Delete
2.74 kB
import os
import csv
import re
def get_image_names(folder_path):
"""
List image files whose numeric IDs fall into specified ranges.
"""
# List all files and sort
files = os.listdir(folder_path)
files.sort()
# Keep only .png images
image_files = [f for f in files if f.lower().endswith('.png')]
selected_images = []
# Regex to extract numeric ID
pattern = re.compile(r'image(\d+)\.png')
for filename in image_files:
match = pattern.match(filename)
if match:
num = int(match.group(1))
# Define the numeric ranges to include
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.
"""
# Get image names for both folders
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))
# Ensure same number of images
if len(folder1_image_names) != len(folder2_image_names):
raise ValueError("The folders have different numbers of selected images. Cannot zip them safely.")
# Create labels: class 1 for all rows
class_labels = [1] * len(folder1_image_names)
# Combine into rows
data = list(zip(folder1_image_names, folder2_image_names, class_labels))
# Write to CSV
with open(csv_filename, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file)
# Optional header
#csv_writer.writerow(['Folder1_Image', 'Folder2_Image', 'Class'])
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__":
# Paths to your folders
folder1_path = './mask/'
folder2_path = './img/'
# Output files
csv_filename = 'label6.csv'
txt_filename = 'label6.txt'
# Generate CSV
save_image_names_to_csv(folder1_path, folder2_path, csv_filename)
# Convert CSV to TXT
csv_to_txt(csv_filename, txt_filename)
print("Done: CSV and TXT files created successfully.")