자체 데이터셋을 준비할 때, 특히 VOC 형식의 레이블과 이미지를 매칭해야 하는 경우, 학습 및 검증 세트를 나누기 위한 텍스트 리스트가 필요합니다. 이 스크립트는 지정된 폴더(하위 폴더 포함)에서 지원되는 이미지 확장자(.jpg, .png 등)를 가진 파일들의 이름을 추출하고, 정렬된 상태로 출력 파일에 저장합니다.
기본 기능
- 지정된 디렉터리 내 모든 하위 폴더 탐색 가능
- 확장자 필터링 (사용자 정의 가능)
- 전체 경로 또는 단순 파일명만 저장 옵션 제공
- UTF-8 인코딩으로 안정적인 텍스트 파일 생성
import os
# ---------------------------- 설정 ----------------------------
image_directory = r"C:\data\images" # 이미지 폴더 경로
output_file = r"C:\data\image_names.txt" # 출력 텍스트 파일 경로
scan_subdirs = True # 하위 폴더 포함 여부
include_full_path = False # 전체 경로 포함 여부
# 지원하는 이미지 확장자
supported_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff', '.webp']
# ---------------------------- 메인 로직 ----------------------------
def extract_image_names():
if not os.path.exists(image_directory):
print(f"오류: 폴더가 존재하지 않습니다 → {image_directory}")
return
image_list = []
if scan_subdirs:
for current_root, _, files in os.walk(image_directory):
for filename in files:
if any(filename.lower().endswith(ext) for ext in supported_extensions):
if include_full_path:
image_list.append(os.path.join(current_root, filename))
else:
relative_path = os.path.relpath(current_root, image_directory)
image_list.append(os.path.join(relative_path, filename))
else:
for filename in os.listdir(image_directory):
if any(filename.lower().endswith(ext) for ext in supported_extensions):
if include_full_path:
image_list.append(os.path.join(image_directory, filename))
else:
image_list.append(filename)
if not image_list:
print(f"경고: {image_directory} 에 이미지 파일이 없습니다.")
return
with open(output_file, 'w', encoding='utf-8') as f:
for item in image_list:
f.write(f"{item}\n")
print(f"✅ 성공적으로 리스트 생성됨 ({len(image_list)}개)")
print(f"→ 결과 저장 위치: {output_file}")
# 예시 출력
print("\n첫 10개 항목:")
for path in image_list[:10]:
print(f" - {path}")
if __name__ == "__main__":
extract_image_names()
파일명만 추출하는 버전 (확장자 제거)
경로 정보 없이 순수한 파일명만 필요하다면 아래 코드를 사용하세요. 중복 제거 및 정렬도 자동 처리됩니다.
import os
# ---------------------------- 설정 ----------------------------
img_folder = r"C:\data\crop_images"
output_txt = r"C:\data\file_ids.txt"
recursive_scan = False
# 이미지 확장자 목록
ext_list = ['.jpg', '.png', '.bmp', '.tif']
# ---------------------------- 메인 함수 ----------------------------
def generate_clean_names():
result = set()
for root, _, files in os.walk(img_folder):
if not recursive_scan and root != img_folder:
continue
for file in files:
if any(file.lower().endswith(ext) for ext in ext_list):
base_name = os.path.splitext(file)[0]
result.add(base_name)
unique_sorted = sorted(result)
if not unique_sorted:
print(f"⚠️ 해당 폴더에 이미지 파일이 없습니다: {img_folder}")
return
with open(output_txt, 'w', encoding='utf-8') as f:
for name in unique_sorted:
f.write(f"{name}\n")
print(f"✅ 파일명 리스트 생성 완료 ({len(unique_sorted)}개)")
print(f"→ 저장 위치: {output_txt}")
print(f"→ 예시: {unique_sorted[:5]}...")
if __name__ == "__main__":
generate_clean_names()
사용자는 각각의 image_directory, output_file 경로와 필요한 옵션을 수정하여 쉽게 적용할 수 있습니다. 다양한 데이터셋 준비 작업에 유용하게 활용될 수 있습니다.