File size: 3,548 Bytes
2251a28 |
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
"""
데이터셋 분할 - Windows 대소문자 문제 해결
각 파일에 고유한 번호를 부여하여 충돌 방지
"""
import os
import shutil
from pathlib import Path
import random
random.seed(42)
# 1. 모든 이미지-라벨 쌍 찾기
print("Finding all image-label pairs...")
pairs = []
for batch_num in range(1, 18):
batch_name = f'batch_{batch_num}'
img_dir = Path(f'data/{batch_name}')
lbl_dir = Path(f'labels/{batch_name}')
if not img_dir.exists():
continue
# 라벨 파일 기준
for lbl_file in lbl_dir.glob('*.txt'):
if lbl_file.name == 'classes.txt':
continue
stem = lbl_file.stem
# 이미지 파일 찾기
img_file_jpg = img_dir / f'{stem}.jpg'
img_file_JPG = img_dir / f'{stem}.JPG'
img_file = None
if img_file_jpg.exists():
img_file = img_file_jpg
elif img_file_JPG.exists():
img_file = img_file_JPG
if img_file and img_file.exists():
pairs.append({
'image': str(img_file),
'label': str(lbl_file),
'stem': stem,
'ext': img_file.suffix
})
print(f"Found {len(pairs)} valid pairs")
# 2. 분할
random.shuffle(pairs)
total = len(pairs)
train_size = int(total * 0.8)
val_size = int(total * 0.1)
train_pairs = pairs[:train_size]
val_pairs = pairs[train_size:train_size + val_size]
test_pairs = pairs[train_size + val_size:]
print(f"Train: {len(train_pairs)}, Val: {len(val_pairs)}, Test: {len(test_pairs)}")
# 3. 디렉토리 생성
os.makedirs('dataset/images/train', exist_ok=True)
os.makedirs('dataset/images/val', exist_ok=True)
os.makedirs('dataset/images/test', exist_ok=True)
os.makedirs('dataset/labels/train', exist_ok=True)
os.makedirs('dataset/labels/val', exist_ok=True)
os.makedirs('dataset/labels/test', exist_ok=True)
# 4. 파일 복사 - 고유한 번호 부여
def copy_files(pairs, split):
print(f"\nCopying {split}...")
for idx, pair in enumerate(pairs):
if (idx + 1) % 200 == 0:
print(f" {idx+1}/{len(pairs)}...")
# 고유한 파일명 생성 (idx를 이용)
# {idx:05d}_{stem}{ext} 형식
img_dst = f"dataset/images/{split}/{idx:05d}_{pair['stem']}{pair['ext']}"
lbl_dst = f"dataset/labels/{split}/{idx:05d}_{pair['stem']}.txt"
shutil.copy2(pair['image'], img_dst)
shutil.copy2(pair['label'], lbl_dst)
print(f" Done! {len(pairs)} files copied")
# 검증
actual_count = len(os.listdir(f"dataset/images/{split}"))
print(f" Verified: {actual_count} files in directory")
if actual_count != len(pairs):
print(f" WARNING: Expected {len(pairs)} but found {actual_count}")
copy_files(train_pairs, 'train')
copy_files(val_pairs, 'val')
copy_files(test_pairs, 'test')
# 5. data.yaml
with open('dataset/data.yaml', 'w') as f:
f.write(f"""# TACO Waste Classification Dataset
path: {Path('dataset').absolute()}
train: images/train
val: images/val
test: images/test
nc: 5
names: ['Plastic', 'Vinyl', 'Can', 'Glass', 'Paper']
""")
print("\ndata.yaml created")
print("\n=== DONE ===")
print(f"\nFinal verification:")
print(f" Train: {len(os.listdir('dataset/images/train'))} images, {len(os.listdir('dataset/labels/train'))} labels")
print(f" Val: {len(os.listdir('dataset/images/val'))} images, {len(os.listdir('dataset/labels/val'))} labels")
print(f" Test: {len(os.listdir('dataset/images/test'))} images, {len(os.listdir('dataset/labels/test'))} labels")
|