| import torch |
| from torchvision.models import efficientnet_b0, EfficientNet_B0_Weights |
| import torchvision.transforms as transforms |
| from PIL import Image |
| import torch.nn.functional as F |
| import json |
| import os |
| import sys |
|
|
| |
| |
| |
| CLASS_MAP_FILENAME = 'labels_map.txt' |
| class_name_map = None |
|
|
| try: |
| if not os.path.exists(CLASS_MAP_FILENAME): |
| print(f"[์ค๋ฅ] ํด๋์ค ์ด๋ฆ ํ์ผ('{CLASS_MAP_FILENAME}')์ ์ฐพ์ ์ ์์ต๋๋ค.") |
| print("ํ์ผ์ ํ์ฌ ๋๋ ํ ๋ฆฌ์ ์ ์ฅํ๋์ง ํ์ธํด ์ฃผ์ธ์.") |
| sys.exit(1) |
|
|
| |
| with open(CLASS_MAP_FILENAME, 'r') as f: |
| class_map_json = json.load(f) |
|
|
| |
| |
| labels_list = [class_map_json[str(i)] for i in range(1000)] |
| |
| |
| class_name_map = {i: name for i, name in enumerate(labels_list)} |
| |
| print(f"ImageNet ํด๋์ค ์ด๋ฆ ({len(class_name_map)}๊ฐ) ๋ก๋ ์๋ฃ.") |
|
|
| except Exception as e: |
| print(f"[์ค๋ฅ] ํด๋์ค ํ์ผ ๋ก๋ ๋๋ ์ฒ๋ฆฌ ์ค ์ค๋ฅ ๋ฐ์: {e}") |
| sys.exit(1) |
|
|
|
|
| |
| |
| |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| print(f"์ฌ์ฉ ์ฅ์น: {device}") |
|
|
| |
| print("์ฌ์ ํ๋ จ๋ EfficientNetB0 ๋ชจ๋ธ ๋ก๋ ์ค...") |
| model = efficientnet_b0(weights=EfficientNet_B0_Weights.IMAGENET1K_V1) |
| model.eval() |
| model = model.to(device) |
| print("๋ชจ๋ธ ๋ก๋ ๋ฐ ํ๊ฐ ๋ชจ๋ ์ค์ ์๋ฃ.") |
|
|
| |
| |
| |
| preprocess = transforms.Compose([ |
| transforms.Resize(256), |
| transforms.CenterCrop(224), |
| transforms.ToTensor(), |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| ]) |
|
|
| |
| |
| |
|
|
| def classify_image(image_path_string): |
| """ |
| ์ฃผ์ด์ง ์ด๋ฏธ์ง ๊ฒฝ๋ก์ ํ์ผ์ EfficientNetB0 ๋ชจ๋ธ๋ก ๋ถ๋ฅํ๊ณ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํฉ๋๋ค. |
| (ํด๋์ค ์ด๋ฆ ํฌํจ) |
| """ |
| try: |
| |
| img = Image.open(image_path_string).convert('RGB') |
| print(f"\n[INFO] ์ด๋ฏธ์ง ๋ก๋ ์ฑ๊ณต: {image_path_string}") |
| |
| input_tensor = preprocess(img) |
| input_batch = input_tensor.unsqueeze(0).to(device) |
|
|
| with torch.no_grad(): |
| output = model(input_batch) |
|
|
| probabilities = F.softmax(output[0], dim=0) |
| top_prob, top_catid = torch.topk(probabilities, 5) |
|
|
| print("\n--- ๋ถ๋ฅ ๊ฒฐ๊ณผ (Top-5) ---") |
| |
| for i in range(top_prob.size(0)): |
| idx = top_catid[i].item() |
| |
| |
| class_name = class_name_map.get(idx, f"์ ์ ์๋ ํด๋์ค (ID: {idx})") |
| |
| print(f"์์ {i+1}:") |
| print(f" - ํด๋์ค ์ด๋ฆ: **{class_name}**") |
| print(f" - ํด๋์ค ์ธ๋ฑ์ค (ID): {idx}") |
| print(f" - ํ๋ฅ : {top_prob[i].item():.4f}") |
|
|
| except FileNotFoundError: |
| print(f"\n[์ค๋ฅ] ์ด๋ฏธ์ง ํ์ผ์ ์ฐพ์ ์ ์์ต๋๋ค: {image_path_string}") |
| print("๊ฒฝ๋ก๋ฅผ ๋ค์ ํ์ธํด์ฃผ์ธ์.") |
| except Exception as e: |
| print(f"\n[์ค๋ฅ] ๋ถ๋ฅ ์ค ๋ฌธ์ ๊ฐ ๋ฐ์ํ์ต๋๋ค: {e}") |
|
|
|
|
| |
| |
| CLASSIFY_TARGET_PATH = 'C:/Users/itg/Pictures/muffin1.png' |
|
|
| |
| classify_image(CLASSIFY_TARGET_PATH) |