|
|
|
|
|
|
|
|
|
|
|
import streamlit as st |
|
import numpy as np |
|
import google.generativeai as genai |
|
|
|
|
|
from sklearn.ensemble import RandomForestClassifier |
|
from sklearn.linear_model import LogisticRegression |
|
|
|
from skimage.filters import sobel |
|
from skimage.segmentation import watershed |
|
from skimage.feature import canny, hog |
|
from skimage.color import rgb2gray |
|
|
|
from skimage import io |
|
from sklearn.preprocessing import StandardScaler |
|
|
|
|
|
api_key = st.secrets["gemini"]["api_key"] |
|
genai.configure(api_key=api_key) |
|
import numpy as np |
|
import google.generativeai as genai |
|
import matplotlib.pyplot as plt |
|
|
|
from sklearn.ensemble import RandomForestClassifier |
|
from sklearn.linear_model import LogisticRegression |
|
from skimage.filters import sobel |
|
from skimage.segmentation import watershed |
|
from skimage.feature import canny, hog |
|
from skimage.color import rgb2gray |
|
from skimage import io |
|
from sklearn.preprocessing import StandardScaler |
|
from sklearn.metrics import accuracy_score |
|
|
|
|
|
api_key = st.secrets["gemini"]["api_key"] |
|
genai.configure(api_key=api_key) |
|
MODEL_ID = "gemini-1.5-flash" |
|
gen_model = genai.GenerativeModel(MODEL_ID) |
|
|
|
def explain_ai(prompt): |
|
try: |
|
response = gen_model.generate_content(prompt) |
|
return response.text |
|
except Exception as e: |
|
return f"Error: {str(e)}" |
|
|
|
|
|
|
|
st.sidebar.title("Navigation") |
|
page = st.sidebar.radio("Go to", ["Home", "Edge Detection", "Segmentation", "Feature Extraction", "AI Classification"]) |
|
|
|
|
|
if page == "Home": |
|
uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"]) |
|
if uploaded_file is not None: |
|
image = io.imread(uploaded_file) |
|
if image.shape[-1] == 4: |
|
image = image[:, :, :3] |
|
gray = rgb2gray(image) |
|
st.image(image, caption="Uploaded Image", use_container_width=True) |
|
st.session_state["gray"] = gray |
|
|
|
|
|
elif page == "Edge Detection": |
|
st.title("Edge Detection") |
|
gray = st.session_state.get("gray") |
|
if gray is not None: |
|
edge_method = st.selectbox("Select Edge Detection Method", ["Canny", "Sobel"]) |
|
edges = canny(gray) if edge_method == "Canny" else sobel(gray) |
|
st.image(edges, caption=f"{edge_method} Edge Detection", use_container_width=True) |
|
st.text_area("Explanation", explain_ai(f"Explain how {edge_method} edge detection works in computer vision."), height=300) |
|
else: |
|
st.warning("Please upload an image on the Home page.") |
|
|
|
|
|
elif page == "Segmentation": |
|
st.title("Image Segmentation") |
|
gray = st.session_state.get("gray") |
|
if gray is not None: |
|
seg_method = st.selectbox("Select Segmentation Method", ["Watershed", "Thresholding"]) |
|
if seg_method == "Watershed": |
|
elevation_map = sobel(gray) |
|
markers = np.zeros_like(gray) |
|
markers[gray < 0.3] = 1 |
|
markers[gray > 0.7] = 2 |
|
segmented = watershed(elevation_map, markers.astype(np.int32)) |
|
else: |
|
threshold_value = st.slider("Choose threshold value", 0, 255, 127) |
|
segmented = (gray > (threshold_value / 255)).astype(np.uint8) * 255 |
|
st.image(segmented, caption=f"{seg_method} Segmentation", use_container_width=True) |
|
st.text_area("Explanation", explain_ai(f"Explain how {seg_method} segmentation works in image processing."), height=300) |
|
else: |
|
st.warning("Please upload an image on the Home page.") |
|
|
|
|
|
elif page == "Feature Extraction": |
|
st.title("HOG Feature Extraction") |
|
gray = st.session_state.get("gray") |
|
if gray is not None: |
|
fd, hog_image = hog(gray, pixels_per_cell=(8, 8), cells_per_block=(2, 2), visualize=True) |
|
st.image(hog_image, caption="HOG Features", use_container_width=True) |
|
st.text_area("Explanation", explain_ai("Explain how Histogram of Oriented Gradients (HOG) feature extraction works."), height=300) |
|
else: |
|
st.warning("Please upload an image on the Home page.") |
|
|
|
|
|
elif page == "AI Classification": |
|
st.title("AI Classification") |
|
gray = st.session_state.get("gray") |
|
if gray is not None: |
|
model_choice = st.selectbox("Select AI Model", ["Random Forest", "Logistic Regression"]) |
|
flat_image = gray.flatten().reshape(-1, 1) |
|
labels = (flat_image > 0.5).astype(int).flatten() |
|
ai_model = RandomForestClassifier(n_jobs=1) if model_choice == "Random Forest" else LogisticRegression() |
|
scaler = StandardScaler() |
|
flat_image_scaled = scaler.fit_transform(flat_image) |
|
ai_model.fit(flat_image_scaled, labels) |
|
predictions = ai_model.predict(flat_image_scaled).reshape(gray.shape) |
|
predictions = (predictions * 255).astype(np.uint8) |
|
accuracy = accuracy_score(labels, ai_model.predict(flat_image_scaled)) |
|
st.image(predictions, caption=f"{model_choice} Pixel Classification", use_container_width=True) |
|
st.text_area("Explanation", explain_ai(f"Explain how {model_choice} is used for image classification."), height=300) |
|
st.write(f"### Accuracy: {accuracy:.2f}") |
|
fig, ax = plt.subplots() |
|
ax.bar(["Accuracy"], [accuracy], color='blue') |
|
ax.set_ylim([0, 1]) |
|
st.pyplot(fig) |
|
else: |
|
st.warning("Please upload an image on the Home page.") |
|
|
|
|
|
MODEL_ID = "gemini-1.5-flash" |
|
gen_model = genai.GenerativeModel(MODEL_ID) |
|
|
|
|
|
def explain_ai(prompt): |
|
"""Generate an explanation using Gemini API with error handling.""" |
|
try: |
|
response = gen_model.generate_content(prompt) |
|
return response.text |
|
except Exception as e: |
|
return f"Error: {str(e)}" |
|
|
|
|
|
st.title("Imaize: Smart Image Analyzer with XAI") |
|
|
|
|
|
|
|
|
|
|
|
st.markdown(""" |
|
This app combines AI-powered image analysis techniques with an easy-to-use interface for explanation generation. |
|
It leverages advanced computer vision algorithms such as **edge detection**, **image segmentation**, and **feature extraction**. |
|
Additionally, the app provides **explanations** for each method used, powered by the Gemini API, to make the process more understandable. |
|
|
|
The main functionalities of the app include: |
|
- **Edge Detection**: Choose between the Canny and Sobel edge detection methods. |
|
- **Segmentation**: Apply Watershed or Thresholding methods to segment images. |
|
- **Feature Extraction**: Extract Histogram of Oriented Gradients (HOG) features from images. |
|
- **AI Classification**: Classify images using Random Forest or Logistic Regression models. |
|
|
|
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. |
|
""") |
|
|
|
|
|
st.markdown(""" |
|
### How to Use the App: |
|
|
|
1. **Upload an Image**: Click on the "Upload an image" button to upload an image (in JPG, PNG, or JPEG format) for analysis. |
|
2. **Select Edge Detection**: Choose between **Canny** or **Sobel** edge detection methods. The app will process the image and display the result. |
|
3. **Apply Segmentation**: Select **Watershed** or **Thresholding** segmentation. You can also adjust the threshold for thresholding segmentation. |
|
4. **Extract HOG Features**: Visualize the HOG (Histogram of Oriented Gradients) features from the image. |
|
5. **Choose AI Model for Classification**: Select either **Random Forest** or **Logistic Regression** to classify the image based on pixel information. |
|
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. |
|
|
|
### Enjoy exploring and understanding image analysis techniques with AI! |
|
""") |
|
|
|
|
|
if uploaded_file is not None: |
|
image = io.imread(uploaded_file) |
|
if image.shape[-1] == 4: |
|
image = image[:, :, :3] |
|
|
|
gray = rgb2gray(image) |
|
|
|
st.image(image, caption="Uploaded Image", use_container_width=True) |
|
|
|
|
|
st.subheader("Edge Detection") |
|
edge_method = st.selectbox("Select Edge Detection Method", ["Canny", "Sobel"], key="edge") |
|
edges = canny(gray) if edge_method == "Canny" else sobel(gray) |
|
edges = (edges * 255).astype(np.uint8) |
|
|
|
col1, col2 = st.columns([1, 1]) |
|
with col1: |
|
st.image(edges, caption=f"{edge_method} Edge Detection", use_container_width=True) |
|
with col2: |
|
explanation = explain_ai(f"Explain how {edge_method} edge detection works in computer vision.") |
|
st.text_area("Explanation", explanation, height=300) |
|
|
|
|
|
st.subheader("Segmentation") |
|
seg_method = st.selectbox("Select Segmentation Method", ["Watershed", "Thresholding"], key="seg") |
|
|
|
|
|
if seg_method == "Watershed": |
|
elevation_map = sobel(gray) |
|
markers = np.zeros_like(gray) |
|
markers[gray < 0.3] = 1 |
|
markers[gray > 0.7] = 2 |
|
segmented = watershed(elevation_map, markers.astype(np.int32)) |
|
else: |
|
threshold_value = st.slider("Choose threshold value", 0, 255, 127) |
|
segmented = (gray > (threshold_value / 255)).astype(np.uint8) * 255 |
|
|
|
col1, col2 = st.columns([1, 1]) |
|
with col1: |
|
st.image(segmented, caption=f"{seg_method} Segmentation", use_container_width=True) |
|
with col2: |
|
explanation = explain_ai(f"Explain how {seg_method} segmentation works in image processing.") |
|
st.text_area("Explanation", explanation, height=300) |
|
|
|
|
|
st.subheader("HOG Feature Extraction") |
|
fd, hog_image = hog(gray, pixels_per_cell=(8, 8), cells_per_block=(2, 2), visualize=True) |
|
|
|
col1, col2 = st.columns([1, 1]) |
|
with col1: |
|
st.image(hog_image, caption="HOG Features", use_container_width=True) |
|
with col2: |
|
explanation = explain_ai("Explain how Histogram of Oriented Gradients (HOG) feature extraction works.") |
|
st.text_area("Explanation", explanation, height=300) |
|
|
|
|
|
st.subheader("AI Classification") |
|
model_choice = st.selectbox("Select AI Model", ["Random Forest", "Logistic Regression"], key="model") |
|
|
|
flat_image = gray.flatten().reshape(-1, 1) |
|
labels = (flat_image > 0.5).astype(int).flatten() |
|
|
|
|
|
ai_model = RandomForestClassifier(n_jobs=1) if model_choice == "Random Forest" else LogisticRegression() |
|
scaler = StandardScaler() |
|
flat_image_scaled = scaler.fit_transform(flat_image) |
|
|
|
ai_model.fit(flat_image_scaled, labels) |
|
predictions = ai_model.predict(flat_image_scaled).reshape(gray.shape) |
|
predictions = (predictions * 255).astype(np.uint8) |
|
|
|
col1, col2 = st.columns([1, 1]) |
|
with col1: |
|
st.image(predictions, caption=f"{model_choice} Pixel Classification", use_container_width=True) |
|
with col2: |
|
explanation = explain_ai(f"Explain how {model_choice} is used for image classification.") |
|
st.text_area("Explanation", explanation, height=300) |
|
|