-
Notifications
You must be signed in to change notification settings - Fork 0
/
DSC.py
73 lines (56 loc) · 2.83 KB
/
DSC.py
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
import os
import cv2
import numpy as np
import pandas as pd
def calculate_dsc(annotated_imgs_directory, label_imgs_directory):
DSCs = {}
annotated_imgs = os.listdir(annotated_imgs_directory)
label_imgs = os.listdir(label_imgs_directory)
for label_img_name in label_imgs:
annotated_img_name = "output_" + label_img_name #change this if annotated image name is different
annotated_img_path = os.path.join(annotated_imgs_directory, annotated_img_name)
label_img_path = os.path.join(label_imgs_directory, label_img_name)
annotated_img = cv2.imread(annotated_img_path)
label_img = cv2.imread(label_img_path)
intersection = 0
ann_pixels = 0
label_pixels = 0
if annotated_img is None:
# print(f"Failed to load images for {annotated_img_name}")
continue
if label_img is None:
print(f"Failed to load images for {label_img_name}")
continue
height, width, _ = annotated_img.shape # Assuming both images have the same size
for y in range(height):
for x in range(width):
# Get RGB values for each image
pixel_annotated_img = annotated_img[y, x]
pixel_label_img = label_img[y, x]
if (pixel_annotated_img == [255, 255, 255]).all():
ann_pixels += 1
if (pixel_label_img == [255, 255, 255]).all():
label_pixels += 1
# Check if the pixel in the first image is green (0, 255, 0)
if (pixel_annotated_img == [255, 255, 255]).all() and (pixel_label_img == [255, 255, 255]).all():
intersection += 1
if intersection == 0 or (x+y) == 0:
continue
dsc = 2 * intersection / (ann_pixels + label_pixels)
DSCs[label_img_name[:-4]] = dsc
return DSCs
annotated_imgs_directory = "annotated_images/" #rename to the directory that contains the segmented images with green overlay
label_imgs_directory = "data/MedSAMDemo_2D/labels/" #rename to the directory that contains the labeled data given to us with white overlay"
DSCs = calculate_dsc(annotated_imgs_directory, label_imgs_directory)
print(DSCs)
df = pd.DataFrame(list(DSCs.items()), columns=['Label ID', 'DSC'])
excel_file_path = 'DSC.xlsx'
# Check if the file already exists
if os.path.exists(excel_file_path):
# Write the DataFrame to an Excel file, overwriting it
df.to_excel(excel_file_path, index=False, mode='w')
print(f"Data has been overwritten in {excel_file_path}")
else:
# Write the DataFrame to an Excel file, creating it
df.to_excel(excel_file_path, index=False)
print(f"Data has been written to {excel_file_path}")