diff --git a/Domains/AI-ML/MiniProjects/ImageClassifier/.gitignore b/Domains/AI-ML/MiniProjects/ImageClassifier/.gitignore new file mode 100644 index 00000000..05a26c77 --- /dev/null +++ b/Domains/AI-ML/MiniProjects/ImageClassifier/.gitignore @@ -0,0 +1,52 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# Virtual environment +venv/ +env/ +ENV/ +.venv + +# Streamlit +.streamlit/ + +# TensorFlow cache +.keras/ +*.h5 +*.pb +*.ckpt + +# Jupyter Notebook +.ipynb_checkpoints + +# Image files (for testing) +*.jpg +*.jpeg +*.png +*.gif +*.bmp + +# Model files (if saved locally) +models/ +*.pkl +*.joblib + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log + +# Distribution / packaging +dist/ +build/ +*.egg-info/ diff --git a/Domains/AI-ML/MiniProjects/ImageClassifier/README.md b/Domains/AI-ML/MiniProjects/ImageClassifier/README.md new file mode 100644 index 00000000..968db886 --- /dev/null +++ b/Domains/AI-ML/MiniProjects/ImageClassifier/README.md @@ -0,0 +1,261 @@ +# ๐Ÿ–ผ๏ธ Image Classifier Using Transfer Learning + +**Contributor:** vatsalgupta2004 +**Domain:** AI-ML +**Difficulty:** Intermediate +**Tech Stack:** Python, TensorFlow/Keras, MobileNetV2, Streamlit + +--- + +## ๐Ÿ“ Description + +A powerful image classification application using Transfer Learning with MobileNetV2 pre-trained on ImageNet. The application features a beautiful web interface built with Streamlit that allows users to upload images and get instant predictions with confidence scores. Supports 1000+ object categories including animals, vehicles, objects, and more. + +--- + +## ๐ŸŽฏ Features + +- โœ… **Pre-trained MobileNetV2 Model** - Leverages transfer learning for accurate predictions +- โœ… **1000+ Categories** - Recognizes animals, vehicles, objects, food, and more +- โœ… **Web Interface** - Beautiful Streamlit UI for easy interaction +- โœ… **Real-time Predictions** - Instant classification with confidence scores +- โœ… **Top-5 Predictions** - Shows the top 5 most likely categories +- โœ… **Image Preprocessing** - Automatic image resizing and normalization +- โœ… **Drag & Drop Upload** - Easy image upload interface +- โœ… **Confidence Visualization** - Progress bars for prediction confidence +- โœ… **Multiple Format Support** - JPG, PNG, JPEG supported +- โœ… **Lightweight & Fast** - MobileNetV2 optimized for speed + +--- + +## ๐Ÿ› ๏ธ Tech Stack + +- **Python 3.8+** - Core programming language +- **TensorFlow 2.x** - Deep learning framework +- **Keras** - High-level neural networks API +- **MobileNetV2** - Pre-trained CNN model +- **Streamlit** - Web application framework +- **Pillow** - Image processing +- **NumPy** - Numerical computations + +--- + +## ๐Ÿ“‹ Prerequisites + +- Python 3.8 or higher +- pip package manager +- 4GB+ RAM recommended +- Internet connection (for first-time model download) + +--- + +## ๐Ÿš€ Installation + +1. **Clone the repository:** + ```bash + cd Domains/AI-ML/MiniProjects/ImageClassifier + ``` + +2. **Create virtual environment (recommended):** + ```bash + python -m venv venv + source venv/bin/activate # On Windows: venv\Scripts\activate + ``` + +3. **Install dependencies:** + ```bash + pip install -r requirements.txt + ``` + +--- + +## ๐Ÿ’ป Usage + +1. **Run the Streamlit app:** + ```bash + streamlit run app.py + ``` + +2. **Open your browser:** + - The app will automatically open at `http://localhost:8501` + - Or manually navigate to the URL shown in terminal + +3. **Classify images:** + - Click "Browse files" or drag & drop an image + - Wait for instant predictions + - View top 5 predictions with confidence scores + +--- + +## ๐Ÿ“ Project Structure + +``` +ImageClassifier/ +โ”‚ +โ”œโ”€โ”€ app.py # Main Streamlit application +โ”œโ”€โ”€ classifier.py # Image classification logic +โ”œโ”€โ”€ requirements.txt # Python dependencies +โ”œโ”€โ”€ README.md # Project documentation +โ”œโ”€โ”€ .gitignore # Git ignore file +โ”‚ +โ””โ”€โ”€ samples/ # Sample test images (optional) + โ”œโ”€โ”€ dog.jpg + โ”œโ”€โ”€ car.jpg + โ””โ”€โ”€ pizza.jpg +``` + +--- + +## ๐Ÿ”ง How It Works + +1. **Model Loading:** + - Uses MobileNetV2 pre-trained on ImageNet dataset + - Includes top classification layer for 1000 categories + - Weights are downloaded automatically on first run + +2. **Image Preprocessing:** + - Resizes image to 224x224 pixels + - Normalizes pixel values to [-1, 1] range + - Applies MobileNetV2-specific preprocessing + +3. **Prediction:** + - Passes preprocessed image through the network + - Decodes predictions to human-readable labels + - Returns top-5 predictions with confidence scores + +4. **Visualization:** + - Displays uploaded image + - Shows predictions in descending confidence order + - Visualizes confidence with progress bars + +--- + +## ๐Ÿ“Š Supported Categories + +The model can classify **1000+ categories** including: + +- ๐Ÿ• **Animals:** Dogs, cats, birds, reptiles, insects +- ๐Ÿš— **Vehicles:** Cars, trucks, airplanes, boats, bicycles +- ๐Ÿ• **Food:** Pizza, burgers, fruits, vegetables, desserts +- ๐Ÿ  **Objects:** Furniture, electronics, tools, clothing +- ๐ŸŒณ **Nature:** Trees, flowers, landscapes, weather +- ๐ŸŽธ **Instruments:** Guitars, pianos, drums, violins +- ๐Ÿˆ **Sports:** Balls, equipment, gear +- And many more! + +--- + +## ๐ŸŽจ Example Use Cases + +1. **Educational Tool:** Learn about object recognition and AI +2. **Content Moderation:** Automatically tag and categorize images +3. **Photo Organization:** Auto-tag photos in your collection +4. **Product Recognition:** Identify products from images +5. **Wildlife Identification:** Recognize animals and plants +6. **Quality Control:** Classify manufactured products +7. **Research:** Study transfer learning and CNNs + +--- + +## ๐Ÿงช Testing + +Try these sample images to test the classifier: + +- **Animals:** Upload pictures of pets, wildlife, or insects +- **Vehicles:** Cars, bikes, planes, boats +- **Food:** Restaurant dishes, fruits, vegetables +- **Objects:** Household items, electronics, tools +- **Nature:** Flowers, trees, landscapes + +--- + +## ๐Ÿ“ˆ Model Performance + +- **Architecture:** MobileNetV2 (Inverted Residuals) +- **Parameters:** ~3.5 million +- **Input Size:** 224x224x3 +- **Training Dataset:** ImageNet (1.2M images, 1000 classes) +- **Top-1 Accuracy:** ~71.8% on ImageNet validation set +- **Top-5 Accuracy:** ~90.8% on ImageNet validation set +- **Inference Speed:** ~30-50ms per image (CPU) + +--- + +## ๐Ÿ”ฎ Future Enhancements + +- [ ] Add custom model training capability +- [ ] Support for video classification +- [ ] Batch processing for multiple images +- [ ] Export predictions to CSV/JSON +- [ ] Confidence threshold filtering +- [ ] Model selection (VGG, ResNet, EfficientNet) +- [ ] Image augmentation preview +- [ ] Deployment to cloud (Heroku, AWS, GCP) +- [ ] Mobile app version +- [ ] API endpoint creation + +--- + +## ๐Ÿ› Troubleshooting + +**Issue:** Model download fails +- **Solution:** Check internet connection, try again, or manually download weights + +**Issue:** Out of memory error +- **Solution:** Close other applications, use smaller batch size, or upgrade RAM + +**Issue:** Slow predictions +- **Solution:** Use GPU if available, or consider using MobileNetV2 Alpha=0.5 for faster inference + +**Issue:** Incorrect predictions +- **Solution:** Ensure good image quality, proper lighting, and clear object visibility + +--- + +## ๐Ÿ“š Learning Resources + +- [TensorFlow Documentation](https://www.tensorflow.org/api_docs) +- [MobileNetV2 Paper](https://arxiv.org/abs/1801.04381) +- [Transfer Learning Guide](https://www.tensorflow.org/tutorials/images/transfer_learning) +- [ImageNet Dataset](https://www.image-net.org/) +- [Streamlit Documentation](https://docs.streamlit.io/) + +--- + +## ๐Ÿค Contributing + +Contributions are welcome! Feel free to: +- Add new features +- Improve model performance +- Enhance UI/UX +- Fix bugs +- Add documentation + +--- + +## ๐Ÿ“„ License + +This project is created for **Hacktoberfest 2025** and educational purposes. + +--- + +## ๐Ÿ™ Acknowledgments + +- **TensorFlow Team** - For the amazing deep learning framework +- **Google** - For MobileNetV2 architecture +- **ImageNet** - For the comprehensive dataset +- **Streamlit** - For the intuitive web framework +- **Hacktoberfest 2025** - For promoting open source + +--- + +## ๐Ÿ“ง Contact + +Created by **vatsalgupta2004** for Hacktoberfest 2025 + +- GitHub: [@vatsalgupta2004](https://github.com/vatsalgupta2004) +- Project: [ProjectHive](https://github.com/vatsalgupta2004/ProjectHive) + +--- + +**โญ If you find this project helpful, please give it a star!** diff --git a/Domains/AI-ML/MiniProjects/ImageClassifier/app.py b/Domains/AI-ML/MiniProjects/ImageClassifier/app.py new file mode 100644 index 00000000..66a5d26a --- /dev/null +++ b/Domains/AI-ML/MiniProjects/ImageClassifier/app.py @@ -0,0 +1,205 @@ +""" +Image Classifier Web Application +Author: vatsalgupta2004 +Description: Streamlit web interface for image classification using Transfer Learning +""" + +import streamlit as st +from PIL import Image +import time +from classifier import ImageClassifier, format_confidence, get_color_for_confidence + +# Page configuration +st.set_page_config( + page_title="AI Image Classifier", + page_icon="๐Ÿ–ผ๏ธ", + layout="wide", + initial_sidebar_state="expanded" +) + +# Custom CSS for better styling +st.markdown(""" + +""", unsafe_allow_html=True) + +# Initialize session state for model +@st.cache_resource +def load_model(): + """Load and cache the classification model""" + return ImageClassifier() + +def main(): + # Header + st.markdown("

๐Ÿ–ผ๏ธ AI Image Classifier

", unsafe_allow_html=True) + st.markdown("

Powered by Transfer Learning & MobileNetV2

", unsafe_allow_html=True) + st.markdown("---") + + # Sidebar + with st.sidebar: + st.header("๐Ÿ“Š About") + st.info(""" + **Image Classifier** uses Transfer Learning with MobileNetV2 pre-trained on ImageNet. + + **Features:** + - ๐ŸŽฏ 1000+ object categories + - โšก Real-time predictions + - ๐Ÿ“ˆ Confidence scores + - ๐Ÿ–ผ๏ธ Easy image upload + """) + + st.header("๐Ÿ› ๏ธ Tech Stack") + st.markdown(""" + - **TensorFlow** - Deep Learning + - **Keras** - Neural Networks API + - **MobileNetV2** - CNN Model + - **Streamlit** - Web Framework + - **Pillow** - Image Processing + """) + + st.header("๐Ÿ“š How to Use") + st.markdown(""" + 1. **Upload** an image (JPG, PNG, JPEG) + 2. **Wait** for automatic processing + 3. **View** top 5 predictions + 4. **Check** confidence scores + """) + + st.header("๐Ÿ‘จโ€๐Ÿ’ป Developer") + st.markdown(""" + **Contributor:** vatsalgupta2004 + + **Hacktoberfest 2025** + + [GitHub](https://github.com/vatsalgupta2004) + """) + + # Main content + col1, col2 = st.columns([1, 1]) + + with col1: + st.header("๐Ÿ“ค Upload Image") + + # File uploader + uploaded_file = st.file_uploader( + "Choose an image...", + type=['jpg', 'jpeg', 'png'], + help="Upload a JPG, JPEG, or PNG image to classify" + ) + + if uploaded_file is not None: + # Display uploaded image + image = Image.open(uploaded_file) + st.image(image, caption='Uploaded Image', use_container_width=True) + + # Image info + st.caption(f"๐Ÿ“ Size: {image.size[0]} x {image.size[1]} pixels") + st.caption(f"๐Ÿ“ Format: {image.format}") + st.caption(f"๐ŸŽจ Mode: {image.mode}") + + with col2: + st.header("๐ŸŽฏ Predictions") + + if uploaded_file is not None: + # Show loading spinner + with st.spinner('๐Ÿ”„ Analyzing image...'): + try: + # Load model + classifier = load_model() + + # Reset file pointer + uploaded_file.seek(0) + + # Make prediction + start_time = time.time() + predictions = classifier.predict_from_file(uploaded_file, top_k=5) + inference_time = time.time() - start_time + + # Success message + st.success(f"โœ… Classification complete! ({inference_time:.2f}s)") + + # Display predictions + st.subheader("๐Ÿ† Top 5 Predictions") + + for idx, (class_id, class_name, confidence) in enumerate(predictions, 1): + # Create expandable section for each prediction + with st.container(): + col_rank, col_name, col_conf = st.columns([0.5, 2, 2]) + + with col_rank: + # Rank emoji + rank_emoji = "๐Ÿฅ‡" if idx == 1 else "๐Ÿฅˆ" if idx == 2 else "๐Ÿฅ‰" if idx == 3 else f"{idx}๏ธโƒฃ" + st.markdown(f"

{rank_emoji}

", unsafe_allow_html=True) + + with col_name: + st.markdown(f"**{class_name}**") + st.caption(f"Class ID: {class_id}") + + with col_conf: + # Progress bar for confidence + st.progress(confidence / 100) + st.caption(format_confidence(confidence)) + + st.markdown("---") + + # Additional info + st.info(f""" + **๐Ÿ’ก Model Information** + - Architecture: MobileNetV2 + - Dataset: ImageNet (1000 classes) + - Inference Time: {inference_time:.3f} seconds + - Top Prediction: {predictions[0][1]} + - Confidence: {predictions[0][2]:.2f}% + """) + + except Exception as e: + st.error(f"โŒ Error during classification: {str(e)}") + st.error("Please try uploading a different image.") + else: + # Placeholder when no image is uploaded + st.info("๐Ÿ‘† Upload an image to see predictions here!") + + st.markdown("### ๐ŸŽจ Example Categories") + st.markdown(""" + Try images of: + - ๐Ÿ• **Animals:** Dogs, cats, birds, wildlife + - ๐Ÿš— **Vehicles:** Cars, planes, boats, bikes + - ๐Ÿ• **Food:** Pizza, burgers, fruits, desserts + - ๐Ÿ  **Objects:** Furniture, electronics, tools + - ๐ŸŒณ **Nature:** Flowers, trees, landscapes + - ๐ŸŽธ **Instruments:** Guitars, pianos, drums + - ๐Ÿˆ **Sports:** Balls, equipment, gear + - And 900+ more categories! + """) + + # Footer + st.markdown("---") + st.markdown(""" +
+

Made with โค๏ธ for Hacktoberfest 2025 by vatsalgupta2004

+

๐ŸŒŸ Powered by TensorFlow & MobileNetV2 | ๐Ÿš€ Built with Streamlit

+
+ """, unsafe_allow_html=True) + +if __name__ == "__main__": + main() diff --git a/Domains/AI-ML/MiniProjects/ImageClassifier/classifier.py b/Domains/AI-ML/MiniProjects/ImageClassifier/classifier.py new file mode 100644 index 00000000..b608f193 --- /dev/null +++ b/Domains/AI-ML/MiniProjects/ImageClassifier/classifier.py @@ -0,0 +1,164 @@ +""" +Image Classifier using Transfer Learning with MobileNetV2 +Author: vatsalgupta2004 +Description: Core classification logic for image prediction +""" + +import numpy as np +from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions +from tensorflow.keras.preprocessing import image +from PIL import Image +import io + +class ImageClassifier: + """ + Image Classifier using pre-trained MobileNetV2 model + """ + + def __init__(self): + """ + Initialize the classifier with MobileNetV2 model + """ + print("๐Ÿ”„ Loading MobileNetV2 model...") + # Load pre-trained MobileNetV2 model with ImageNet weights + self.model = MobileNetV2( + weights='imagenet', + include_top=True, # Include classification layer + input_shape=(224, 224, 3) + ) + print("โœ… Model loaded successfully!") + + def preprocess_image(self, img): + """ + Preprocess image for MobileNetV2 model + + Args: + img: PIL Image object + + Returns: + Preprocessed numpy array ready for prediction + """ + # Resize image to 224x224 (MobileNetV2 input size) + img = img.resize((224, 224)) + + # Convert to RGB if necessary (handle RGBA, grayscale, etc.) + if img.mode != 'RGB': + img = img.convert('RGB') + + # Convert to numpy array + img_array = image.img_to_array(img) + + # Add batch dimension (model expects batches) + img_array = np.expand_dims(img_array, axis=0) + + # Apply MobileNetV2-specific preprocessing (scales to [-1, 1]) + img_array = preprocess_input(img_array) + + return img_array + + def predict(self, img, top_k=5): + """ + Predict the class of an image + + Args: + img: PIL Image object + top_k: Number of top predictions to return + + Returns: + List of tuples (class_id, class_name, confidence) + """ + # Preprocess the image + processed_img = self.preprocess_image(img) + + # Make prediction + predictions = self.model.predict(processed_img, verbose=0) + + # Decode predictions to human-readable labels + decoded_predictions = decode_predictions(predictions, top=top_k)[0] + + # Format results: (class_id, class_name, confidence) + results = [] + for pred in decoded_predictions: + class_id = pred[0] + class_name = pred[1].replace('_', ' ').title() + confidence = float(pred[2]) * 100 # Convert to percentage + results.append((class_id, class_name, confidence)) + + return results + + def predict_from_file(self, image_file, top_k=5): + """ + Predict from uploaded file object + + Args: + image_file: File-like object (from Streamlit file uploader) + top_k: Number of top predictions to return + + Returns: + List of tuples (class_id, class_name, confidence) + """ + # Load image from file + img = Image.open(image_file) + + # Make prediction + return self.predict(img, top_k) + + def get_model_info(self): + """ + Get information about the loaded model + + Returns: + Dictionary with model information + """ + return { + 'model_name': 'MobileNetV2', + 'input_shape': (224, 224, 3), + 'parameters': self.model.count_params(), + 'layers': len(self.model.layers), + 'trainable_params': sum([np.prod(v.shape) for v in self.model.trainable_weights]), + 'non_trainable_params': sum([np.prod(v.shape) for v in self.model.non_trainable_weights]) + } + + +def format_confidence(confidence): + """ + Format confidence score for display + + Args: + confidence: Float confidence value (0-100) + + Returns: + Formatted string with confidence + """ + if confidence >= 90: + emoji = "๐ŸŸข" + label = "Very High" + elif confidence >= 70: + emoji = "๐ŸŸก" + label = "High" + elif confidence >= 50: + emoji = "๐ŸŸ " + label = "Medium" + else: + emoji = "๐Ÿ”ด" + label = "Low" + + return f"{emoji} {confidence:.2f}% ({label} Confidence)" + + +def get_color_for_confidence(confidence): + """ + Get color code based on confidence level + + Args: + confidence: Float confidence value (0-100) + + Returns: + Color name for Streamlit + """ + if confidence >= 70: + return "green" + elif confidence >= 50: + return "orange" + else: + return "red" diff --git a/Domains/AI-ML/MiniProjects/ImageClassifier/requirements.txt b/Domains/AI-ML/MiniProjects/ImageClassifier/requirements.txt new file mode 100644 index 00000000..8ea5d938 --- /dev/null +++ b/Domains/AI-ML/MiniProjects/ImageClassifier/requirements.txt @@ -0,0 +1,17 @@ +# Image Classifier - Python Dependencies + +# Deep Learning Framework +tensorflow>=2.13.0,<2.16.0 +keras>=2.13.0 + +# Image Processing +Pillow>=10.0.0 + +# Web Framework +streamlit>=1.28.0 + +# Numerical Computing +numpy>=1.24.0,<2.0.0 + +# Additional Utilities +protobuf>=3.20.0,<4.0.0 diff --git a/Domains/AI-ML/MiniProjects/ImageClassifier/test_setup.py b/Domains/AI-ML/MiniProjects/ImageClassifier/test_setup.py new file mode 100644 index 00000000..1baad414 --- /dev/null +++ b/Domains/AI-ML/MiniProjects/ImageClassifier/test_setup.py @@ -0,0 +1,114 @@ +""" +Test script to verify the Image Classifier setup +Author: vatsalgupta2004 +""" + +def test_imports(): + """Test if all required packages can be imported""" + print("๐Ÿ” Testing imports...") + + try: + import tensorflow as tf + print(f"โœ… TensorFlow {tf.__version__} imported successfully") + except ImportError as e: + print(f"โŒ TensorFlow import failed: {e}") + return False + + try: + import streamlit as st + print(f"โœ… Streamlit imported successfully") + except ImportError as e: + print(f"โŒ Streamlit import failed: {e}") + return False + + try: + from PIL import Image + print(f"โœ… Pillow imported successfully") + except ImportError as e: + print(f"โŒ Pillow import failed: {e}") + return False + + try: + import numpy as np + print(f"โœ… NumPy {np.__version__} imported successfully") + except ImportError as e: + print(f"โŒ NumPy import failed: {e}") + return False + + return True + + +def test_model_loading(): + """Test if MobileNetV2 model can be loaded""" + print("\n๐Ÿ” Testing model loading...") + + try: + from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2 + + print("๐Ÿ“ฅ Loading MobileNetV2 model (this may take a moment)...") + model = MobileNetV2(weights='imagenet', include_top=True) + print(f"โœ… Model loaded successfully!") + print(f"๐Ÿ“Š Model has {model.count_params():,} parameters") + print(f"๐Ÿ“Š Model has {len(model.layers)} layers") + + return True + except Exception as e: + print(f"โŒ Model loading failed: {e}") + return False + + +def test_classifier(): + """Test the ImageClassifier class""" + print("\n๐Ÿ” Testing ImageClassifier class...") + + try: + from classifier import ImageClassifier + + print("๐Ÿ“ฅ Initializing classifier...") + classifier = ImageClassifier() + print("โœ… Classifier initialized successfully!") + + # Get model info + info = classifier.get_model_info() + print(f"๐Ÿ“Š Model Name: {info['model_name']}") + print(f"๐Ÿ“Š Input Shape: {info['input_shape']}") + print(f"๐Ÿ“Š Total Parameters: {info['parameters']:,}") + + return True + except Exception as e: + print(f"โŒ Classifier test failed: {e}") + return False + + +def main(): + """Run all tests""" + print("=" * 60) + print("๐Ÿงช Image Classifier - Setup Verification Test") + print("=" * 60) + + # Test imports + if not test_imports(): + print("\nโŒ Import test failed. Please install requirements:") + print(" pip install -r requirements.txt") + return + + # Test model loading + if not test_model_loading(): + print("\nโŒ Model loading test failed. Check internet connection.") + return + + # Test classifier + if not test_classifier(): + print("\nโŒ Classifier test failed. Check classifier.py file.") + return + + print("\n" + "=" * 60) + print("โœ… All tests passed! Your Image Classifier is ready to use!") + print("=" * 60) + print("\n๐Ÿš€ To run the app, execute:") + print(" streamlit run app.py") + print("\n๐Ÿ“š For more information, see README.md") + + +if __name__ == "__main__": + main()