File size: 2,873 Bytes
46a377d | 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 | '''
Generate superpixel labels for training images
'''
from skimage.segmentation import slic, mark_boundaries
from skimage.io import imread, imsave
import skimage.exposure
from glob import glob
import json
from data_process.util import NpEncoder
import os
import numpy as np
import argparse
import ipdb
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--super_postfix', default= '', help='superpixel dir post fix', type=str)
args = parser.parse_args()
return args
def makedir(_dir):
if not os.path.exists(_dir):
os.makedirs(_dir)
def gen_superpixel_label(paths):
def save_json(save_path, segments):
with open(save_path, 'w') as f:
json.dump(segments, f, cls=NpEncoder)
def save_img_overlay(save_path, boundary):
imsave(save_path, boundary, check_contrast=False)
for path in paths:
name = path.split('/')[-1]
img = imread(path)
if apply_contrast:
img = skimage.exposure.equalize_adapthist(img)
if use_prob:
prob_t5 = np.expand_dims(np.load(os.path.join(Params['root_prob'], name.split('.')[0] + '.npy')), 2).astype(
'double') * 255
# We use softmax with temperature 5 as learned features to help generate superpixels.
segments = slic(np.concatenate(( np.expand_dims(img,2), prob_t5), axis = 2), n_segments=n_segments, compactness=compactness) # shape (H, W)
else:
segments = slic(img, n_segments=n_segments, compactness=compactness) # shape (H, W)
# save superpixel label
save_path = Params['tar_dir'] + name.split('.png')[0] + '.json'
save_json(save_path, segments)
# save visualization: superpixel boundary on image
boundary = mark_boundaries(img, segments, mode='thick')
save_path = Params['tar_dir2'] + name
save_img_overlay(save_path, boundary)
if __name__ == '__main__':
subdir = 'ISIC_noise' # 'JSRT_noise'
args = parse_args()
Params = {
'root': '/group/gaozht/Dataset/%s/train/image/' % subdir,
# 'root_prob': '/group/gaozht/nlseg_exp/output/%s_train/heatmap_npy' %args.super_postfix,
'tar_dir': '/group/gaozht/Dataset/%s/train/superpixel_%s/' % (subdir, args.super_postfix),
'tar_dir2': '/group/gaozht/Dataset/%s/train/superpixel_vis_%s/' % (subdir,args.super_postfix),
}
makedir(Params['tar_dir'])
makedir(Params['tar_dir2'])
apply_contrast = False
use_prob = False
n_segments, compactness = 100, 10 # default param for ISIC
# n_segments, compactness = 800, 10 # default param for JSRT lung, heart
# n_segments, compactness = 1200, 10 # default param for JSRT clavicle
paths = sorted(glob(Params['root'] + '*.png'))
print('Total images:', len(paths))
gen_superpixel_label(paths)
|