Commit Β·
4d42d1c
1
Parent(s): ac02215
..
Browse filesFiles changed (17)
- .gitattributes+1
- .streamlit/config.tomlAdded+5
- Garbage_Clf_CNN/Garbage_Image__CLF_CNN.ipynbAdded
- Garbage_Clf_CNN/Readme.mdAdded+133
- Garbage_Clf_CNN/app.pyAdded+82
- Garbage_Clf_CNN/requirements.txtAdded+4
- README.md+130-15
- class_names.jsonAdded+1
- models/model.h5Added+3
- notebooks/model_building_training.ipynbAdded
- notebooks/preprocessing.ipynbAdded
- plots/ConfusionMatrix.pngAdded
- plots/History_Accuracy_Loss.pngAdded
- plots/countplot.pngAdded
- requirements.txt+4-3
- scripts/train_val_test_split.pyAdded+49
- src/streamlit_app.py+72-38
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.keras filter=lfs diff=lfs merge=lfs -text12345[browser]gatherUsageStats = false
[server]enableXsrfProtection = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133# β»οΈ Waste Category Image Classifier (Streamlit + Keras)
An interactive web app for classifying waste images into **10 distinct categories** using a custom-trained Convolutional Neural Network (CNN). Built with **TensorFlow/Keras** and deployed via **Streamlit**, this app demonstrates the power of deep learning in sustainability-oriented image classification.
---
## π Demo
Upload an image and instantly get a class prediction with confidence and full class-wise probabilities.

