File size: 3,498 Bytes
ac831c4
5f4e276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62b1b2e
5f4e276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from dotenv import load_dotenv
from roboflow import Roboflow
import tempfile
import os
import requests
from PIL import Image

# Muat variabel lingkungan dari file .env
load_dotenv()
api_key = os.getenv("ROBOFLOW_API_KEY")
workspace = os.getenv("ROBOFLOW_WORKSPACE")
project_name = os.getenv("ROBOFLOW_PROJECT")
model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))

# Inisialisasi Roboflow menggunakan data yang diambil dari secrets
rf = Roboflow(api_key=api_key)
project = rf.workspace(workspace).project(project_name)
model = project.version(model_version).model

# Fungsi untuk memotong gambar menjadi potongan-potongan kecil
def slice_image(image, slice_size=512, overlap=0):
    width, height = image.size
    slices = []

    step = slice_size - overlap

    for top in range(0, height, step):
        for left in range(0, width, step):
            bottom = min(top + slice_size, height)
            right = min(left + slice_size, width)
            slices.append((left, top, right, bottom))

    return slices

# Fungsi untuk menangani input dan output gambar
def detect_objects(image):
    slice_size = 512
    overlap = 50

    # Potong gambar menjadi bagian kecil
    slices = slice_image(image, slice_size, overlap)
    results = []
    class_count = {}
    total_count = 0

    for i, (left, top, right, bottom) in enumerate(slices):
        sliced_image = image.crop((left, top, right, bottom))

        # Simpan gambar slice sementara
        with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
            sliced_image.save(temp_file, format="JPEG")
            temp_file_path = temp_file.name

        try:
            # Lakukan prediksi pada setiap slice
            predictions = model.predict(temp_file_path, confidence=60, overlap=80).json()

            for prediction in predictions['predictions']:
                prediction["left"] += left
                prediction["top"] += top
                prediction["right"] += left
                prediction["bottom"] += top

                results.append(prediction)

                # Perbarui jumlah objek per kelas
                class_name = prediction['class']
                class_count[class_name] = class_count.get(class_name, 0) + 1
                total_count += 1
        except requests.exceptions.HTTPError as http_err:
            return f"HTTP error occurred: {http_err}", None
        except Exception as err:
            return f"An error occurred: {err}", None
        finally:
            os.remove(temp_file_path)

    # Gabungkan hasil deteksi
    result_text = "Product Nestle\n\n"
    for class_name, count in class_count.items():
        result_text += f"{class_name}: {count}\n"
    result_text += f"\nTotal Product Nestle: {total_count}"

    # Kembalikan hasil
    return image, result_text

# Membuat antarmuka Gradio dengan tata letak fleksibel
with gr.Blocks() as iface:
    with gr.Row():
        with gr.Column():
            input_image = gr.Image(type="pil", label="Input Image")
        with gr.Column():
            output_image = gr.Image(label="Detect Object")
        with gr.Column():
            output_text = gr.Textbox(label="Counting Object")

    # Tombol untuk memproses input
    detect_button = gr.Button("Detect")

    # Hubungkan tombol dengan fungsi deteksi
    detect_button.click(
        fn=detect_objects,
        inputs=input_image,
        outputs=[output_image, output_text]
    )

# Menjalankan antarmuka
iface.launch()