Update app.py
Browse files
app.py
CHANGED
|
@@ -1,98 +1,68 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import tensorflow as tf
|
| 3 |
-
import numpy as np
|
| 4 |
-
from PIL import Image
|
| 5 |
-
import cv2
|
| 6 |
-
from tensorflow.keras.applications.efficientnet import preprocess_input
|
| 7 |
-
|
| 8 |
-
# === Konfigurasi halaman ===
|
| 9 |
-
st.set_page_config(page_title="Garbage Classifier", page_icon="♻️", layout="centered")
|
| 10 |
-
st.markdown("<h1 style='text-align: center; color: white;'>♻️ Garbage Classifier - EfNetB2</h1>", unsafe_allow_html=True)
|
| 11 |
-
st.write("
|
| 12 |
-
|
| 13 |
-
# === Load model ===
|
| 14 |
-
@st.cache_resource
|
| 15 |
-
def load_model():
|
| 16 |
-
base_model = tf.keras.applications.EfficientNetB2(
|
| 17 |
-
include_top=False,
|
| 18 |
-
weights="imagenet",
|
| 19 |
-
input_shape=(224, 224, 3)
|
| 20 |
-
)
|
| 21 |
-
x = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)
|
| 22 |
-
x = tf.keras.layers.Dropout(0.3)(x)
|
| 23 |
-
output = tf.keras.layers.Dense(6, activation='softmax')(x)
|
| 24 |
-
model = tf.keras.models.Model(inputs=base_model.input, outputs=output)
|
| 25 |
-
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
|
| 26 |
-
model.load_weights("model/best_model_weights_trial1.keras")
|
| 27 |
-
return model
|
| 28 |
-
|
| 29 |
-
try:
|
| 30 |
-
model = load_model()
|
| 31 |
-
except Exception as e:
|
| 32 |
-
st.error(f"Gagal memuat model: {e}")
|
| 33 |
-
st.stop()
|
| 34 |
-
|
| 35 |
-
labels = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
|
| 36 |
-
|
| 37 |
-
# === Preprocessing untuk EfficientNet ===
|
| 38 |
-
def preprocess(frame):
|
| 39 |
-
img = cv2.resize(frame, (224, 224))
|
| 40 |
-
img = img.astype('float32')
|
| 41 |
-
img = preprocess_input(img)
|
| 42 |
-
return np.expand_dims(img, axis=0)
|
| 43 |
-
|
| 44 |
-
# === Fungsi prediksi dan anotasi ===
|
| 45 |
-
def predict_and_draw(frame):
|
| 46 |
-
input_tensor = preprocess(frame)
|
| 47 |
-
pred = model.predict(input_tensor, verbose=0)[0]
|
| 48 |
-
class_idx = np.argmax(pred)
|
| 49 |
-
label = labels[class_idx]
|
| 50 |
-
confidence = pred[class_idx]
|
| 51 |
-
|
| 52 |
-
h, w, _ = frame.shape
|
| 53 |
-
cv2.rectangle(frame, (10, 10), (w - 10, h - 10), (0, 255, 0), 3)
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
(text_w, text_h),
|
| 57 |
-
cv2.
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
st.
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
if use_webcam and start_cam and not stop_cam:
|
| 70 |
-
stframe = st.empty()
|
| 71 |
-
cap = cv2.VideoCapture(0)
|
| 72 |
-
|
| 73 |
-
while cap.isOpened():
|
| 74 |
-
ret, frame = cap.read()
|
| 75 |
-
if not ret:
|
| 76 |
-
st.warning("❌ Tidak bisa mengakses kamera.")
|
| 77 |
-
break
|
| 78 |
-
|
| 79 |
-
frame = cv2.flip(frame, 1)
|
| 80 |
-
result = predict_and_draw(frame)
|
| 81 |
-
stframe.image(result, channels="BGR")
|
| 82 |
-
|
| 83 |
-
if stop_cam:
|
| 84 |
-
break
|
| 85 |
-
|
| 86 |
-
cap.release()
|
| 87 |
-
cv2.destroyAllWindows()
|
| 88 |
-
|
| 89 |
-
# === Upload Gambar Alternatif ===
|
| 90 |
-
st.markdown("---")
|
| 91 |
-
st.markdown("### 🖼️ Atau Upload Gambar:")
|
| 92 |
-
|
| 93 |
-
uploaded_file = st.file_uploader("Upload file gambar", type=["jpg", "jpeg", "png"])
|
| 94 |
-
if uploaded_file is not None:
|
| 95 |
-
pil_img = Image.open(uploaded_file).convert("RGB")
|
| 96 |
-
frame = np.array(pil_img)
|
| 97 |
-
result = predict_and_draw(frame)
|
| 98 |
-
st.image(result, channels="BGR")
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import cv2
|
| 6 |
+
from tensorflow.keras.applications.efficientnet import preprocess_input
|
| 7 |
+
|
| 8 |
+
# === Konfigurasi halaman ===
|
| 9 |
+
st.set_page_config(page_title="Garbage Classifier", page_icon="♻️", layout="centered")
|
| 10 |
+
st.markdown("<h1 style='text-align: center; color: white;'>♻️ Garbage Classifier - EfNetB2</h1>", unsafe_allow_html=True)
|
| 11 |
+
st.write("Upload gambar untuk mendapatkan prediksi jenis sampah.")
|
| 12 |
+
|
| 13 |
+
# === Load model ===
|
| 14 |
+
@st.cache_resource
|
| 15 |
+
def load_model():
|
| 16 |
+
base_model = tf.keras.applications.EfficientNetB2(
|
| 17 |
+
include_top=False,
|
| 18 |
+
weights="imagenet",
|
| 19 |
+
input_shape=(224, 224, 3)
|
| 20 |
+
)
|
| 21 |
+
x = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)
|
| 22 |
+
x = tf.keras.layers.Dropout(0.3)(x)
|
| 23 |
+
output = tf.keras.layers.Dense(6, activation='softmax')(x)
|
| 24 |
+
model = tf.keras.models.Model(inputs=base_model.input, outputs=output)
|
| 25 |
+
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
|
| 26 |
+
model.load_weights("model/best_model_weights_trial1.keras")
|
| 27 |
+
return model
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
model = load_model()
|
| 31 |
+
except Exception as e:
|
| 32 |
+
st.error(f"Gagal memuat model: {e}")
|
| 33 |
+
st.stop()
|
| 34 |
+
|
| 35 |
+
labels = ['cardboard', 'glass', 'metal', 'paper', 'plastic', 'trash']
|
| 36 |
+
|
| 37 |
+
# === Preprocessing untuk EfficientNet ===
|
| 38 |
+
def preprocess(frame):
|
| 39 |
+
img = cv2.resize(frame, (224, 224))
|
| 40 |
+
img = img.astype('float32')
|
| 41 |
+
img = preprocess_input(img)
|
| 42 |
+
return np.expand_dims(img, axis=0)
|
| 43 |
+
|
| 44 |
+
# === Fungsi prediksi dan anotasi ===
|
| 45 |
+
def predict_and_draw(frame):
|
| 46 |
+
input_tensor = preprocess(frame)
|
| 47 |
+
pred = model.predict(input_tensor, verbose=0)[0]
|
| 48 |
+
class_idx = np.argmax(pred)
|
| 49 |
+
label = labels[class_idx]
|
| 50 |
+
confidence = pred[class_idx]
|
| 51 |
+
|
| 52 |
+
h, w, _ = frame.shape
|
| 53 |
+
cv2.rectangle(frame, (10, 10), (w - 10, h - 10), (0, 255, 0), 3)
|
| 54 |
+
text = f"{label} ({confidence * 100:.2f}%)"
|
| 55 |
+
(text_w, text_h), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)
|
| 56 |
+
cv2.rectangle(frame, (10, 10), (10 + text_w + 20, 10 + text_h + 20), (0, 0, 0), -1)
|
| 57 |
+
cv2.putText(frame, text, (20, 30 + text_h), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
|
| 58 |
+
|
| 59 |
+
return frame
|
| 60 |
+
|
| 61 |
+
# === Upload Gambar ===
|
| 62 |
+
st.markdown("### 🖼️ Upload Gambar untuk Prediksi")
|
| 63 |
+
uploaded_file = st.file_uploader("Pilih gambar sampah", type=["jpg", "jpeg", "png"])
|
| 64 |
+
if uploaded_file is not None:
|
| 65 |
+
pil_img = Image.open(uploaded_file).convert("RGB")
|
| 66 |
+
frame = np.array(pil_img)
|
| 67 |
+
result = predict_and_draw(frame)
|
| 68 |
+
st.image(result, channels="BGR")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|