|
|
|
|
|
import gradio as gr |
|
from ultralytics import YOLO |
|
from PIL import Image |
|
import numpy as np |
|
import yaml |
|
import os |
|
import zipfile |
|
|
|
|
|
|
|
model = YOLO("best.pt") |
|
|
|
|
|
with open("data.yaml", "r") as f: |
|
class_names = yaml.safe_load(f)["names"] |
|
|
|
|
|
with zipfile.ZipFile("test.zip", 'r') as zip_ref: |
|
zip_ref.extractall("test") |
|
|
|
|
|
def detect_objects(image): |
|
results = model(image)[0] |
|
detected_classes = [] |
|
|
|
for box in results.boxes: |
|
cls_id = int(box.cls[0].item()) |
|
class_name = class_names[cls_id] |
|
detected_classes.append(class_name) |
|
|
|
result_image = Image.fromarray(results.plot()) |
|
summary = ", ".join(set(detected_classes)) if detected_classes else "탐지된 객체 없음" |
|
|
|
return result_image, f"탐지된 클래스: {summary}" |
|
|
|
|
|
def get_image_file_list(): |
|
image_dir = "test/images" |
|
file_list = sorted([ |
|
f for f in os.listdir(image_dir) if f.endswith((".jpg", ".png")) |
|
]) |
|
return file_list |
|
|
|
|
|
def load_image_by_index(index_display: int): |
|
index = index_display - 1 |
|
file_list = get_image_file_list() |
|
if 0 <= index < len(file_list): |
|
image_path = os.path.join("test/images", file_list[index]) |
|
return Image.open(image_path).convert("RGB") |
|
else: |
|
return Image.new("RGB", (300, 300), color="gray") |
|
|
|
|
|
with gr.Blocks() as demo: |
|
gr.Markdown("## ✌ YOLO 객체 탐지 템플릿 2 - 탭 기반 멀티기능 데모") |
|
gr.Markdown("Tab 1: 테스트 이미지 선택 / Tab 2: 사용자 이미지 업로드") |
|
|
|
with gr.Tab("📁 테스트 데이터셋에서 실행"): |
|
file_list = get_image_file_list() |
|
index_choices = [i + 1 for i in range(len(file_list))] |
|
|
|
dropdown = gr.Dropdown(choices=index_choices, value=1, label="테스트 이미지 번호 선택") |
|
load_btn = gr.Button("이미지 불러오기") |
|
selected_image = gr.Image(label="선택된 이미지", type="pil") |
|
detect_btn = gr.Button("탐지 실행") |
|
result_img = gr.Image(label="탐지 결과 이미지") |
|
result_txt = gr.Textbox(label="탐지된 클래스 요약") |
|
|
|
load_btn.click(fn=load_image_by_index, inputs=dropdown, outputs=selected_image) |
|
detect_btn.click(fn=detect_objects, inputs=selected_image, outputs=[result_img, result_txt]) |
|
|
|
with gr.Tab("🖼️ 사용자 이미지 업로드"): |
|
user_img = gr.Image(type="pil", label="이미지 업로드") |
|
user_btn = gr.Button("탐지 실행") |
|
user_result_img = gr.Image(label="탐지 결과 이미지") |
|
user_result_txt = gr.Textbox(label="탐지된 클래스 요약") |
|
user_btn.click(fn=detect_objects, inputs=user_img, outputs=[user_result_img, user_result_txt]) |
|
|
|
demo.launch() |
|
|
|
|