---
## π§ Model Summary
- **Architecture**: Custom CNN- **Input Shape**: 224Γ224 RGB- **Layers**: - Convolutional layers with BatchNorm and ReLU - MaxPooling - Global Average Pooling - Dense layers with Dropout- **Optimizer**: Adam (`lr=1e-5`)- **Loss**: Categorical Crossentropy- **Final Layer**: Softmax (10 classes)
---
## π Dataset
The dataset consists of images from 10 waste-related categories:
| Class | Count ||---------------|-------|| battery | 944 || biological | 997 || cardboard | 1825 || clothes | 5327 || glass | 3061 || metal | 1020 || paper | 1680 || plastic | 1984 || shoes | 1977 || trash | 947 |
### π Data Split
| Split | Images ||-----------|--------|| Training | 15,806 || Validation| 1,976 || Testing | 1,980 |
### π§Ό Preprocessing
- All images resized to `224Γ224`- Normalized using: `rescale=1./255`
---
## ποΈ Model Architecture (Keras Sequential)
```pythonInput(shape=(224, 224, 3)) βConv2D(32) β BN β ReLU βConv2D(64) β BN β ReLU β MaxPool(4Γ4) βConv2D(128) β BN β ReLU βConv2D(128) β BN β ReLU β MaxPool(2Γ2) βConv2D(256) β BN β ReLU β MaxPool(2Γ2) βConv2D(512) β BN β ReLU β MaxPool(2Γ2) βGlobalAveragePooling βDense(256) β Dropout(0.4) βDense(10, activation='softmax')````
---
## π₯οΈ Web App Features
* β
Upload image and classify in real-time* π Display confidence score* π Class probabilities table/bar chart* π§ Show model architecture summary in sidebar
---
## π¦ Installation & Run Locally
1. **Clone the repo**
```bashgit clone https://github.com/Amr1Moussa/NTI-final_projects.gitcd NTI-final_projects```
2. **(Optional)** Create a virtual environment
```bashpython -m venv venvsource venv/bin/activate # On Windows: venv\Scripts\activate```
3. **Install dependencies**
```bashpip install -r requirements.txt```
4. **Run the app**
```bashstreamlit run app.py```
---
## π Requirements
See `requirements.txt`:
```txtstreamlittensorflownumpypillowpandasmatplotlib```
## π License
MIT License β use freely, contribute openly, credit kindly.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import streamlit as stimport numpy as npfrom PIL import Image, ImageOpsimport tensorflow as tffrom io import StringIO
# ========== Load Model ==========@st.cache_resourcedef load_model(): model = tf.keras.models.load_model("my_model.keras") return model
model = load_model()
# ========== Class Labels ==========# Replace with your actual class names if neededclass_names = [ 'battery', 'biological', 'cardboard', 'clothes', 'glass', 'metal', 'paper', 'plastic', 'shoes', 'trash']
# ========== Sidebar ==========st.sidebar.title("βοΈ Options")st.sidebar.markdown("""Upload an image for classification.- Supported formats: JPG, PNG, JPEG- Input image will be resized to 224x224""")
if st.sidebar.button("Show Model Summary"): string_io = StringIO() model.summary(print_fn=lambda x: string_io.write(x + "\n")) summary_string = string_io.getvalue() st.sidebar.subheader("π Model Architecture") st.sidebar.text(summary_string)
# ========== Main Title ==========st.title("π§ Garbage Classifier App")st.markdown("Upload an image, and the model will predict the class.")
# ========== File Upload ==========uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
# ========== Preprocessing ==========target_size = (224, 224)
def preprocess_image(img): img = img.resize(target_size) img_array = tf.keras.preprocessing.image.img_to_array(img) img_array = img_array / 255.0 return np.expand_dims(img_array, axis=0)
# ========== Inference ==========if uploaded_file is not None: image = Image.open(uploaded_file).convert("RGB") # Show uploaded image st.image(image, caption="π· Uploaded Image", use_column_width=True)
# Preprocess and predict processed = preprocess_image(image) prediction = model.predict(processed)[0] predicted_index = np.argmax(prediction) predicted_class = class_names[predicted_index] confidence = prediction[predicted_index] * 100
# Show result st.markdown(f"### π― Prediction: `{predicted_class}`") st.markdown(f"**Confidence:** {confidence:.2f}%")
# Display all class probabilities in a table st.subheader("π Class Probabilities") prob_dict = {class_names[i]: float(f"{prediction[i]:.4f}") for i in range(len(class_names))} st.dataframe(prob_dict, use_container_width=True)1234streamlit>=1.32.0tensorflow>=2.12.0pillownumpy1234567891011121314151617181920212223242526272829303132333423456789101112353637383940414243444515464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132171331341920135# Garbage Classification Using ResNet50
This project implements an image classification model using **Transfer Learning with ResNet50** to categorize images of garbage into multiple classes. The model is trained on the ["Garbage Classification V2"](https://www.kaggle.com/datasets/sumn2u/garbage-classification-v2) dataset and built with TensorFlow and Keras.
---
## π Demo
Upload an image and instantly get a class prediction with confidence and full class-wise probabilities.

## π Dataset
* **Source**: [Kaggle - Garbage Classification V2](https://www.kaggle.com/datasets/sumn2u/garbage-classification-v2)* **Classes**: Mixed garbage categories such as cardboard, glass, metal, paper, plastic, trash, etc.* **Format**: Folder-based classification (i.e., one subfolder per class)
The dataset consists of images from 10 waste-related categories:
| Class | Count ||---------------|-------|| battery | 944 || biological | 997 || cardboard | 1825 || clothes | 5327 || glass | 3061 || metal | 1020 || paper | 1680 || plastic | 1984 || shoes | 1977 || trash | 947 |
---title: ResNet50 Garbage Classifieremoji: πcolorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: Streamlit template spacelicense: mit
### π Data Split
| Split | Images ||-----------|--------|| Training | 13,833 || Validation| 3,952 || Testing | 1,976 |
---
# Welcome to Streamlit!### π§Ό Preprocessing
- ```tensorflow.keras.applications.resnet50.preprocess_input```
---
## π§ Model Architecture```Input Image (224x224x3) βResNet50 Base (Frozen) βGlobalAveragePooling2D() βDense(256, activation='relu') βDropout(0.5) βDense(num_classes, activation='softmax')```---
## π§ͺ Training Configuration
* **Image Size**: 224x224* **Batch Size**: 32* **Epochs**: Customizable (default usually 10β25)* **Optimizer**: Adam* **Loss Function**: Categorical Crossentropy* **Metrics**: Accuracy
---
## π₯οΈ Web App Features
* β
Upload image and classify in real-time* π Display confidence score* π Class probabilities table/bar chart* π§ Show model architecture summary in sidebar
---
## π¦ Installation & Run Locally
1. **Clone the repo**
```bashgit clone https://github.com/Amr1Moussa/NTI-final_projects.gitcd NTI-final_projects```
2. **(Optional)** Create a virtual environment
```bashpython -m venv venvsource venv/bin/activate # On Windows: venv\Scripts\activate```
3. **Install dependencies**
```bashpip install -r requirements.txt```
4. **Run the app**
```bashstreamlit run app.py```
---
## π Requirements
See `requirements.txt`:
```txtstreamlittensorflownumpypillowpandasmatplotlib```
---
Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:## π License
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).MIT License β use freely, contribute openly, credit kindly.1["battery", "biological", "cardboard", "clothes", "glass", "metal", "paper", "plastic", "shoes", "trash"]123version https://git-lfs.github.com/spec/v1oid sha256:d251d2c294ed1140908f5341694ddbc057b6d21b11c9670c0caae85645ec87e6size 2369280561231234altairpandasstreamlitstreamlit>=1.32.0tensorflow>=2.12.0pillownumpy12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import osimport shutilfrom sklearn.model_selection import train_test_split
# Set pathstry: ORIGINAL_DATASET = input("Enter the path to the original dataset: ") # Path to the original dataset if not ORIGINAL_DATASET: raise ValueError("Please provide the path to the original dataset.") BASE_DIR = "../data/preprocessed_data" # Output directory
if not os.path.exists(BASE_DIR): os.makedirs(BASE_DIR)except Exception as e: print(f"Error: {e}") exit(1)
# Check if the original dataset existsif not os.path.exists(ORIGINAL_DATASET): print(f"Error: The original dataset path '{ORIGINAL_DATASET}' does not exist.") exit(1)
try: # Create folders for split in ["train", "val", "test"]: for category in os.listdir(ORIGINAL_DATASET): os.makedirs(os.path.join(BASE_DIR, split, category), exist_ok=True)
# Split data for category in os.listdir(ORIGINAL_DATASET): category_path = os.path.join(ORIGINAL_DATASET, category) images = os.listdir(category_path)
train_imgs, temp_imgs = train_test_split(images, test_size=0.3, random_state=42) val_imgs, test_imgs = train_test_split(temp_imgs, test_size=0.33, random_state=42) # 0.33 of 0.3 = 10%
for img_name in train_imgs: shutil.copy(os.path.join(category_path, img_name), os.path.join(BASE_DIR, "train", category, img_name))
for img_name in val_imgs: shutil.copy(os.path.join(category_path, img_name), os.path.join(BASE_DIR, "val", category, img_name))
for img_name in test_imgs: shutil.copy(os.path.join(category_path, img_name), os.path.join(BASE_DIR, "test", category, img_name))
print("Done splitting dataset!")except Exception as e: print(f"An error occurred while splitting the dataset: {e}, please check the paths and try again.") exit(1)1231234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697067891011121314151617181920212223242526272829303132333435363738394071727374import altair as altimport numpy as npimport pandas as pdimport osimport streamlit as stfrom PIL import Imageimport numpy as npimport tensorflow as tffrom tensorflow.keras.preprocessing.image import img_to_arrayfrom tensorflow.keras.applications.resnet50 import preprocess_inputfrom io import StringIO
# ========== Load Model ==========
MODEL_PATH = os.path.join("models", "model.h5")
if not os.path.exists(MODEL_PATH): st.error(f"β Model file not found at: {MODEL_PATH}") st.stop()else: model = tf.keras.models.load_model(MODEL_PATH)
# ========== Class Labels ==========# Replace with your actual class names if neededclass_names = ["battery", "biological", "cardboard", "clothes", "glass", "metal", "paper", "plastic", "shoes", "trash"]
# ========== Sidebar ==========st.sidebar.title("βοΈ Options")st.sidebar.markdown("""Upload an image for classification.- Supported formats: JPG, PNG, JPEG- Input image will be resized to 224x224""")
if st.sidebar.button("Show Model Summary"): string_io = StringIO() model.summary(print_fn=lambda x: string_io.write(x + "\n")) summary_string = string_io.getvalue() st.sidebar.subheader("π Model Architecture") st.sidebar.text(summary_string)
# ========== Main Title ==========st.title("π§ Garbage Classifier App")st.markdown("Upload an image, and the model will predict the class.")
# ========== File Upload ==========uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
# ========== Preprocessing ==========IMG_SIZE = (224, 224)def preprocess_image(img): return preprocess_input(np.expand_dims(img_to_array(img.convert("RGB").resize(IMG_SIZE)), axis=0))
# ========== Inference ==========if uploaded_file is not None: image = Image.open(uploaded_file).convert("RGB") # Show uploaded image st.image(image, caption="π· Uploaded Image", use_container_width=True)
# Preprocess and predict processed = preprocess_image(image) prediction = model.predict(processed)[0] predicted_index = np.argmax(prediction) predicted_class = class_names[predicted_index] confidence = prediction[predicted_index] * 100
# Show result st.markdown(f"### π― Prediction: `{predicted_class}`") st.markdown(f"**Confidence:** {confidence:.2f}%")
"""# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).
In the meantime, below is an example of what you can do with just a few lines of code:"""
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indices
x = radius * np.cos(theta)y = radius * np.sin(theta)
df = pd.DataFrame({ "x": x, "y": y, "idx": indices, "rand": np.random.randn(num_points),})
st.altair_chart(alt.Chart(df, height=700, width=700) .mark_point(filled=True) .encode( x=alt.X("x", axis=None), y=alt.Y("y", axis=None), color=alt.Color("idx", legend=None, scale=alt.Scale()), size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])), )) # Display all class probabilities in a table st.subheader("π Class Probabilities") prob_dict = {class_names[i]: float(f"{prediction[i]:.4f}") for i in range(len(class_names))} st.dataframe(prob_dict, use_container_width=True).gitattributes+1
.streamlit/config.tomlAdded+5
Garbage_Clf_CNN/Garbage_Image__CLF_CNN.ipynbAdded
Garbage_Clf_CNN/Readme.mdAdded+133
Garbage_Clf_CNN/app.pyAdded+82
Garbage_Clf_CNN/requirements.txtAdded+4
README.md+130-15
class_names.jsonAdded+1
models/model.h5Added+3
notebooks/model_building_training.ipynbAdded
notebooks/preprocessing.ipynbAdded
plots/ConfusionMatrix.pngAdded

plots/History_Accuracy_Loss.pngAdded

plots/countplot.pngAdded

requirements.txt+4-3
scripts/train_val_test_split.pyAdded+49
src/streamlit_app.py+72-38