benedictpepper commited on
Commit
b6b0c1b
·
1 Parent(s): 582ea6f
Files changed (3) hide show
  1. data/sample_mri.jpg +0 -0
  2. requirements.txt +4 -0
  3. src/segment_fcm.py +162 -0
data/sample_mri.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ numpy>=1.21.0
2
+ opencv-python>=4.5.0
3
+ scikit-fuzzy>=0.4.0
4
+ scikit-learn>=1.0.0
src/segment_fcm.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import cv2
4
+ import skfuzzy as fuzz
5
+ from sklearn.metrics import silhouette_score, davies_bouldin_score
6
+
7
+
8
+ class FCMSegmenter:
9
+ """Fuzzy C-Means based MRI tumor segmentation."""
10
+
11
+ def __init__(self, n_clusters=4, fuzziness=2.0, max_iter=1000, error=0.005):
12
+ self.n_clusters = n_clusters
13
+ self.fuzziness = fuzziness
14
+ self.max_iter = max_iter
15
+ self.error = error
16
+ self.cntr = None
17
+ self.u = None
18
+ self.fpc = None
19
+ self.iterations = None
20
+ self.objective_value = None
21
+
22
+ def load_image(self, image_path):
23
+ """Load and preprocess image for segmentation."""
24
+ if not os.path.exists(image_path):
25
+ raise FileNotFoundError(f"Image not found: {image_path}")
26
+
27
+ img = cv2.imread(image_path)
28
+ if img is None:
29
+ raise ValueError(f"Failed to load image: {image_path}")
30
+
31
+ img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) > 2 else img
32
+ original_shape = img_gray.shape
33
+ pixel_data = img_gray.flatten().astype(np.float32).reshape((1, -1))
34
+
35
+ return img, img_gray, pixel_data, original_shape
36
+
37
+ def segment(self, pixel_data):
38
+ """Apply Fuzzy C-Means clustering to pixel data."""
39
+ cntr, u, _, _, jm, p, fpc = fuzz.cluster.cmeans(
40
+ data=pixel_data,
41
+ c=self.n_clusters,
42
+ m=self.fuzziness,
43
+ error=self.error,
44
+ maxiter=self.max_iter,
45
+ init=None
46
+ )
47
+
48
+ self.cntr = cntr
49
+ self.u = u
50
+ self.fpc = fpc
51
+ self.iterations = p
52
+ self.objective_value = jm[-1]
53
+
54
+ return np.argmax(u, axis=0)
55
+
56
+ def create_segmented_image(self, cluster_labels, original_shape):
57
+ """Convert cluster labels to color-coded segmented image."""
58
+ segmented_labels = cluster_labels.reshape(original_shape)
59
+ segmented_color = np.zeros((original_shape[0], original_shape[1], 3), dtype=np.uint8)
60
+
61
+ sorted_centers = np.argsort(self.cntr.flatten())
62
+ color_map = {
63
+ sorted_centers[0]: [0, 0, 0],
64
+ sorted_centers[1]: [85, 85, 85],
65
+ sorted_centers[2]: [0, 255, 0],
66
+ sorted_centers[3]: [255, 0, 0]
67
+ }
68
+
69
+ for i in range(self.n_clusters):
70
+ mask = segmented_labels == i
71
+ color = color_map.get(i, [255, 255, 255])
72
+ segmented_color[mask] = color
73
+
74
+ return segmented_labels, segmented_color
75
+
76
+ def evaluate(self, pixel_data, cluster_labels):
77
+ """Compute clustering quality metrics."""
78
+ labels_flat = cluster_labels.flatten()
79
+ data_flat = pixel_data.flatten()
80
+
81
+ metrics = {
82
+ 'fpc': self.fpc,
83
+ 'iterations': self.iterations,
84
+ 'objective_value': self.objective_value
85
+ }
86
+
87
+ if len(np.unique(labels_flat)) > 1:
88
+ try:
89
+ metrics['silhouette'] = silhouette_score(data_flat.reshape(-1, 1), labels_flat)
90
+ metrics['davies_bouldin'] = davies_bouldin_score(data_flat.reshape(-1, 1), labels_flat)
91
+ except Exception:
92
+ pass
93
+
94
+ return metrics
95
+
96
+ def process(self, image_path):
97
+ """Full segmentation pipeline."""
98
+ img_bgr, img_gray, pixel_data, original_shape = self.load_image(image_path)
99
+ cluster_labels = self.segment(pixel_data)
100
+ segmented_labels, segmented_color = self.create_segmented_image(cluster_labels, original_shape)
101
+ metrics = self.evaluate(pixel_data, cluster_labels)
102
+
103
+ return {
104
+ 'original': cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB),
105
+ 'gray': img_gray,
106
+ 'segmented_labels': segmented_labels,
107
+ 'segmented_color': segmented_color,
108
+ 'metrics': metrics
109
+ }
110
+
111
+ def save_results(self, results, output_dir='output'):
112
+ """Save segmentation results to disk."""
113
+ os.makedirs(output_dir, exist_ok=True)
114
+
115
+ cv2.imwrite(
116
+ os.path.join(output_dir, 'segmented_color.png'),
117
+ cv2.cvtColor(results['segmented_color'], cv2.COLOR_RGB2BGR)
118
+ )
119
+ cv2.imwrite(
120
+ os.path.join(output_dir, 'segmented_labels.png'),
121
+ results['segmented_labels'].astype(np.uint8)
122
+ )
123
+
124
+ with open(os.path.join(output_dir, 'metrics.txt'), 'w') as f:
125
+ f.write("FCM Segmentation Metrics\n")
126
+ f.write(f"FPC: {results['metrics'].get('fpc', 'N/A'):.4f}\n")
127
+ f.write(f"Iterations: {results['metrics'].get('iterations', 'N/A')}\n")
128
+ f.write(f"Objective Value: {results['metrics'].get('objective_value', 'N/A'):.4f}\n")
129
+ if 'silhouette' in results['metrics']:
130
+ f.write(f"Silhouette Score: {results['metrics']['silhouette']:.4f}\n")
131
+ if 'davies_bouldin' in results['metrics']:
132
+ f.write(f"Davies-Bouldin Index: {results['metrics']['davies_bouldin']:.4f}\n")
133
+
134
+
135
+ def main():
136
+ import argparse
137
+
138
+ parser = argparse.ArgumentParser(description='FCM-based MRI Tumor Segmentation')
139
+ parser.add_argument('--input', type=str, required=True, help='Path to input MRI image')
140
+ parser.add_argument('--output', type=str, default='output', help='Output directory')
141
+ parser.add_argument('--clusters', type=int, default=4, help='Number of clusters')
142
+ parser.add_argument('--fuzziness', type=float, default=2.0, help='Fuzziness parameter')
143
+ args = parser.parse_args()
144
+
145
+ segmenter = FCMSegmenter(
146
+ n_clusters=args.clusters,
147
+ fuzziness=args.fuzziness
148
+ )
149
+
150
+ print(f"Processing: {args.input}")
151
+ results = segmenter.process(args.input)
152
+
153
+ print(f"\nSegmentation complete.")
154
+ print(f"FPC: {results['metrics']['fpc']:.4f}")
155
+ print(f"Iterations: {results['metrics']['iterations']}")
156
+
157
+ segmenter.save_results(results, args.output)
158
+ print(f"Results saved to: {args.output}/")
159
+
160
+
161
+ if __name__ == '__main__':
162
+ main()