DermaAI - Skin Disease Classification Model
A deep learning model for classifying skin diseases using computer vision. This model can identify 5 different skin conditions with confidence scores and medical recommendations.
π₯ Supported Skin Conditions
The model can classify the following skin diseases:
- Atopic Dermatitis - A chronic inflammatory skin condition
- Eczema - Inflammatory skin condition causing red, itchy patches
- Psoriasis - Autoimmune condition causing scaly skin patches
- Seborrheic Keratoses - Common benign skin growths
- Tinea Ringworm Candidiasis - Fungal skin infections
π§ Model Details
- Model Type: Keras/TensorFlow model based on EfficientNetV2
- Task: Image Classification (Multi-class)
- Domain: Medical/Dermatology
- Framework: TensorFlow/Keras
- Input Size: 224x224x3 (RGB images)
- Output: 5-class probability distribution
- Preprocessing: EfficientNetV2 preprocessing
π Quick Start
Basic Usage
import tensorflow as tf
from huggingface_hub import hf_hub_download
import numpy as np
from PIL import Image
from tensorflow.keras.applications.efficientnet_v2 import preprocess_input
# Download and load the model
model_path = hf_hub_download(repo_id="Siraja704/DermaAI", filename="DermaAI.keras")
model = tf.keras.models.load_model(model_path)
# Class names
class_names = [
'Atopic Dermatitis',
'Eczema',
'Psoriasis',
'Seborrheic Keratoses',
'Tinea Ringworm Candidiasis'
]
# Prediction function
def predict_skin_condition(image_path):
# Load and preprocess image
image = Image.open(image_path).convert('RGB')
image = image.resize((224, 224))
image_array = np.array(image)
image_array = preprocess_input(image_array)
image_array = np.expand_dims(image_array, axis=0)
# Make prediction
predictions = model.predict(image_array)
predicted_class_index = np.argmax(predictions[0])
predicted_class = class_names[predicted_class_index]
confidence = predictions[0][predicted_class_index] * 100
return predicted_class, confidence
# Example usage
prediction, confidence = predict_skin_condition("path/to/your/image.jpg")
print(f"Prediction: {prediction} ({confidence:.2f}% confidence)")
π Flask API Usage
Create a complete web API for skin disease classification:
1. Install Dependencies
pip install flask numpy tensorflow pillow flask-cors huggingface-hub
2. Create Flask Application (app.py
)
from flask import Flask, request, jsonify
import numpy as np
import tensorflow as tf
import base64
import io
from PIL import Image
from flask_cors import CORS
from tensorflow.keras.applications.efficientnet_v2 import preprocess_input
from huggingface_hub import hf_hub_download
app = Flask(__name__)
CORS(app)
# Download and load the model from Hugging Face
print("Downloading model from Hugging Face...")
model_path = hf_hub_download(repo_id="Siraja704/DermaAI", filename="DermaAI.keras")
model = tf.keras.models.load_model(model_path)
print("β
Model loaded successfully!")
# Class names
class_names = [
'Atopic Dermatitis',
'Eczema',
'Psoriasis',
'Seborrheic Keratoses',
'Tinea Ringworm Candidiasis'
]
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.json
if not data or 'image' not in data:
return jsonify({'error': 'No image data provided'}), 400
# Process base64 image
image_data = data['image']
if 'base64,' in image_data:
image_data = image_data.split('base64,')[1]
# Decode and preprocess image
decoded_image = base64.b64decode(image_data)
image = Image.open(io.BytesIO(decoded_image)).convert('RGB')
image = image.resize((224, 224))
image_array = np.array(image)
image_array = preprocess_input(image_array)
image_array = np.expand_dims(image_array, axis=0)
# Make prediction
predictions = model.predict(image_array)
predicted_class_index = int(np.argmax(predictions[0]))
predicted_class = class_names[predicted_class_index]
confidence = float(predictions[0][predicted_class_index] * 100)
# Get top alternatives
top_indices = np.argsort(predictions[0])[-3:][::-1]
top_predictions = [
{
'class': class_names[i],
'confidence': float(predictions[0][i] * 100)
}
for i in top_indices if i != predicted_class_index
]
# Generate medical recommendation
if confidence < 10:
recommendation = "Very low confidence. Please retake image with better lighting and focus."
elif confidence < 30:
recommendation = "Low confidence. Preliminary result only. Consult a dermatologist."
elif confidence < 60:
recommendation = "Moderate confidence. Consider alternatives and consult healthcare professional."
else:
recommendation = "High confidence prediction. Always consult healthcare professional for confirmation."
return jsonify({
'prediction': predicted_class,
'confidence': round(confidence, 2),
'all_confidences': {
class_names[i]: float(pred * 100) for i, pred in enumerate(predictions[0])
},
'top_alternatives': top_predictions,
'recommendation': recommendation
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/health', methods=['GET'])
def health():
return jsonify({'status': 'healthy', 'model_loaded': True})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=True)
3. Run the API
python app.py
The API will be available at http://localhost:5001
4. API Usage Examples
Python Client:
import requests
import base64
def predict_image(image_path, api_url="http://localhost:5001/predict"):
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
data = {"image": f"data:image/jpeg;base64,{encoded_string}"}
response = requests.post(api_url, json=data)
return response.json()
# Usage
result = predict_image("skin_image.jpg")
print(f"Prediction: {result['prediction']} ({result['confidence']}%)")
JavaScript Client:
async function predictSkinCondition(imageFile) {
const base64 = await new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(imageFile);
});
const response = await fetch('http://localhost:5001/predict', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({image: base64})
});
return await response.json();
}
cURL:
curl -X POST http://localhost:5001/predict \
-H "Content-Type: application/json" \
-d '{"image": "data:image/jpeg;base64,YOUR_BASE64_IMAGE_HERE"}'
π API Response Format
{
"prediction": "Eczema",
"confidence": 85.23,
"all_confidences": {
"Atopic Dermatitis": 12.45,
"Eczema": 85.23,
"Psoriasis": 1.32,
"Seborrheic Keratoses": 0.67,
"Tinea Ringworm Candidiasis": 0.33
},
"top_alternatives": [
{
"class": "Atopic Dermatitis",
"confidence": 12.45
}
],
"recommendation": "High confidence prediction. Always consult healthcare professional for confirmation."
}
πΌοΈ Image Requirements
- Formats: JPG, PNG, WebP, and other common formats
- Size: Automatically resized to 224x224 pixels
- Quality: High-resolution images with good lighting work best
- Focus: Ensure affected skin area is clearly visible
π³ Docker Deployment
Dockerfile:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY app.py .
EXPOSE 5001
CMD ["python", "app.py"]
Requirements.txt:
flask>=2.0.0
numpy>=1.21.0
tensorflow>=2.13.0
pillow>=9.0.0
flask-cors>=3.0.0
huggingface-hub>=0.20.0
Build and Run:
docker build -t dermaai-api .
docker run -p 5001:5001 dermaai-api
βοΈ Important Medical Disclaimer
This model is for educational and research purposes only. It should NOT be used as a substitute for professional medical diagnosis or treatment. Always consult qualified healthcare professionals for proper medical evaluation and treatment of skin conditions.
π Performance Notes
- Input: 224x224 RGB images
- Preprocessing: EfficientNetV2 normalization
- Architecture: Based on EfficientNetV2
- Classes: 5 skin disease categories
- Confidence Levels:
- Low: < 30% (requires professional consultation)
- Moderate: 30-60% (consider alternatives)
- High: > 60% (still requires medical confirmation)
π€ Citation
If you use this model in your research or applications, please cite appropriately:
@misc{dermaai2024,
title={DermaAI: Deep Learning Model for Skin Disease Classification},
author={Siraja704},
year={2024},
publisher={Hugging Face},
url={https://huggingface.co/Siraja704/DermaAI}
}
π License
Licensed under the Apache 2.0 License. See the LICENSE file for details.
π Links
- Model Repository: Siraja704/DermaAI
- Framework: TensorFlow
- Base Architecture: EfficientNetV2
- Downloads last month
- 31