Spaces:
Runtime error
Runtime error
Added new files with .gitignore
Browse files- .gitignore +1 -0
- .streamlit/secrets.toml +2 -0
- app.py +154 -0
- requirements +7 -0
.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
.streamlit/secrets.toml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[gemini]
|
| 2 |
+
api_key = "AIzaSyBavKv_J522lZkirjVMx5WH-cXvPylddMY"
|
app.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Ci-Dave from BSCS-AI
|
| 2 |
+
# Description: This Python script creates a Streamlit web application for image analysis using computer vision techniques and AI-generated explanations.
|
| 3 |
+
# The app allows users to upload an image, apply edge detection, segmentation, feature extraction, and AI classification.
|
| 4 |
+
# The explanations for each technique are generated using the Gemini API for AI-generated content.
|
| 5 |
+
|
| 6 |
+
import streamlit as st # Streamlit library to create the web interface
|
| 7 |
+
import numpy as np # Library for numerical operations
|
| 8 |
+
import google.generativeai as genai # Gemini API for AI-generated explanations
|
| 9 |
+
|
| 10 |
+
# Random Forest and Logistic Regression model for classification
|
| 11 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 12 |
+
from sklearn.linear_model import LogisticRegression
|
| 13 |
+
|
| 14 |
+
from skimage.filters import sobel # Sobel edge detection filter from skimage
|
| 15 |
+
from skimage.segmentation import watershed # Watershed segmentation method
|
| 16 |
+
from skimage.feature import canny, hog # Canny edge detection and HOG feature extraction
|
| 17 |
+
from skimage.color import rgb2gray # Convert RGB images to grayscale
|
| 18 |
+
|
| 19 |
+
from skimage import io # I/O functions for reading images
|
| 20 |
+
from sklearn.preprocessing import StandardScaler # Standardization of image data
|
| 21 |
+
|
| 22 |
+
# Load Gemini API key from Streamlit Secrets configuration
|
| 23 |
+
api_key = st.secrets["gemini"]["api_key"] # Get API key from Streamlit secrets
|
| 24 |
+
genai.configure(api_key=api_key) # Configure the Gemini API with the API key
|
| 25 |
+
|
| 26 |
+
MODEL_ID = "gemini-1.5-flash" # Specify the model ID for Gemini
|
| 27 |
+
gen_model = genai.GenerativeModel(MODEL_ID) # Initialize the Gemini model
|
| 28 |
+
|
| 29 |
+
# Function to generate explanations using the Gemini API
|
| 30 |
+
def explain_ai(prompt):
|
| 31 |
+
"""Generate an explanation using Gemini API with error handling."""
|
| 32 |
+
try:
|
| 33 |
+
response = gen_model.generate_content(prompt) # Get AI-generated content based on prompt
|
| 34 |
+
return response.text # Return the explanation text
|
| 35 |
+
except Exception as e:
|
| 36 |
+
return f"Error: {str(e)}" # Return error message if there's an issue
|
| 37 |
+
|
| 38 |
+
# App title
|
| 39 |
+
st.title("Imaize: Smart Image Analyzer with XAI")
|
| 40 |
+
|
| 41 |
+
# Image upload section
|
| 42 |
+
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"]) # Allow user to upload an image file
|
| 43 |
+
|
| 44 |
+
# App Description
|
| 45 |
+
st.markdown("""
|
| 46 |
+
This app combines AI-powered image analysis techniques with an easy-to-use interface for explanation generation.
|
| 47 |
+
It leverages advanced computer vision algorithms such as **edge detection**, **image segmentation**, and **feature extraction**.
|
| 48 |
+
Additionally, the app provides **explanations** for each method used, powered by the Gemini API, to make the process more understandable.
|
| 49 |
+
|
| 50 |
+
The main functionalities of the app include:
|
| 51 |
+
- **Edge Detection**: Choose between the Canny and Sobel edge detection methods.
|
| 52 |
+
- **Segmentation**: Apply Watershed or Thresholding methods to segment images.
|
| 53 |
+
- **Feature Extraction**: Extract Histogram of Oriented Gradients (HOG) features from images.
|
| 54 |
+
- **AI Classification**: Classify images using Random Forest or Logistic Regression models.
|
| 55 |
+
|
| 56 |
+
Whether you're exploring computer vision or simply curious about how these techniques work, this app will guide you through the process with easy-to-understand explanations.
|
| 57 |
+
""")
|
| 58 |
+
|
| 59 |
+
# Instructions on how to use the app
|
| 60 |
+
st.markdown("""
|
| 61 |
+
### How to Use the App:
|
| 62 |
+
|
| 63 |
+
1. **Upload an Image**: Click on the "Upload an image" button to upload an image (in JPG, PNG, or JPEG format) for analysis.
|
| 64 |
+
2. **Select Edge Detection**: Choose between **Canny** or **Sobel** edge detection methods. The app will process the image and display the result.
|
| 65 |
+
3. **Apply Segmentation**: Select **Watershed** or **Thresholding** segmentation. You can also adjust the threshold for thresholding segmentation.
|
| 66 |
+
4. **Extract HOG Features**: Visualize the HOG (Histogram of Oriented Gradients) features from the image.
|
| 67 |
+
5. **Choose AI Model for Classification**: Select either **Random Forest** or **Logistic Regression** to classify the image based on pixel information.
|
| 68 |
+
6. **Read the Explanations**: For each technique, you'll find a detailed explanation of how it works, powered by AI. Simply read the generated explanation to understand the underlying processes.
|
| 69 |
+
|
| 70 |
+
### Enjoy exploring and understanding image analysis techniques with AI!
|
| 71 |
+
""")
|
| 72 |
+
|
| 73 |
+
# If an image is uploaded, proceed with the analysis
|
| 74 |
+
if uploaded_file is not None:
|
| 75 |
+
image = io.imread(uploaded_file) # Read the uploaded image using skimage
|
| 76 |
+
if image.shape[-1] == 4: # If the image has 4 channels (RGBA), remove the alpha channel
|
| 77 |
+
image = image[:, :, :3]
|
| 78 |
+
|
| 79 |
+
gray = rgb2gray(image) # Convert the image to grayscale for processing
|
| 80 |
+
|
| 81 |
+
st.image(image, caption="Uploaded Image", use_container_width=True) # Display the uploaded image
|
| 82 |
+
|
| 83 |
+
# Edge Detection Section
|
| 84 |
+
st.subheader("Edge Detection") # Title for edge detection section
|
| 85 |
+
edge_method = st.selectbox("Select Edge Detection Method", ["Canny", "Sobel"], key="edge") # Select edge detection method
|
| 86 |
+
edges = canny(gray) if edge_method == "Canny" else sobel(gray) # Apply chosen edge detection method
|
| 87 |
+
edges = (edges * 255).astype(np.uint8) # Convert edge map to 8-bit image format
|
| 88 |
+
|
| 89 |
+
col1, col2 = st.columns([1, 1]) # Create two columns for layout
|
| 90 |
+
with col1:
|
| 91 |
+
st.image(edges, caption=f"{edge_method} Edge Detection", use_container_width=True) # Display the edge detection result
|
| 92 |
+
with col2:
|
| 93 |
+
st.write("### Explanation") # Show explanation header
|
| 94 |
+
explanation = explain_ai(f"Explain how {edge_method} edge detection works in computer vision.") # Get explanation from AI
|
| 95 |
+
st.text_area("Explanation", explanation, height=300) # Display explanation in a text area
|
| 96 |
+
|
| 97 |
+
# Segmentation Section
|
| 98 |
+
st.subheader("Segmentation") # Title for segmentation section
|
| 99 |
+
seg_method = st.selectbox("Select Segmentation Method", ["Watershed", "Thresholding"], key="seg") # Select segmentation method
|
| 100 |
+
|
| 101 |
+
# Perform segmentation based on chosen method
|
| 102 |
+
if seg_method == "Watershed":
|
| 103 |
+
elevation_map = sobel(gray) # Create elevation map using Sobel filter
|
| 104 |
+
markers = np.zeros_like(gray) # Initialize marker array
|
| 105 |
+
markers[gray < 0.3] = 1 # Mark low-intensity regions
|
| 106 |
+
markers[gray > 0.7] = 2 # Mark high-intensity regions
|
| 107 |
+
segmented = watershed(elevation_map, markers.astype(np.int32)) # Apply watershed segmentation
|
| 108 |
+
else:
|
| 109 |
+
threshold_value = st.slider("Choose threshold value", 0, 255, 127) # Slider to choose threshold value
|
| 110 |
+
segmented = (gray > (threshold_value / 255)).astype(np.uint8) * 255 # Apply thresholding segmentation
|
| 111 |
+
|
| 112 |
+
col1, col2 = st.columns([1, 1]) # Create two columns for layout
|
| 113 |
+
with col1:
|
| 114 |
+
st.image(segmented, caption=f"{seg_method} Segmentation", use_container_width=True) # Display segmentation result
|
| 115 |
+
with col2:
|
| 116 |
+
st.write("### Explanation") # Show explanation header
|
| 117 |
+
explanation = explain_ai(f"Explain how {seg_method} segmentation works in image processing.") # Get explanation from AI
|
| 118 |
+
st.text_area("Explanation", explanation, height=300) # Display explanation in a text area
|
| 119 |
+
|
| 120 |
+
# HOG Feature Extraction Section
|
| 121 |
+
st.subheader("HOG Feature Extraction") # Title for HOG feature extraction section
|
| 122 |
+
fd, hog_image = hog(gray, pixels_per_cell=(8, 8), cells_per_block=(2, 2), visualize=True) # Extract HOG features
|
| 123 |
+
|
| 124 |
+
col1, col2 = st.columns([1, 1]) # Create two columns for layout
|
| 125 |
+
with col1:
|
| 126 |
+
st.image(hog_image, caption="HOG Features", use_container_width=True) # Display HOG feature image
|
| 127 |
+
with col2:
|
| 128 |
+
st.write("### Explanation") # Show explanation header
|
| 129 |
+
explanation = explain_ai("Explain how Histogram of Oriented Gradients (HOG) feature extraction works.") # Get explanation from AI
|
| 130 |
+
st.text_area("Explanation", explanation, height=300) # Display explanation in a text area
|
| 131 |
+
|
| 132 |
+
# AI Classification Section
|
| 133 |
+
st.subheader("AI Classification") # Title for AI classification section
|
| 134 |
+
model_choice = st.selectbox("Select AI Model", ["Random Forest", "Logistic Regression"], key="model") # Select AI model for classification
|
| 135 |
+
|
| 136 |
+
flat_image = gray.flatten().reshape(-1, 1) # Flatten the grayscale image into a 1D array for classification
|
| 137 |
+
labels = (flat_image > 0.5).astype(int).flatten() # Generate binary labels based on intensity threshold
|
| 138 |
+
|
| 139 |
+
# Choose model (Random Forest or Logistic Regression)
|
| 140 |
+
ai_model = RandomForestClassifier(n_jobs=1) if model_choice == "Random Forest" else LogisticRegression() # Initialize the model
|
| 141 |
+
scaler = StandardScaler() # Standardize the image data for better classification
|
| 142 |
+
flat_image_scaled = scaler.fit_transform(flat_image) # Scale the image data
|
| 143 |
+
|
| 144 |
+
ai_model.fit(flat_image_scaled, labels) # Train the AI model on the image data
|
| 145 |
+
predictions = ai_model.predict(flat_image_scaled).reshape(gray.shape) # Make predictions on the image
|
| 146 |
+
predictions = (predictions * 255).astype(np.uint8) # Convert predictions to 8-bit image format
|
| 147 |
+
|
| 148 |
+
col1, col2 = st.columns([1, 1]) # Create two columns for layout
|
| 149 |
+
with col1:
|
| 150 |
+
st.image(predictions, caption=f"{model_choice} Pixel Classification", use_container_width=True) # Display classification result
|
| 151 |
+
with col2:
|
| 152 |
+
st.write("### Explanation") # Show explanation header
|
| 153 |
+
explanation = explain_ai(f"Explain how {model_choice} is used for image classification.") # Get explanation from AI
|
| 154 |
+
st.text_area("Explanation", explanation, height=300) # Display explanation in a text area
|
requirements
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
opencv-python
|
| 3 |
+
numpy
|
| 4 |
+
matplotlib
|
| 5 |
+
scikit-learn
|
| 6 |
+
scikit-image
|
| 7 |
+
google.generativeai
|