Ku-Yolo-DataSet / inference.py
hyeon2525's picture
Add YOLO training and evaluation scripts
3a6b652
"""
학습된 모델로 추론 (예측) 테스트
- 단일 이미지 또는 폴더 예측
- 결과 시각화 및 저장
"""
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("잘못된 선택입니다.")