MCPcopy Create free account
hub / github.com/HealthX-Lab/MedCLIP-SAMv2 / postprocess_kmeans

Function postprocess_kmeans

postprocessing/postprocess_saliency_maps.py:103–150  ·  view source on GitHub ↗
(args)

Source from the content-addressed store, hash-verified

101 cv2.imwrite(output, segmented_image)
102
103def postprocess_kmeans(args):
104
105 files = os.listdir(args.sal_path)
106
107 if (not os.path.exists(args.output_path)):
108 os.makedirs(args.output_path)
109
110 for file in tqdm(files):
111
112 kmeans = KMeans(n_clusters=2,random_state=10)
113 attn_weights = cv2.imread(args.sal_path+'/'+file, 0) / 255
114 h, w = attn_weights.shape
115 image = cv2.resize(attn_weights, (256, 256),interpolation=cv2.INTER_NEAREST)
116 flat_image = image.reshape(-1, 1)
117
118 labels = kmeans.fit_predict(flat_image)
119
120 segmented_image = labels.reshape(256, 256)
121
122 centroids = kmeans.cluster_centers_.flatten()
123
124 # Identify the background cluster (assuming it has the lowest centroid value)
125 background_cluster = np.argmin(centroids)
126
127 # Mark background pixels as 0 and foreground pixels as 1
128 segmented_image = np.where(segmented_image == background_cluster, 0, 1)
129
130 segmented_image = cv2.resize(segmented_image, (w,h),interpolation=cv2.INTER_NEAREST)
131 segmented_image = segmented_image.astype(np.uint8)*255
132
133 nb_blobs, im_with_separated_blobs, stats, _ = cv2.connectedComponentsWithStats(segmented_image)
134 sizes = stats[:, cv2.CC_STAT_AREA]
135
136 # Sort sizes (ignoring the background at index 0)
137 sorted_sizes = sorted(sizes[1:], reverse=True)
138
139 # Determine the top K sizes
140 top_k_sizes = sorted_sizes[:args.num_contours]
141
142 im_result = np.zeros_like(im_with_separated_blobs)
143
144 for index_blob in range(1, nb_blobs):
145 if sizes[index_blob] in top_k_sizes:
146 im_result[im_with_separated_blobs == index_blob] = 255
147
148 segmented_image = im_result
149
150 cv2.imwrite(args.output_path+'/'+file, segmented_image)
151
152
153def get_parser():

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected