File size: 7,292 Bytes
8312ddd
 
 
 
 
 
 
d28c822
 
8312ddd
d28c822
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8312ddd
d28c822
 
 
 
 
 
 
8312ddd
 
 
 
 
 
 
 
 
d28c822
8312ddd
d28c822
 
8312ddd
 
 
d28c822
8312ddd
 
d28c822
8312ddd
 
 
 
d28c822
 
 
 
 
8312ddd
 
 
d28c822
8312ddd
d28c822
 
 
 
 
 
 
 
 
8312ddd
 
e9a9c89
d28c822
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9a9c89
d28c822
 
 
e9a9c89
d28c822
 
8312ddd
 
 
d28c822
 
 
8312ddd
 
d28c822
8312ddd
 
 
 
d28c822
 
8312ddd
d28c822
 
 
 
 
 
 
 
 
 
 
 
8312ddd
 
 
d28c822
8312ddd
 
e9a9c89
8312ddd
d28c822
 
 
 
 
8312ddd
d28c822
 
 
8312ddd
 
d28c822
8312ddd
d28c822
8312ddd
 
 
d28c822
 
 
 
 
 
 
 
8312ddd
 
 
 
d28c822
 
 
8312ddd
 
 
d28c822
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8312ddd
 
 
d28c822
 
8312ddd
 
 
 
 
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
import cv2
import numpy as np
import pandas as pd
import gradio as gr
from skimage import measure, morphology
from skimage.segmentation import watershed
import matplotlib.pyplot as plt
import base64
from datetime import datetime

def apply_color_transformation(image, transform_type):
    """Apply different color transformations to the image"""
    if len(image.shape) == 3:
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    
    if transform_type == "Original":
        return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    elif transform_type == "Grayscale":
        return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    elif transform_type == "Binary":
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
        return binary
    elif transform_type == "CLAHE":
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
        return clahe.apply(gray)
    return image

def process_image(image, transform_type):
    """Process uploaded image and extract cell features"""
    if image is None:
        return None, None, None, None
    
    # Store original image for color transformations
    original_image = image.copy()
    
    # Process image as before
    if len(image.shape) == 3:
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    
    # Basic preprocessing
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
    enhanced = clahe.apply(gray)
    blurred = cv2.medianBlur(enhanced, 5)
    
    # [Rest of the processing code remains the same until visualization]
    
    # Create enhanced visualization with timestamp
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    vis_img = image.copy()
    contours = measure.find_contours(markers, 0.5)
    
    # Draw contours and cell IDs with improved visibility
    for contour in contours:
        coords = contour.astype(int)
        cv2.drawContours(vis_img, [coords], -1, (0,255,0), 2)  # Thicker lines
    
    for region in measure.regionprops(markers):
        if region.area >= 50:
            y, x = region.centroid
            # Add white background for better text visibility
            cv2.putText(vis_img, str(region.label), 
                       (int(x), int(y)),
                       cv2.FONT_HERSHEY_SIMPLEX, 
                       0.5, (255,255,255), 2)  # White outline
            cv2.putText(vis_img, str(region.label), 
                       (int(x), int(y)),
                       cv2.FONT_HERSHEY_SIMPLEX, 
                       0.5, (0,0,255), 1)  # Red text
    
    # Add timestamp and cell count
    cv2.putText(vis_img, f"Analyzed: {timestamp}", 
                (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 
                0.7, (255,255,255), 2)
    
    # Create summary plots with improved styling
    plt.style.use('seaborn')
    fig, axes = plt.subplots(2, 2, figsize=(15, 12))
    fig.suptitle('Cell Analysis Results', fontsize=16, y=0.95)
    
    df = pd.DataFrame(features)
    if not df.empty:
        # Distribution plots
        df['area'].hist(ax=axes[0,0], bins=20, color='skyblue', edgecolor='black')
        axes[0,0].set_title('Cell Size Distribution')
        axes[0,0].set_xlabel('Area')
        axes[0,0].set_ylabel('Count')
        
        df['circularity'].hist(ax=axes[0,1], 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')
        
        # Scatter plots
        axes[1,0].scatter(df['circularity'], df['mean_intensity'], 
                         alpha=0.6, c='purple')
        axes[1,0].set_title('Circularity vs Intensity')
        axes[1,0].set_xlabel('Circularity')
        axes[1,0].set_ylabel('Mean Intensity')
        
        # Add box plot
        df.boxplot(column=['area', 'circularity'], ax=axes[1,1])
        axes[1,1].set_title('Feature Distributions')
    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 to original image
    transformed_image = apply_color_transformation(original_image, transform_type)
    
    return (
        cv2.cvtColor(vis_img, cv2.COLOR_BGR2RGB),
        transformed_image,
        fig,
        df
    )

# Create enhanced 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/)
    - [GitHub](https://github.com/yourusername)  <!-- Add your GitHub URL -->
    """)
    
    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"
                    )
                    download_btn = gr.Button(
                        "Download Results",
                        variant="secondary"
                    )
    
    # Add footer
    gr.Markdown("""
    ---
    ### πŸ“ Notes
    - Supported image formats: PNG, JPG, JPEG
    - Minimum recommended resolution: 512x512 pixels
    - Processing time varies with image size and cell count
    
    *Last updated: January 2025*
    """)
    
    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()