TwoDClassifier
This github is a model that uses pretrained deeplearning network or other CV algorithm to provide a MCP server. Model can use this to quickly distinguish 2D material properties such as thickness. The neural network part is not open source yet.
Ask AI about TwoDClassifier
Powered by Claude Β· Grounded in docs
I know everything about TwoDClassifier. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
2D Material Classifier π§¬
A clean, modern deep learning framework for 2D material classification, extracted and refactored from the CC_v12 project. Supports classification of various 2D materials including graphene, hBN (hexagonal boron nitride), and other layered materials.
π Quick Start
Installation
# Clone or download this project
cd twoDClassifier
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
Basic Usage
from src.model_loader import load_graphene_model
# Load a pretrained model (supports various 2D materials)
classifier = load_graphene_model('hBN_monolayer') # or 'graphene_1', 'hBN', etc.
# Make prediction on an image
prediction = classifier.predict_single_image('path/to/image.jpg')
print(f"Prediction: {'Good' if prediction == 1 else 'Bad'}")
# Get probabilities
probs = classifier.predict_single_image('path/to/image.jpg', return_probabilities=True)
print(f"Good probability: {probs[0][1]:.3f}")
Run Examples
# Command line example
python examples/basic_usage.py
# GUI Application
python examples/gui_app.py
π Project Structure
twoDClassifier/
βββ models/ # Pretrained models for various 2D materials
β βββ graphene_1/
β β βββ trained_model.json
β β βββ trained_model.h5
β βββ graphene_2/
β β βββ trained_model.json
β β βββ trained_model.h5
β βββ hBN/
β β βββ trained_model.json
β β βββ trained_model.h5
β βββ hBN_monolayer/
β β βββ trained_model.json
β β βββ trained_model.h5
β βββ [other 2D material models...]
βββ src/ # Source code
β βββ __init__.py
β βββ model_loader.py # Model loading utilities
β βββ image_utils.py # Image preprocessing
βββ examples/ # Usage examples and demos
β βββ basic_usage.py # Command-line usage example
β βββ gui_app.py # GUI testing application
β βββ test_mcp_simple.py # MCP server testing
β βββ mcp_client_example.py # MCP client example
βββ data/ # Sample test images (uploaded images stored here)
βββ GUI_USAGE.md # GUI usage guide
βββ mcp_http_server.py # HTTP/REST MCP server for web clients
βββ mcp_fastmcp_server.py # FastMCP server (HTTP + stdio transport, 88 lines)
βββ mcp_fastmcp_stdio_server.py # FastMCP stdio-only server (Claude Desktop)
βββ start_server.py # Unified server launcher with port fallback
βββ start_http_server.py # HTTP server launcher with port fallback
βββ start_fastmcp_server.py # FastMCP HTTP server launcher with port fallback
βββ claude_desktop_config.json # Claude Desktop configuration example
βββ MCP_USAGE.md # HTTP MCP server documentation
βββ todo.md # Development planning document
βββ requirements.txt
βββ README.md
π§ Model Architecture
All pretrained models use CNN architectures optimized for 2D material classification:
Standard Architecture (used across material types):
- Input: RGB images (flexible size, default 100x100)
- 4 Convolutional layers with max pooling
- Filters: 32 β 64 β 128 β 256
- Global max pooling + dropout
- Binary classification output
Key Features:
- Automatic image preprocessing (center crop + resize)
- Class balancing support
- TensorFlow 2.x compatible
- Clean, modular code structure
- GUI testing interface for easy model/image testing
- Multiple model support (9 pretrained models available)
- Sample data and examples for immediate testing
π Model Performance
These models were trained on 2D material microscopy images to classify flake quality across different materials (graphene, hBN, etc.):
- Class 0: Bad/poor quality flakes
- Class 1: Good/high quality flakes
π₯οΈ GUI Application
For easy testing and demonstration, use the included GUI:
python gui_app.py
GUI Features:
- Image Selection: Upload your own images or use existing ones in
data/folder - Model Selection: Pick from 9 available models (graphene, hBN variants)
- Real-time Prediction: Instant results with confidence scores
- Visual Interface: Image preview and color-coded results
- Model Comparison: Easy switching between different models
See GUI_USAGE.md for detailed instructions.
π MCP Server (Remote Access & Claude Desktop)
The project includes dual MCP server support for maximum compatibility:
Server Options
1. HTTP/REST Server (mcp_http_server.py) - For web clients and API access:
# Install HTTP server dependencies
pip install fastapi 'uvicorn[standard]' python-multipart httpx
# Start HTTP server (default: localhost:8000)
python mcp_http_server.py
# Custom IP and port for remote access
python mcp_http_server.py --host 0.0.0.0 --port 8001
2. FastMCP Server (mcp_fastmcp_server.py) - For MCP clients (β 70% less code):
# Install FastMCP dependencies
pip install fastmcp tensorflow opencv-python pillow numpy
# Start HTTP server (default: localhost:8000 with port fallback)
python mcp_fastmcp_server.py
# Custom configuration
python mcp_fastmcp_server.py --host 0.0.0.0 --port 8001
# For stdio transport (Claude Desktop)
python mcp_fastmcp_server.py --transport stdio
# OR use dedicated stdio server
python mcp_fastmcp_stdio_server.py
Why Two Servers?
- HTTP Server: Perfect for web applications, remote API access, production deployments
- FastMCP Server: Seamless MCP client integration with compact, clean code
- Both share the same model logic: No duplication, consistent results
Available MCP Tools (Both Servers)
upload_image- Upload images for classification (supports up to 16MB files)list_models- Get available model list (9 models)predict_flake_quality- Run quality predictions with confidence scoresget_prediction_history- Access prediction history
Usage Examples
HTTP Client (Web/API):
import requests, base64
server = "http://localhost:8000" # or remote IP
# Upload and analyze
with open("image.jpg", "rb") as f:
data = {"image_data": base64.b64encode(f.read()).decode(), "filename": "image.jpg"}
upload = requests.post(f"{server}/mcp/tools/upload_image", data=data)
prediction = requests.post(f"{server}/mcp/tools/predict_flake_quality",
data={"model_name": "hBN_monolayer", "image_filename": upload.json()["filename"]})
print(f"Quality: {prediction.json()['quality']}")
MCP Client Integration:
HTTP clients (web/API):
import requests
response = requests.get("http://localhost:8000/mcp/tools/list_models")
Claude Desktop (stdio):
- Configure client with full path to
mcp_fastmcp_stdio_server.py - Chat with AI: "What 2D material models are available?"
- Upload images: "Can you analyze this graphene flake for quality?"
Code Comparison
| Feature | HTTP Server | FastMCP Server |
|---|---|---|
| Lines of Code | 288 lines | 88 lines β |
| Setup Complexity | Manual FastAPI setup | Decorator-based β |
| Protocol Handling | Manual JSON-RPC | Automatic β |
| Transport Support | HTTP only | HTTP + stdio β |
| MCP Clients | β Not compatible | β Native support |
| Web/API Clients | β Perfect | β HTTP mode β |
| Remote Access | β Network ready | β HTTP mode β |
Documentation:
MCP_USAGE.md- HTTP server API reference
π οΈ Advanced Usage
Custom Preprocessing
from src.image_utils import CenterCrop
from PIL import Image
import numpy as np
# Load and preprocess image manually
image = Image.open('image.jpg')
transform = CenterCrop(crop_size=float('inf'), target_size=100)
processed_image = transform(image)
image_array = np.array(processed_image)
# Make prediction
prediction = classifier.predict(image_array)
Batch Prediction
# Process multiple images at once
image_batch = np.stack([image1, image2, image3]) # Shape: (3, height, width, 3)
predictions = classifier.predict(image_batch)
Model Information
# Get detailed model information
info = classifier.get_model_info()
print(f"Input shape: {info['input_shape']}")
print(f"Trainable parameters: {info['trainable_params']}")
π Requirements
- Python 3.8-3.10
- TensorFlow 2.8+
- OpenCV
- Pillow
- NumPy
- Tkinter (included with Python - for GUI)
π― Use Cases
This framework is ideal for:
- Research: 2D material quality assessment (graphene, hBN, transition metal dichalcogenides, etc.)
- Industrial: Automated quality control in materials manufacturing
- Educational: Deep learning demonstrations and materials science teaching
- Development: Rapid prototyping of material classification systems
- Analysis: Batch processing of microscopy images
π§ Troubleshooting
Common Issues
- Model loading errors: Ensure both
.jsonand.h5files are present - Image size issues: Models automatically handle different input sizes
- Memory errors: Process images in smaller batches
- TensorFlow warnings: These are usually safe to ignore
Performance Tips
- Use batch processing for multiple images
- Consider image size vs. accuracy tradeoffs
- GPU acceleration works automatically if CUDA is available
π Current Status & Next Phase
Phase 1 - Completed:
- β Multi-material 2D classification framework (graphene, hBN, etc.)
- β Clean, modular codebase with 9 pretrained models
- β Command-line interface and comprehensive examples
- β GUI application for easy testing and demonstration
- β Sample data and complete documentation
Phase 2 - Completed:
- β Dual MCP server architecture supporting both web and MCP clients
- β HTTP/REST server (288 lines) for web applications and remote API access
- β FastMCP server (88 lines) with HTTP + stdio transport support
- β Unified server launcher with automatic port fallback
- β Shared model logic - both servers use identical classification algorithms
- β Network-accessible service with configurable IP/port binding
- β Production-ready architecture with comprehensive documentation
Phase 3 - Completed:
- β
Project organization - moved examples to
examples/directory - β Code cleanup - removed outdated config and test files
- β Documentation updates - reflects current project structure
- β Server launcher scripts - multiple options for easy deployment
Ready for Phase 4+: Advanced authentication, custom model training, production scaling, and enterprise deployment features.
π€ Contributing
This project was extracted and cleaned from the original CC_v12 codebase. The neural network architectures and preprocessing methods have been preserved while creating a more maintainable structure.
π License
Extracted from CC_v12 project - check original project for licensing information.
π References
- Original CC_v12 project for microscopy automation
- TensorFlow/Keras documentation
- Materials science research on 2D material characterization
