File size: 6,594 Bytes
3a6b652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""
학습된 모델로 추론 (예측) 테스트
- 단일 이미지 또는 폴더 예측
- 결과 시각화 및 저장
"""

from ultralytics import YOLO
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np


def predict_image(model_path, image_path, conf=0.25, save=True, show=False):
    """
    이미지 예측

    Args:
        model_path: 모델 경로
        image_path: 이미지 경로
        conf: 신뢰도 임계값 (0.0 ~ 1.0)
        save: 결과 저장 여부
        show: 결과 표시 여부
    """

    print("=" * 60)
    print("이미지 예측")
    print("=" * 60)

    # 모델 로드
    print(f"모델 로드: {model_path}")
    model = YOLO(model_path)

    # 예측
    print(f"이미지: {image_path}")
    print(f"신뢰도 임계값: {conf}")

    results = model.predict(
        source=image_path,
        save=save,
        conf=conf,
        iou=0.7,
        show_labels=True,
        show_conf=True,
        line_width=2,
    )

    # 결과 분석
    for r in results:
        print(f"\n탐지 결과:")
        print(f"  이미지 크기: {r.orig_shape}")
        print(f"  탐지된 객체 수: {len(r.boxes)}")

        if len(r.boxes) > 0:
            print(f"\n  {'클래스':<12} {'신뢰도':>8} {'좌표 (x, y, w, h)'}")
            print("  " + "-" * 50)

            for box in r.boxes:
                cls_id = int(box.cls[0])
                conf_val = float(box.conf[0])
                cls_name = r.names[cls_id]
                xyxy = box.xyxy[0].cpu().numpy()

                print(f"  {cls_name:<12} {conf_val:>7.2%}  "
                      f"({xyxy[0]:.0f}, {xyxy[1]:.0f}, "
                      f"{xyxy[2]-xyxy[0]:.0f}, {xyxy[3]-xyxy[1]:.0f})")
        else:
            print("  객체가 탐지되지 않았습니다.")

    # 시각화
    if show:
        for r in results:
            img = r.plot()  # BGR
            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

            plt.figure(figsize=(12, 8))
            plt.imshow(img_rgb)
            plt.axis('off')
            plt.title(f"Detection Results (conf={conf})", fontsize=14)
            plt.tight_layout()
            plt.show()

    print("\n✅ 예측 완료!")
    if save:
        print(f"결과 저장: runs/detect/predict/")

    return results


def predict_folder(model_path, folder_path, conf=0.25, save=True):
    """
    폴더 내 모든 이미지 예측

    Args:
        model_path: 모델 경로
        folder_path: 이미지 폴더 경로
        conf: 신뢰도 임계값
        save: 결과 저장 여부
    """

    print("=" * 60)
    print("폴더 예측")
    print("=" * 60)

    # 모델 로드
    model = YOLO(model_path)

    # 이미지 파일 찾기
    folder = Path(folder_path)
    image_files = list(folder.glob('*.[jJ][pP][gG]')) + \
                  list(folder.glob('*.[pP][nN][gG]'))

    print(f"폴더: {folder_path}")
    print(f"발견된 이미지: {len(image_files)}개")

    if len(image_files) == 0:
        print("❌ 이미지를 찾을 수 없습니다.")
        return None

    # 예측
    results = model.predict(
        source=folder_path,
        save=save,
        conf=conf,
        iou=0.7,
        show_labels=True,
        show_conf=True,
    )

    # 통계
    total_detections = sum(len(r.boxes) for r in results)

    print(f"\n예측 완료!")
    print(f"  처리한 이미지: {len(results)}개")
    print(f"  총 탐지 객체: {total_detections}개")
    print(f"  평균 객체/이미지: {total_detections/len(results):.2f}개")

    if save:
        print(f"\n결과 저장: runs/detect/predict/")

    return results


def compare_predictions(model_path, image_path, conf_levels=[0.1, 0.25, 0.5, 0.75]):
    """
    다양한 신뢰도 임계값으로 예측 비교

    Args:
        model_path: 모델 경로
        image_path: 이미지 경로
        conf_levels: 신뢰도 임계값 리스트
    """

    print("=" * 60)
    print("신뢰도 임계값 비교")
    print("=" * 60)

    model = YOLO(model_path)

    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    axes = axes.flatten()

    for i, conf in enumerate(conf_levels):
        print(f"\n신뢰도 {conf:.2f} 예측 중...")

        results = model.predict(
            source=image_path,
            conf=conf,
            save=False,
            verbose=False
        )

        for r in results:
            img = r.plot()
            img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

            axes[i].imshow(img_rgb)
            axes[i].axis('off')
            axes[i].set_title(f'Confidence = {conf} ({len(r.boxes)} objects)',
                             fontsize=12, fontweight='bold')

    plt.tight_layout()
    plt.savefig('confidence_comparison.png', dpi=150, bbox_inches='tight')
    print("\n✅ 비교 결과 저장: confidence_comparison.png")
    plt.show()


if __name__ == '__main__':
    import sys

    # 기본 모델 경로
    default_model = 'waste_classification/yolov8n_5class/weights/best.pt'

    print("=" * 60)
    print("YOLO 추론 테스트")
    print("=" * 60)

    # 모델 경로
    if len(sys.argv) > 1:
        model_path = sys.argv[1]
    else:
        print(f"\n모델 경로 (엔터: {default_model}):")
        user_input = input().strip()
        model_path = user_input if user_input else default_model

    if not Path(model_path).exists():
        print(f"❌ 모델을 찾을 수 없습니다: {model_path}")
        sys.exit(1)

    # 이미지 경로
    if len(sys.argv) > 2:
        image_path = sys.argv[2]
    else:
        default_image = 'data/batch_1/000006.jpg'
        print(f"이미지 경로 (엔터: {default_image}):")
        user_input = input().strip()
        image_path = user_input if user_input else default_image

    if not Path(image_path).exists():
        print(f"❌ 이미지를 찾을 수 없습니다: {image_path}")
        sys.exit(1)

    # 예측 실행
    print("\n작업 선택:")
    print("  1. 단일 이미지 예측")
    print("  2. 폴더 예측")
    print("  3. 신뢰도 비교")

    choice = input("선택 (1/2/3, 엔터: 1): ").strip() or '1'

    if choice == '1':
        predict_image(model_path, image_path, conf=0.25, save=True, show=True)
    elif choice == '2':
        folder = Path(image_path).parent if Path(image_path).is_file() else image_path
        predict_folder(model_path, folder, conf=0.25, save=True)
    elif choice == '3':
        compare_predictions(model_path, image_path)
    else:
        print("잘못된 선택입니다.")