-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract_patches.py
executable file
·299 lines (248 loc) · 10.7 KB
/
extract_patches.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""extract_patches.py
Patch extraction script.
"""
import re
import glob
import os
import tqdm
import pathlib
import cv2
import numpy as np
from PIL import Image
import pdb
from misc.patch_extractor import PatchExtractor
from misc.utils import rm_n_mkdir
from dataset import get_dataset
def save_img():
save_root = "/labs3/amartel_data3/tingxiao/hover_net/kumar-mask/"
open_root = "/labs3/amartel_data3/tingxiao/hover_net/kumar-patches/train/540x540_164x164/"
file_list = os.listdir(open_root)
file_list.sort()
for file in file_list:
base_name = file.split('.')[0]
im_ann = np.load(open_root+file)
#img = im_ann[:,:,0:3]
#im = Image.fromarray(img.astype(np.uint8)).convert('RGB')
#im.save("{0}/{1}.png".format(save_root, base_name))
mask = im_ann[:,:,3:4]
mask[mask>0]=1
_,contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[1]
res = cv2.drawContours(mask, [cnt], 0, (0, 0, 255), 1)
new_mask = Image.fromarray((res).astype(np.uint8)).convert('RGB')
new_mask.save("{0}/{1}.png".format(save_root, base_name))
'''
mask = np.squeeze(mask, axis=2)
mask = np.stack((mask,)*3, axis=-1)
new_mask = Image.fromarray((mask*255).astype(np.uint8)).convert('RGB')
new_mask.save("{0}/{1}.png".format(save_root, base_name))
'''
def extract_img():
type_classification = True
win_size = [540, 540]
step_size = [164, 164]
extract_type = "mirror" # Choose 'mirror' or 'valid'. 'mirror'- use padding at borders. 'valid'- only extract from valid regions.
# Name of dataset - use Kumar, CPM17 or CoNSeP.
# This used to get the specific dataset img and ann loading scheme from dataset.py
dataset_name = "kumar"
#save_root = "/labs3/amartel_data3/tingxiao/hover_net/%s-patches/" % dataset_name
save_root = "/labs3/amartel_data3/tingxiao/hover_net/IHC-patches/"
# a dictionary to specify where the dataset path should be
dataset_info = {
"train": {
"img": (".tif", "/labs3/amartel_data3/tingxiao/hover_net/IHC/"),
#"ann": (".mat", "/labs3/amartel_data3/tingxiao/hover_net/kumar/train/Labels/"),
},
#"valid": {
# "img": (".png", "/labs3/amartel_data3/tingxiao/hover_net/kumar/test_same/stain_images1/no_backgrounds/"),
# "ann": (".mat", "/labs3/amartel_data3/tingxiao/hover_net/kumar/test_same/Labels/"),
#},
}
patterning = lambda x: re.sub("([\[\]])", "[\\1]", x)
parser = get_dataset(dataset_name)
xtractor = PatchExtractor(win_size, step_size)
for split_name, split_desc in dataset_info.items():
img_ext, img_dir = split_desc["img"]
#ann_ext, ann_dir = split_desc["ann"]
out_dir = "%s/%s/%dx%d_%dx%d/" % (
save_root,
split_name,
win_size[0],
win_size[1],
step_size[0],
step_size[1],
)
file_list = glob.glob(patterning("%s/*%s" % (img_dir, img_ext)))
file_list.sort() # ensure same ordering across platform
rm_n_mkdir(out_dir)
pbar_format = "Process File: |{bar}| {n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
pbarx = tqdm.tqdm(
total=len(file_list), bar_format=pbar_format, ascii=True, position=0
)
for file_idx, file_path in enumerate(file_list):
base_name = pathlib.Path(file_path).stem
print(img_dir,base_name,img_ext)
img = parser.load_img("%s/%s%s" % (img_dir, base_name, img_ext))
#ann = parser.load_ann("%s/%s%s" % (ann_dir, base_name.split('_')[0], ann_ext), type_classification,flag)
#pdb.set_trace()
# *
#img = np.concatenate([img, ann], axis=-1)
sub_patches = xtractor.extract(img, extract_type)
pbar_format = "Extracting : |{bar}| {n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
pbar = tqdm.tqdm(
total=len(sub_patches),
leave=False,
bar_format=pbar_format,
ascii=True,
position=1,
)
for idx, patch in enumerate(sub_patches):
im = Image.fromarray(patch.astype(np.uint8)).convert('RGB')
im.save("{0}/{1}_{2:03d}.png".format(out_dir, base_name, idx))
#np.save("{0}/{1}_{2:03d}.npy".format(out_dir, base_name, idx), patch)
pbar.update()
pbar.close()
# *
pbarx.update()
pbarx.close()
def extract_new():
type_classification = False
win_size = [540, 540]
step_size = [164, 164]
extract_type = "mirror" # Choose 'mirror' or 'valid'. 'mirror'- use padding at borders. 'valid'- only extract from valid regions.
# Name of dataset - use Kumar, CPM17 or CoNSeP.
# This used to get the specific dataset img and ann loading scheme from dataset.py
dataset_name = "kumar"
save_root = "/labs3/amartel_data3/tingxiao/hover_net/B-patches/"# % dataset_name
# a dictionary to specify where the dataset path should be
dataset_info = {
"train": {
"img": (".png", "/labs3/amartel_data3/tingxiao/hover_net/kumar/train/B/"),
"ann": (".mat", "/labs3/amartel_data3/tingxiao/hover_net/kumar/train/Labels/"),
},
"valid": {
"img": (".png", "/labs3/amartel_data3/tingxiao/hover_net/kumar/train/B/"),
"ann": (".mat", "/labs3/amartel_data3/tingxiao/hover_net/kumar/train/Labels/"),
},
}
patterning = lambda x: re.sub("([\[\]])", "[\\1]", x)
parser = get_dataset(dataset_name)
xtractor = PatchExtractor(win_size, step_size)
for split_name, split_desc in dataset_info.items():
img_ext, img_dir = split_desc["img"]
ann_ext, ann_dir = split_desc["ann"]
out_dir = "%s/%s/%dx%d_%dx%d/" % (
save_root,
split_name,
win_size[0],
win_size[1],
step_size[0],
step_size[1],
)
file_list = glob.glob(patterning("%s/*%s" % (img_dir, img_ext)))
file_list.sort() # ensure same ordering across platform
rm_n_mkdir(out_dir)
pbar_format = "Process File: |{bar}| {n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
pbarx = tqdm.tqdm(
total=len(file_list), bar_format=pbar_format, ascii=True, position=0
)
for file_idx, file_path in enumerate(file_list):
base_name = pathlib.Path(file_path).stem
print(img_dir,base_name,img_ext)
img = parser.load_img("%s/%s%s" % (img_dir, base_name, img_ext))
if 'blue' in base_name:
flag = 'blue'
if 'brown' in base_name:
flag = 'brown'
ann = parser.load_ann("%s/%s%s" % (ann_dir, base_name.split('_')[0], ann_ext), type_classification)
#pdb.set_trace()
# *
img = np.concatenate([img, ann], axis=-1)
sub_patches = xtractor.extract(img, extract_type)
pbar_format = "Extracting : |{bar}| {n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
pbar = tqdm.tqdm(
total=len(sub_patches),
leave=False,
bar_format=pbar_format,
ascii=True,
position=1,
)
for idx, patch in enumerate(sub_patches):
np.save("{0}/{1}_{2:03d}.npy".format(out_dir, base_name, idx), patch)
pbar.update()
pbar.close()
# *
pbarx.update()
pbarx.close()
def extract_four_types():
type_classification = True
win_size = [540, 540]
step_size = [164, 164]
extract_type = "mirror" # Choose 'mirror' or 'valid'. 'mirror'- use padding at borders. 'valid'- only extract from valid regions.
# Name of dataset - use aml
# This used to get the specific dataset img and ann loading scheme from dataset.py
dataset_name = "aml"#"kumar"
save_root = "/labs3/amartel_data3/tingxiao/hover_net/%s-intens-patches/" % dataset_name
dataset_info = {
"train": {
"img": (".png", "/labs3/amartel_data3/tingxiao/hover_net/AML-ROIS-intens/train/Images/"),
"ann": (".mat", "/labs3/amartel_data3/tingxiao/hover_net/AML-ROIS-intens/train/Anno/"),
},
"valid": {
"img": (".png", "/labs3/amartel_data3/tingxiao/hover_net/AML-ROIS-intens/valid/Images/"),
"ann": (".mat", "/labs3/amartel_data3/tingxiao/hover_net/AML-ROIS-intens/valid/Anno/"),
},
}
patterning = lambda x: re.sub("([\[\]])", "[\\1]", x)
parser = get_dataset(dataset_name)
xtractor = PatchExtractor(win_size, step_size)
for split_name, split_desc in dataset_info.items():
img_ext, img_dir = split_desc["img"]
ann_ext, ann_dir = split_desc["ann"]
out_dir = "%s/%s/%dx%d_%dx%d/" % (
save_root,
split_name,
win_size[0],
win_size[1],
step_size[0],
step_size[1],
)
file_list = glob.glob(patterning("%s/*%s" % (ann_dir, ann_ext)))
file_list.sort() # ensure same ordering across platform
rm_n_mkdir(out_dir)
pbar_format = "Process File: |{bar}| {n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
pbarx = tqdm.tqdm(
total=len(file_list), bar_format=pbar_format, ascii=True, position=0
)
for file_idx, file_path in enumerate(file_list):
base_name = pathlib.Path(file_path).stem
print(img_dir,base_name,img_ext)
img = parser.load_img("%s/%s%s" % (img_dir, base_name, img_ext))
ann = parser.load_ann(
"%s/%s%s" % (ann_dir, base_name, ann_ext), type_classification,5
)
# *
img = np.concatenate([img, ann], axis=-1)
sub_patches = xtractor.extract(img, extract_type)
pbar_format = "Extracting : |{bar}| {n_fmt}/{total_fmt}[{elapsed}<{remaining},{rate_fmt}]"
pbar = tqdm.tqdm(
total=len(sub_patches),
leave=False,
bar_format=pbar_format,
ascii=True,
position=1,
)
for idx, patch in enumerate(sub_patches):
np.save("{0}/{1}_{2:03d}.npy".format(out_dir, base_name, idx), patch)
pbar.update()
pbar.close()
# *
pbarx.update()
pbarx.close()
# -------------------------------------------------------------------------------------
if __name__ == "__main__":
# Determines whether to extract type map (only applicable to datasets with class labels).
extract_four_types()
#extract_img()
#save_img()
#extract_new()