File size: 4,724 Bytes
2b08904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from ultralytics import YOLO
import cv2
import numpy as np
from PIL import Image
import torch

# Моделді жүктеу
model = None

def load_model(model_path="best.pt"):
    """Моделді жүктеу функциясы"""
    global model
    try:
        model = YOLO(model_path)
        return "Модель сәтті жүктелді!"
    except Exception as e:
        return f"Қате: {str(e)}"

def predict_image(image, conf_threshold=0.25, iou_threshold=0.45):
    """Суретті талдау және сегментация жасау"""
    if model is None:
        return None, "Модель жүктелмеген!"
    
    try:
        # Болжам жасау
        results = model.predict(
            source=image,
            conf=conf_threshold,
            iou=iou_threshold,
            save=False
        )
        
        # Нәтижені визуализациялау
        annotated_img = results[0].plot()
        annotated_img = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
        
        # Анықталған объектілер туралы ақпарат
        detections = []
        if results[0].masks is not None:
            for i, (box, mask) in enumerate(zip(results[0].boxes, results[0].masks)):
                class_id = int(box.cls[0])
                confidence = float(box.conf[0])
                class_name = model.names[class_id]
                detections.append(f"{i+1}. {class_name}: {confidence:.2%}")
        
        info_text = "\n".join(detections) if detections else "Объектілер табылмады"
        
        return annotated_img, info_text
    
    except Exception as e:
        return None, f"Қате: {str(e)}"

# Gradio интерфейсі
def create_interface():
    with gr.Blocks(title="YOLOv8 Қазақша Сегментация", theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # 🎯 YOLOv8 Сегментация - Қазақша
        
        Бұл модель объектілерді анықтап, сегментациялайды. 
        Суретті жүктеп, параметрлерді орнатыңыз.
        """)
        
        with gr.Row():
            with gr.Column():
                input_image = gr.Image(
                    label="Суретті жүктеңіз",
                    type="numpy"
                )
                
                conf_slider = gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=0.25,
                    step=0.05,
                    label="Сенімділік табалдырығы (Confidence)"
                )
                
                iou_slider = gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=0.45,
                    step=0.05,
                    label="IoU табалдырығы"
                )
                
                predict_btn = gr.Button("🔍 Талдау", variant="primary")
            
            with gr.Column():
                output_image = gr.Image(
                    label="Нәтиже"
                )
                output_text = gr.Textbox(
                    label="Анықталған объектілер",
                    lines=10
                )
        
        gr.Markdown("""
        ### 📝 Нұсқаулық:
        1. Суретті жүктеңіз
        2. Қажет болса параметрлерді өзгертіңіз
        3. "Талдау" батырмасын басыңыз
        
        ### ⚙️ Параметрлер:
        - **Сенімділік табалдырығы**: Объектіді қабылдау үшін минималды сенімділік
        - **IoU табалдырығы**: Non-maximum suppression үшін қолданылады
        """)
        
        predict_btn.click(
            fn=predict_image,
            inputs=[input_image, conf_slider, iou_slider],
            outputs=[output_image, output_text]
        )
        
        # Мысал суреттер
        gr.Markdown("### 📸 Мысалдар:")
        gr.Examples(
            examples=[
                ["example1.jpg", 0.25, 0.45],
                ["example2.jpg", 0.25, 0.45],
            ],
            inputs=[input_image, conf_slider, iou_slider],
            outputs=[output_image, output_text],
            fn=predict_image,
            cache_examples=False,
        )
    
    return demo

# Моделді жүктеу
load_model()

# Интерфейсті іске қосу
if __name__ == "__main__":
    demo = create_interface()
    demo.launch()