ibrahim313 commited on
Commit
fc4ac67
·
verified ·
1 Parent(s): 496d8af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -103
app.py CHANGED
@@ -10,114 +10,122 @@ from datetime import datetime
10
 
11
  def apply_color_transformation(image, transform_type):
12
  """Apply different color transformations to the image"""
13
- if len(image.shape) == 3:
14
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
15
-
16
- if transform_type == "Original":
17
- return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
18
- elif transform_type == "Grayscale":
19
- return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
20
- elif transform_type == "Binary":
21
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
22
- _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
23
- return binary
24
- elif transform_type == "CLAHE":
25
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
26
- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
27
- return clahe.apply(gray)
28
- return image
 
 
 
 
29
 
30
  def process_image(image, transform_type):
31
  """Process uploaded image and extract cell features"""
32
- if image is None:
33
- return None, None, None, None
34
-
35
- # Store original image for color transformations
36
- original_image = image.copy()
37
-
38
- # Process image as before
39
- if len(image.shape) == 3:
40
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
41
-
42
- # Basic preprocessing
43
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
44
- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
45
- enhanced = clahe.apply(gray)
46
- blurred = cv2.medianBlur(enhanced, 5)
47
-
48
- # [Rest of the processing code remains the same until visualization]
49
-
50
- # Create enhanced visualization with timestamp
51
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
52
- vis_img = image.copy()
53
- contours = measure.find_contours(markers, 0.5)
54
-
55
- # Draw contours and cell IDs with improved visibility
56
- for contour in contours:
57
- coords = contour.astype(int)
58
- cv2.drawContours(vis_img, [coords], -1, (0,255,0), 2) # Thicker lines
59
-
60
- for region in measure.regionprops(markers):
61
- if region.area >= 50:
62
- y, x = region.centroid
63
- # Add white background for better text visibility
64
- cv2.putText(vis_img, str(region.label),
65
- (int(x), int(y)),
66
- cv2.FONT_HERSHEY_SIMPLEX,
67
- 0.5, (255,255,255), 2) # White outline
68
- cv2.putText(vis_img, str(region.label),
69
- (int(x), int(y)),
70
- cv2.FONT_HERSHEY_SIMPLEX,
71
- 0.5, (0,0,255), 1) # Red text
72
-
73
- # Add timestamp and cell count
74
- cv2.putText(vis_img, f"Analyzed: {timestamp}",
75
- (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
76
- 0.7, (255,255,255), 2)
77
-
78
- # Create summary plots with improved styling
79
- plt.style.use('seaborn')
80
- fig, axes = plt.subplots(2, 2, figsize=(15, 12))
81
- fig.suptitle('Cell Analysis Results', fontsize=16, y=0.95)
82
-
83
- df = pd.DataFrame(features)
84
- if not df.empty:
85
- # Distribution plots
86
- df['area'].hist(ax=axes[0,0], bins=20, color='skyblue', edgecolor='black')
87
- axes[0,0].set_title('Cell Size Distribution')
88
- axes[0,0].set_xlabel('Area')
89
- axes[0,0].set_ylabel('Count')
90
 
91
- df['circularity'].hist(ax=axes[0,1], bins=20, color='lightgreen', edgecolor='black')
92
- axes[0,1].set_title('Circularity Distribution')
93
- axes[0,1].set_xlabel('Circularity')
94
- axes[0,1].set_ylabel('Count')
95
 
96
- # Scatter plots
97
- axes[1,0].scatter(df['circularity'], df['mean_intensity'],
98
- alpha=0.6, c='purple')
99
- axes[1,0].set_title('Circularity vs Intensity')
100
- axes[1,0].set_xlabel('Circularity')
101
- axes[1,0].set_ylabel('Mean Intensity')
102
 
103
- # Add box plot
104
- df.boxplot(column=['area', 'circularity'], ax=axes[1,1])
105
- axes[1,1].set_title('Feature Distributions')
106
- else:
107
- for ax in axes.flat:
108
- ax.text(0.5, 0.5, 'No cells detected', ha='center', va='center')
109
-
110
- plt.tight_layout()
111
-
112
- # Apply color transformation to original image
113
- transformed_image = apply_color_transformation(original_image, transform_type)
114
-
115
- return (
116
- cv2.cvtColor(vis_img, cv2.COLOR_BGR2RGB),
117
- transformed_image,
118
- fig,
119
- df
120
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  # Create enhanced Gradio interface
123
  with gr.Blocks(title="Advanced Cell Analysis Tool", theme=gr.themes.Soft()) as demo:
@@ -201,4 +209,7 @@ with gr.Blocks(title="Advanced Cell Analysis Tool", theme=gr.themes.Soft()) as d
201
 
202
  # Launch the demo
203
  if __name__ == "__main__":
204
- demo.launch()
 
 
 
 
10
 
11
  def apply_color_transformation(image, transform_type):
12
  """Apply different color transformations to the image"""
13
+ try:
14
+ if len(image.shape) == 3:
15
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
16
+
17
+ if transform_type == "Original":
18
+ return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
19
+ elif transform_type == "Grayscale":
20
+ return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
21
+ elif transform_type == "Binary":
22
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
23
+ _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
24
+ return binary
25
+ elif transform_type == "CLAHE":
26
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
27
+ clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
28
+ return clahe.apply(gray)
29
+ return image
30
+ except Exception as e:
31
+ print(f"Error in apply_color_transformation: {e}")
32
+ return None
33
 
34
  def process_image(image, transform_type):
35
  """Process uploaded image and extract cell features"""
36
+ try:
37
+ if image is None:
38
+ return None, None, None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # Store original image for color transformations
41
+ original_image = image.copy()
 
 
42
 
43
+ # Process image as before
44
+ if len(image.shape) == 3:
45
+ image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
 
 
 
46
 
47
+ # Basic preprocessing
48
+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
49
+ clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
50
+ enhanced = clahe.apply(gray)
51
+ blurred = cv2.medianBlur(enhanced, 5)
52
+
53
+ # [Rest of the processing code remains the same until visualization]
54
+
55
+ # Create enhanced visualization with timestamp
56
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
57
+ vis_img = image.copy()
58
+ contours = measure.find_contours(markers, 0.5)
59
+
60
+ # Draw contours and cell IDs with improved visibility
61
+ for contour in contours:
62
+ coords = contour.astype(int)
63
+ cv2.drawContours(vis_img, [coords], -1, (0,255,0), 2) # Thicker lines
64
+
65
+ for region in measure.regionprops(markers):
66
+ if region.area >= 50:
67
+ y, x = region.centroid
68
+ # Add white background for better text visibility
69
+ cv2.putText(vis_img, str(region.label),
70
+ (int(x), int(y)),
71
+ cv2.FONT_HERSHEY_SIMPLEX,
72
+ 0.5, (255,255,255), 2) # White outline
73
+ cv2.putText(vis_img, str(region.label),
74
+ (int(x), int(y)),
75
+ cv2.FONT_HERSHEY_SIMPLEX,
76
+ 0.5, (0,0,255), 1) # Red text
77
+
78
+ # Add timestamp and cell count
79
+ cv2.putText(vis_img, f"Analyzed: {timestamp}",
80
+ (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
81
+ 0.7, (255,255,255), 2)
82
+
83
+ # Create summary plots with improved styling
84
+ plt.style.use('seaborn')
85
+ fig, axes = plt.subplots(2, 2, figsize=(15, 12))
86
+ fig.suptitle('Cell Analysis Results', fontsize=16, y=0.95)
87
+
88
+ df = pd.DataFrame(features)
89
+ if not df.empty:
90
+ # Distribution plots
91
+ df['area'].hist(ax=axes[0,0], bins=20, color='skyblue', edgecolor='black')
92
+ axes[0,0].set_title('Cell Size Distribution')
93
+ axes[0,0].set_xlabel('Area')
94
+ axes[0,0].set_ylabel('Count')
95
+
96
+ df['circularity'].hist(ax=axes[0,1], bins=20, color='lightgreen', edgecolor='black')
97
+ axes[0,1].set_title('Circularity Distribution')
98
+ axes[0,1].set_xlabel('Circularity')
99
+ axes[0,1].set_ylabel('Count')
100
+
101
+ # Scatter plots
102
+ axes[1,0].scatter(df['circularity'], df['mean_intensity'],
103
+ alpha=0.6, c='purple')
104
+ axes[1,0].set_title('Circularity vs Intensity')
105
+ axes[1,0].set_xlabel('Circularity')
106
+ axes[1,0].set_ylabel('Mean Intensity')
107
+
108
+ # Add box plot
109
+ df.boxplot(column=['area', 'circularity'], ax=axes[1,1])
110
+ axes[1,1].set_title('Feature Distributions')
111
+ else:
112
+ for ax in axes.flat:
113
+ ax.text(0.5, 0.5, 'No cells detected', ha='center', va='center')
114
+
115
+ plt.tight_layout()
116
+
117
+ # Apply color transformation to original image
118
+ transformed_image = apply_color_transformation(original_image, transform_type)
119
+
120
+ return (
121
+ cv2.cvtColor(vis_img, cv2.COLOR_BGR2RGB),
122
+ transformed_image,
123
+ fig,
124
+ df
125
+ )
126
+ except Exception as e:
127
+ print(f"Error in process_image: {e}")
128
+ return None, None, None, None
129
 
130
  # Create enhanced Gradio interface
131
  with gr.Blocks(title="Advanced Cell Analysis Tool", theme=gr.themes.Soft()) as demo:
 
209
 
210
  # Launch the demo
211
  if __name__ == "__main__":
212
+ try:
213
+ demo.launch()
214
+ except Exception as e:
215
+ print(f"Error launching Gradio interface: {e}")