1import torch
2import onnxruntime as ort
3import numpy as np
4from PIL import Image
5from torchvision import transforms
6import json
78# 모델 정보 로드9withopen('image_classifier_model_0.2_model_info.json','r')as f:10 model_info = json.load(f)1112# PyTorch 모델 로드13model = torch.load('image_classifier_model_0.2.pth', map_location='cpu')14model.eval()1516# ONNX 모델 사용 (더 빠른 추론)17onnx_session = ort.InferenceSession('image_classifier_model_0.2.onnx')1819# 이미지 전처리20transform = transforms.Compose([21 transforms.Resize((224,224)),22 transforms.CenterCrop(224),23 transforms.ToTensor(),24 transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225])25])2627defclassify_image_pytorch(image_path):28"""PyTorch 모델을 사용한 이미지 분류"""29 image = transform(Image.open(image_path)).unsqueeze(0)3031with torch.no_grad():32 outputs = model(image)33 predictions ={}3435for head_name, logits in outputs.items():36 probabilities = torch.softmax(logits, dim=1)37 predicted_class = torch.argmax(probabilities, dim=1).item()38 confidence = probabilities[0, predicted_class].item()3940 predictions[head_name]={41'class_id': predicted_class,42'confidence': confidence,43'probabilities': probabilities[0].tolist()44}4546return predictions
4748defclassify_image_onnx(image_path):49"""ONNX 모델을 사용한 이미지 분류 (권장)"""50 image = transform(Image.open(image_path)).numpy()5152# ONNX 모델 추론53 input_feed ={'input': image.astype(np.float32)}54 outputs = onnx_session.run(None, input_feed)5556 predictions ={}57 head_names =['scene','concept','object']5859for i, head_name inenumerate(head_names):60 logits = outputs[i]61 probabilities = torch.softmax(torch.tensor(logits), dim=1)62 predicted_class = torch.argmax(probabilities, dim=1).item()63 confidence = probabilities[0, predicted_class].item()6465 predictions[head_name]={66'class_id': predicted_class,67'confidence': confidence,68'probabilities': probabilities[0].tolist()69}7071return predictions
7273# 예시 사용74predictions = classify_image_onnx("hotel_room.jpg")75print("분류 결과:")76for head, result in predictions.items():77print(f"{head}: 클래스 {result['class_id']}, 신뢰도 {result['confidence']:.4f}")
클래스 ID를 실제 클래스명으로 변환
python
1defget_class_names(predictions, model_info):2"""클래스 ID를 실제 클래스명으로 변환"""3 class_mappings = model_info['class_mappings']45 results ={}6for head, result in predictions.items():7 class_id = result['class_id']8if head in class_mappings:9 actual_class_id = class_mappings[head][str(class_id)]10 results[head]={11'class_id': actual_class_id,12'confidence': result['confidence']13}1415return results
1617# 클래스명 변환 예시18class_names = get_class_names(predictions, model_info)19print("실제 클래스 ID:")20for head, result in class_names.items():21print(f"{head}: {result['class_id']}")
배치 처리
python
1defclassify_batch_images(image_paths):2"""여러 이미지를 한 번에 분류"""3 results =[]45for image_path in image_paths:6 predictions = classify_image_onnx(image_path)7 results.append({8'image_path': image_path,9'predictions': predictions
10})1112return results
1314# 예시15image_paths =["room1.jpg","bathroom1.jpg","lobby1.jpg"]16batch_results = classify_batch_images(image_paths)1718for result in batch_results:19print(f"\n이미지: {result['image_path']}")20for head, pred in result['predictions'].items():21print(f" {head}: 클래스 {pred['class_id']}, 신뢰도 {pred['confidence']:.4f}")
모델 파일
image_classifier_model_0.2.pth: PyTorch 모델 파일
image_classifier_model_0.2.onnx: ONNX 모델 파일 (추론 최적화)
image_classifier_model_0.2_model_info.json: 모델 메타데이터
image_classifier_model_0.2_inference_example.py: 추론 예제 코드
모델 아키텍처
멀티헤드 분류 시스템
입력 이미지 (224×224)
↓
DINOv2 백본 (Frozen)
↓
공통 특징 (1024차원)
├─── Scene 헤드 → 6개 클래스
├─── Concept 헤드 → 3개 클래스
└─── Object 헤드 → 13개 클래스
주요 특징
DINOv2 백본: 강력한 비전 트랜스포머 기반 특징 추출
백본 고정: 사전훈련된 특징을 활용하여 과적합 방지
멀티헤드: 3개 헤드로 다각도 분석
클래스 가중치: 불균형 데이터 자동 보정
전처리 요구사항
이미지 크기: 224x224 픽셀
색상 공간: RGB
정규화: ImageNet 표준값 사용 (mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
크롭: 중앙 크롭 (center crop)
지원 형식: JPG, PNG, JPEG
사용 사례
직접 사용
호텔 이미지 자동 분류: 객실, 욕실, 로비 등 장면별 자동 분류
이미지 메타데이터 생성: 이미지의 장면, 개념, 객체 정보 자동 추출
이미지 데이터베이스 관리: 대량의 호텔 이미지 자동 태깅
품질 관리: 이미지 분류 일관성 검증
다운스트림 사용
호텔 관리 시스템: 객실 이미지 자동 분류 및 관리
여행 플랫폼: 객실 타입별 이미지 필터링
부동산 플랫폼: 숙소 시설 정보 자동 추출
이미지 검색 엔진: 다중 속성 기반 이미지 검색
제한사항
도메인 특화: 호텔/숙소 이미지에 특화되어 있어 다른 도메인에서는 성능이 제한적입니다.
이미지 품질: 저화질이나 노이즈가 많은 이미지에서는 성능이 저하될 수 있습니다.
각도 의존성: 특정 각도에서 촬영된 이미지에 대해 성능이 다를 수 있습니다.
클래스 불균형: 일부 클래스는 다른 클래스보다 성능이 낮을 수 있습니다.
라이선스
Apache 2.0 License
참고
이 모델은 Room Clusterer 프로젝트의 일부로 개발되었습니다. 더 자세한 정보는 프로젝트 저장소를 참조하세요.