|
|
|
|
|
import streamlit as st |
|
|
import tensorflow as tf |
|
|
from tensorflow import keras |
|
|
import numpy as np |
|
|
from PIL import Image |
|
|
import matplotlib.pyplot as plt |
|
|
from sklearn.model_selection import train_test_split |
|
|
|
|
|
|
|
|
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() |
|
|
|
|
|
|
|
|
x_train, x_test = x_train / 255.0, x_test / 255.0 |
|
|
|
|
|
|
|
|
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42) |
|
|
|
|
|
|
|
|
def create_model(): |
|
|
model = keras.models.Sequential([ |
|
|
keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), |
|
|
keras.layers.MaxPooling2D((2, 2)), |
|
|
keras.layers.Conv2D(64, (3, 3), activation='relu'), |
|
|
keras.layers.MaxPooling2D((2, 2)), |
|
|
keras.layers.Conv2D(128, (3, 3), activation='relu'), |
|
|
keras.layers.Flatten(), |
|
|
keras.layers.Dense(128, activation='relu'), |
|
|
keras.layers.Dense(10, activation='softmax') |
|
|
]) |
|
|
return model |
|
|
|
|
|
|
|
|
import os |
|
|
if not os.path.exists("cifar10_cnn_model.h5"): |
|
|
|
|
|
model = create_model() |
|
|
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) |
|
|
|
|
|
|
|
|
st.write("Training the model...") |
|
|
history = model.fit(x_train, y_train, epochs=40, validation_data=(x_val, y_val)) |
|
|
|
|
|
|
|
|
model.save("cifar10_cnn_model.h5") |
|
|
st.write("Model saved as 'cifar10_cnn_model.h5'") |
|
|
else: |
|
|
|
|
|
st.write("Loading pre-trained model...") |
|
|
model = keras.models.load_model("cifar10_cnn_model.h5") |
|
|
|
|
|
|
|
|
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] |
|
|
|
|
|
|
|
|
st.title("Image Detection System") |
|
|
|
|
|
|
|
|
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"]) |
|
|
|
|
|
if uploaded_file is not None: |
|
|
|
|
|
image = Image.open(uploaded_file) |
|
|
st.image(image, caption="Uploaded Image", use_column_width=True) |
|
|
|
|
|
|
|
|
image = image.resize((32, 32)) |
|
|
image = np.array(image) / 255.0 |
|
|
image = np.expand_dims(image, axis=0) |
|
|
|
|
|
|
|
|
predictions = model.predict(image) |
|
|
predicted_class = np.argmax(predictions) |
|
|
confidence = np.max(predictions) * 100 |
|
|
|
|
|
|
|
|
st.write(f"**Prediction:** {class_names[predicted_class]}") |
|
|
st.write(f"**Confidence:** {confidence:.2f}%") |
|
|
model.save("cifar10_cnn_model.keras") |