File size: 9,285 Bytes
8312ddd d28c822 3cf3c0d cd32abe 3cf3c0d cd32abe 3cf3c0d cd32abe 3cf3c0d cd32abe 3cf3c0d cd32abe 3cf3c0d cd32abe 3cf3c0d cd32abe 8f2167b cd32abe d28c822 3cf3c0d 8f2167b fc4ac67 cd32abe fc4ac67 d28c822 3cf3c0d cd32abe a0d6076 8f2167b a0d6076 3cf3c0d cd32abe 3cf3c0d cd32abe a0d6076 8f2167b 3cf3c0d a0d6076 cd32abe 8f2167b cd32abe 3cf3c0d 8f2167b cd32abe 8f2167b cd32abe 8f2167b cd32abe 8f2167b cd32abe c2460b3 fc4ac67 3cf3c0d fc4ac67 c2460b3 fc4ac67 3cf3c0d 8f2167b c2460b3 fc4ac67 c2460b3 fc4ac67 8f2167b c2460b3 fc4ac67 3cf3c0d cd32abe 3cf3c0d cd32abe c2460b3 cd32abe fc4ac67 a0d6076 fc4ac67 8f2167b c2460b3 fc4ac67 a0d6076 8f2167b fc4ac67 3cf3c0d 8f2167b fc4ac67 8f2167b fc4ac67 8f2167b c2460b3 cd32abe 8f2167b 8312ddd 3cf3c0d 8f2167b d28c822 8312ddd d28c822 8312ddd d28c822 8312ddd e9a9c89 8312ddd d28c822 8312ddd d28c822 8312ddd d28c822 8312ddd d28c822 8312ddd d28c822 8312ddd d28c822 8312ddd d28c822 8312ddd 8f2167b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
import cv2
import numpy as np
import pandas as pd
import gradio as gr
import matplotlib.pyplot as plt
from datetime import datetime
def detect_blood_cells(image):
"""Optimized function for blood cell detection"""
# Convert to RGB if grayscale
if len(image.shape) == 2:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
# Convert to HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
# Optimized red color ranges for blood cells
lower_red1 = np.array([0, 100, 100]) # Increased saturation threshold
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([160, 100, 100]) # Increased saturation threshold
upper_red2 = np.array([180, 255, 255])
# Create masks for red color
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
mask = mask1 + mask2
# Enhanced noise removal
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2)
# Apply distance transform to separate touching cells
dist_transform = cv2.distanceTransform(mask, cv2.DIST_L2, 5)
_, sure_fg = cv2.threshold(dist_transform, 0.5 * dist_transform.max(), 255, 0)
sure_fg = np.uint8(sure_fg)
# Find connected components
_, markers = cv2.connectedComponents(sure_fg)
# Find contours with hierarchy to handle nested contours
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Filter contours based on area and circularity
filtered_contours = []
for contour in contours:
area = cv2.contourArea(contour)
perimeter = cv2.arcLength(contour, True)
if perimeter == 0:
continue
circularity = 4 * np.pi * area / (perimeter * perimeter)
# Optimized thresholds for your specific images
if 500 < area < 2500 and circularity > 0.8: # Adjusted thresholds
filtered_contours.append(contour)
return filtered_contours, markers
def process_image(image, transform_type):
"""Process uploaded image and extract blood cell features"""
if image is None:
return None, None, None, None
try:
# Store original image
original_image = image.copy()
# Detect blood cells
contours, markers = detect_blood_cells(image)
# Extract features
features = []
for i, contour in enumerate(contours, 1):
area = cv2.contourArea(contour)
perimeter = cv2.arcLength(contour, True)
circularity = 4 * np.pi * area / (perimeter * perimeter)
# Calculate centroid
M = cv2.moments(contour)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
# Extract mean color intensity
mask = np.zeros(image.shape[:2], dtype=np.uint8)
cv2.drawContours(mask, [contour], -1, 255, -1)
mean_intensity = cv2.mean(cv2.cvtColor(image, cv2.COLOR_RGB2GRAY), mask=mask)[0]
features.append({
'label': i,
'area': area,
'perimeter': perimeter,
'circularity': circularity,
'mean_intensity': mean_intensity,
'centroid_x': cx,
'centroid_y': cy
})
# Create visualization
vis_img = image.copy()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Draw contours and labels with enhanced visibility
for feature in features:
i = feature['label'] - 1
cv2.drawContours(vis_img, contours, i, (0, 255, 0), 2)
# Add cell labels
x = feature['centroid_x']
y = feature['centroid_y']
# White outline
cv2.putText(vis_img, str(feature['label']),
(x-10, y), cv2.FONT_HERSHEY_SIMPLEX,
0.4, (255, 255, 255), 2)
# Red text
cv2.putText(vis_img, str(feature['label']),
(x-10, y), cv2.FONT_HERSHEY_SIMPLEX,
0.4, (0, 0, 255), 1)
# Add timestamp and cell count with better positioning
info_text = f"Analyzed: {timestamp} | Cells Detected: {len(features)}"
cv2.putText(vis_img, info_text,
(10, 25), cv2.FONT_HERSHEY_SIMPLEX,
0.6, (255, 255, 255), 2)
# Create analysis plots
plt.style.use('default')
fig, axes = plt.subplots(2, 2, figsize=(15, 12))
fig.suptitle('Blood Cell Analysis Results', fontsize=16, y=0.95)
df = pd.DataFrame(features)
if not df.empty:
# Distribution plots
axes[0,0].hist(df['area'], bins=20, color='skyblue', edgecolor='black')
axes[0,0].set_title('Cell Size Distribution')
axes[0,0].set_xlabel('Area (pixels)')
axes[0,0].set_ylabel('Count')
axes[0,0].grid(True, alpha=0.3)
axes[0,1].hist(df['circularity'], bins=20, color='lightgreen', edgecolor='black')
axes[0,1].set_title('Circularity Distribution')
axes[0,1].set_xlabel('Circularity')
axes[0,1].set_ylabel('Count')
axes[0,1].grid(True, alpha=0.3)
# Scatter plot
scatter = axes[1,0].scatter(df['area'], df['mean_intensity'],
c=df['circularity'], cmap='viridis',
alpha=0.6)
axes[1,0].set_title('Area vs Intensity')
axes[1,0].set_xlabel('Area')
axes[1,0].set_ylabel('Mean Intensity')
axes[1,0].grid(True, alpha=0.3)
plt.colorbar(scatter, ax=axes[1,0], label='Circularity')
# Box plot
df.boxplot(column=['area', 'circularity'], ax=axes[1,1])
axes[1,1].set_title('Feature Distributions')
axes[1,1].grid(True, alpha=0.3)
else:
for ax in axes.flat:
ax.text(0.5, 0.5, 'No cells detected', ha='center', va='center')
plt.tight_layout()
# Apply color transformation
transformed_image = apply_color_transformation(original_image, transform_type)
return (
vis_img,
transformed_image,
fig,
df
)
except Exception as e:
print(f"Error processing image: {str(e)}")
import traceback
traceback.print_exc()
return None, None, None, None
# Create Gradio interface
with gr.Blocks(title="Advanced Cell Analysis Tool", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# π¬ Advanced Bioengineering Cell Analysis Tool
## Features
- π Automated cell detection and measurement
- π Comprehensive statistical analysis
- π¨ Multiple visualization options
- π₯ Downloadable results
## Author
- **Muhammad Ibrahim Qasmi**
- [LinkedIn](https://www.linkedin.com/in/muhammad-ibrahim-qasmi-9876a1297/)
""")
with gr.Row():
with gr.Column(scale=1):
input_image = gr.Image(
label="Upload Image",
type="numpy"
)
transform_type = gr.Dropdown(
choices=["Original", "Grayscale", "Binary", "CLAHE"],
value="Original",
label="Image Transform"
)
analyze_btn = gr.Button(
"Analyze Image",
variant="primary",
size="lg"
)
with gr.Column(scale=2):
with gr.Tabs():
with gr.Tab("Analysis Results"):
output_image = gr.Image(
label="Detected Cells"
)
gr.Markdown("*Green contours show detected cells, red numbers are cell IDs*")
with gr.Tab("Image Transformations"):
transformed_image = gr.Image(
label="Transformed Image"
)
gr.Markdown("*Select different transformations from the dropdown menu*")
with gr.Tab("Statistics"):
output_plot = gr.Plot(
label="Statistical Analysis"
)
gr.Markdown("*Hover over plots for detailed values*")
with gr.Tab("Data"):
output_table = gr.DataFrame(
label="Cell Features"
)
analyze_btn.click(
fn=process_image,
inputs=[input_image, transform_type],
outputs=[output_image, transformed_image, output_plot, output_table]
)
# Launch the demo
if __name__ == "__main__":
demo.launch() |