-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
101 lines (69 loc) · 2.27 KB
/
main.py
File metadata and controls
101 lines (69 loc) · 2.27 KB
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
#!/usr/local/bin/python
import requests
import csv
from multiprocessing import Pool
import io
import zipfile
import os
api_endpoint = "https://services.cancerimagingarchive.net/services/v3/TCIA/query/getImage?SeriesInstanceUID="
train_path = "../mass_case_description_train_set.csv"
test_path = "../mass_case_description_test_set.csv"
train_output_dir = "../train_data/"
test_output_dir = "../test_data/"
limit = 10
pool_workers = 10
def load_csv(csv_path):
data = []
key_to_index = {}
with open(csv_path, "r") as f:
reader = csv.reader(f)
first_row = next(iter(reader))
for index, key in enumerate(first_row):
key_to_index[key] = index
for row in reader:
data.append(row)
return data, key_to_index
def download_file(file_path, output_dir):
seriesInstanceUID = file_path.split("/")[-2]
response = requests.get(api_endpoint + seriesInstanceUID)
buf = io.BytesIO(response.content)
files = zipfile.ZipFile(buf)
smallest_dcm_file = None
for file in files.infolist():
if ".dcm" == file.filename[-4:] and (smallest_dcm_file is None or smallest_dcm_file.file_size > file.file_size):
smallest_dcm_file = file
if smallest_dcm_file:
return files.extract(smallest_dcm_file, output_dir)
else:
return None
def save_image(id_, label, file_path, output_dir):
file_path = download_file(file_path, output_dir)
if not file_path:
return False
os.system(f"mogrify -format png {file_path}")
os.system(f"mv {file_path[:-4]}.png {output_dir}{label}_{id_}.png")
os.system(f"rm {file_path}")
print(f"Successfully downloaded {id_}")
return True
def download_data(item):
if save_image(*item):
return True
return False
def build_dataset(data, key_to_index, output_dir):
pool = Pool(processes=pool_workers)
download_meta_data = []
counts = {}
for item in data[:limit]:
patient_id = item[key_to_index["patient_id"]]
file_path = item[key_to_index["cropped image file path"]]
if patient_id not in counts:
counts[patient_id] = 0
else:
counts[patient_id] += 1
download_meta_data.append((patient_id, item[key_to_index["pathology"]], file_path, output_dir))
pool.map(download_data, download_meta_data)
def main():
train_data, key_to_index = load_csv(train_path)
build_dataset(train_data, key_to_index, train_output_dir)
if __name__ == "__main__":
main()