Open KengoAraki opened 3 years ago
def bb_to_patch(
self,
default_level,
level,
size,
stride,
bb,
output_main_dir,
contours_th=0.5,
): # size=(width, height)
assert isinstance(bb, dict), "bb(bounding-box) must be dict type"
obj_name = bb['name']
# bbのx, yをlevel0用に変換(bbはbg_mask_level05における座標のため)
bx_wsi_0 = bb['x'] * (2 ** default_level) # bounding-boxの左上x座標(level0)
by_wsi_0 = bb['y'] * (2 ** default_level) # bounding-boxの左上y座標(level0)
# bbのw, hを特定のlevel用に変換
bw_wsi = bb['w'] * (2 ** (default_level - level)) # bounding-boxの横幅(level)
bh_wsi = bb['h'] * (2 ** (default_level - level)) # bounding-boxの縦幅(level)
row_max = int((bw_wsi - size[0]) / stride + 1)
column_max = int((bh_wsi - size[1]) / stride + 1)
# 細胞領域のマスク画像,背景領域のマスク画像の1ピクセルが特定のレベルのWSIの何ピクセルに相当するか計算
stride_rate = stride / 2 ** (default_level - level)
width_rate = size[0] / 2 ** (default_level - level)
height_rate = size[1] / 2 ** (default_level - level)
assert self.filename_semantic_mask is not None, "Should set filename_semantic_mask"
semantic_mask = Image.open(self.filename_semantic_mask)
semantic_mask_np = np.array(semantic_mask)
assert self.filename_bg_mask is not None, "Should set filename_bg_mask"
bg_mask_np = np.array(Image.open(self.filename_bg_mask))
cnt = 0
for column in range(column_max):
for row in range(row_max):
i = int(bx_wsi_0 + (row * stride * (2 ** level)))
j = int(by_wsi_0 + (column * stride * (2 ** level)))
mask_base_idx = {'row': int(bb['x'] + (row * stride_rate)),
'col': int(bb['y'] + (column * stride_rate))}
# width_rate×height_rateの領域(背景領域のマスク画像)の画素値が0の画素数で比較
if (
len(
np.where(
bg_mask_np[
mask_base_idx['col']:int(mask_base_idx['col'] + height_rate),
mask_base_idx['row']:int(mask_base_idx['row'] + width_rate),
]
== 0
)[0]
)
>= contours_th * height_rate * width_rate
):
# width_rate×height_rateの領域(semanticマスク)の画素値が255以外(背景以外)の画素数で比較
if (
len(
np.where(
semantic_mask_np[
mask_base_idx['col']:int(mask_base_idx['col'] + height_rate),
mask_base_idx['row']:int(mask_base_idx['row'] + width_rate),
]
!= 255
)[0]
)
>= contours_th * height_rate * width_rate
):
s_p = semantic_mask_np[
mask_base_idx['col']:int(mask_base_idx['col'] + height_rate),
mask_base_idx['row']:int(mask_base_idx['row'] + width_rate)
]
output_dir = self._get_output_dir(
s_p, output_main_dir, obj_name)
if output_dir is not None:
self.read_region((i, j), level, size).save(
output_dir
+ str(level)
+ "_"
+ str(cnt).zfill(10)
+ ".png"
)
cnt = cnt + 1
`
https://github.com/KengoAraki/WSI_Predmap/blob/247b070bcda8240ac35bdc8ef4d0795c106af887/openslide_wsi.py#L76