def my_label2rgboverlay(labels, colors, image, alpha=0.2):
"""
Generates image with segmentation labels on top
Parameters
----------
labels: labels of one image (0, 1)
colors: colormap
image: image (0, 1, c), where c=3 (rgb)
alpha: transparency
"""
image_float = gray2rgb(img_as_float(rgb2gray(image) if
image.shape[2] == 3 else
np.squeeze(image)))
label_image = my_label2rgb(labels, colors)
output = image_float * alpha + label_image * (1 - alpha)
return output
python类gray2rgb()的实例源码
def gray2rgb(image):
"""
Grayscale scale image to RGB image
>>> image = np.eye(3, dtype='uint8') * 255
>>> gray2rgb(image)
array([[[255, 255, 255],
[ 0, 0, 0],
[ 0, 0, 0]],
<BLANKLINE>
[[ 0, 0, 0],
[255, 255, 255],
[ 0, 0, 0]],
<BLANKLINE>
[[ 0, 0, 0],
[ 0, 0, 0],
[255, 255, 255]]], dtype=uint8)
:param numpy array image: Numpy array with range [0,255] and dtype 'uint8'.
:return: RGB image
:rtype: numpy array with range [0,255] and dtype 'uint8'
"""
return skc.gray2rgb(image)
def vis_result(image, seg, gt, file_name='test.png'):
indices = np.where(seg == 1)
indices_gt = np.where(gt == 1)
im_norm = image / image.max()
rgb_image = color.gray2rgb(im_norm)
multiplier = [0., 1., 1.]
multiplier_gt = [1., 1., 0.]
im_seg = rgb_image.copy()
im_gt = rgb_image.copy()
im_seg[indices[0], indices[1], :] *= multiplier
im_gt[indices_gt[0], indices_gt[1], :] *= multiplier_gt
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
plt.imshow(im_seg)
a.set_title('Segmentation')
a = fig.add_subplot(1, 2, 2)
plt.imshow(im_gt)
a.set_title('Ground truth')
plt.savefig(file_name)
def get(self, uri):
i = imread(uri)
if len(i.shape) == 2:
i = gray2rgb(i)
else:
i = i[:, :, :3]
c = self._image_to_color.get(i)
dbg = self._settings['debug']
if dbg is None:
return c
c, imgs = c
b = splitext(basename(uri))[0]
imsave(join(dbg, b + '-resized.jpg'), imgs['resized'])
imsave(join(dbg, b + '-back.jpg'), img_as_float(imgs['back']))
imsave(join(dbg, b + '-skin.jpg'), img_as_float(imgs['skin']))
imsave(join(dbg, b + '-clusters.jpg'), imgs['clusters'])
return c, {
'resized': join(dbg, b + '-resized.jpg'),
'back': join(dbg, b + '-back.jpg'),
'skin': join(dbg, b + '-skin.jpg'),
'clusters': join(dbg, b + '-clusters.jpg'),
}
def load_img(path, grayscale=False, resize=None, order=1):
# Load image
img = io.imread(path)
# Resize
# print('Desired resize: ' + str(resize))
if resize is not None:
img = skimage.transform.resize(img, resize, order=order,
preserve_range=True)
# print('Final resize: ' + str(img.shape))
# Color conversion
if len(img.shape)==2 and not grayscale:
img = gray2rgb(img)
elif len(img.shape)>2 and img.shape[2]==3 and grayscale:
img = rgb2gray(img)
# Return image
return img
def load_img(path, grayscale=False, resize=None, order=1):
# Load image
img = io.imread(path)
# Resize
# print('Desired resize: ' + str(resize))
if resize is not None:
img = skimage.transform.resize(img, resize, order=order,
preserve_range=True)
# print('Final resize: ' + str(img.shape))
# Color conversion
if len(img.shape) == 2 and not grayscale:
img = gray2rgb(img)
elif len(img.shape) > 2 and img.shape[2] == 3 and grayscale:
img = rgb2gray(img)
# Return image
return img
def main(args):
"""
Entry point.
"""
# load the image
img = imread(args.input)
if img.ndim == 2:
img = gray2rgb(img)
elif img.shape[2] == 4:
img = img[:, :, :3]
upper_dim = max(img.shape[:2])
if upper_dim > args.max_dim:
img = rescale(img, args.max_dim/float(upper_dim), order=3)
# compute saliency
start = timeit.default_timer()
img_sal = compute_saliency(img)
runtime = timeit.default_timer() - start
print("Took {0} seconds.".format(runtime))
# save image
(fname, ext) = os.path.splitext(args.input)
out_path = fname + "_saliency" + ext
imsave(out_path, img_sal)
def _normalise_image(image, *, image_cmap=None):
image = img_as_float(image)
if image.ndim == 2:
if image_cmap is None:
image = gray2rgb(image)
else:
image = plt.get_cmap(image_cmap)(image)[..., :3]
return image
def vis_col_im(im, gt):
indices_0 = np.where(gt == 0) # nothing
indices_1 = np.where(gt == 1) # necrosis
indices_2 = np.where(gt == 2) # edema
indices_3 = np.where(gt == 3) # non-enhancing tumor
indices_4 = np.where(gt == 4) # enhancing tumor
im = np.asarray(im, dtype='float32')
im = im*1./im.max()
rgb_image = color.gray2rgb(im)
m0 = [1., 1., 1.]
m1 = [1., 0., 0.]
m2 = [0.2, 1., 0.2]
m3 = [1., 1., 0.2]
m4 = [1., 0.6, 0.2]
im = rgb_image.copy()
im[indices_0[0], indices_0[1], :] *= m0
im[indices_1[0], indices_1[1], :] *= m1
im[indices_2[0], indices_2[1], :] *= m2
im[indices_3[0], indices_3[1], :] *= m3
im[indices_4[0], indices_4[1], :] *= m4
plt.imshow(im)
plt.show()
plt.close()
def col_im(im, gt):
im = np.asarray(im, dtype='float32')
im = im*1./im.max()
rgb_image = color.gray2rgb(im)
im = rgb_image.copy()
if gt is None:
return im
indices_0 = np.where(gt == 0) # nothing
indices_1 = np.where(gt == 1) # necrosis
indices_2 = np.where(gt == 2) # edema
indices_3 = np.where(gt == 3) # non-enhancing tumor
indices_4 = np.where(gt == 4) # enhancing tumor
m0 = [1., 1., 1.]
m1 = [1., 0., 0.] # red: necrosis
m2 = [0.2, 1., 0.2] # green: edema
m3 = [1., 1., 0.2] # yellow: non-enhancing tumor
m4 = [1., 0.6, 0.2] # orange: enhancing tumor
im[indices_0[0], indices_0[1], :] *= m0
im[indices_1[0], indices_1[1], :] *= m1
im[indices_2[0], indices_2[1], :] *= m2
im[indices_3[0], indices_3[1], :] *= m3
im[indices_4[0], indices_4[1], :] *= m4
return im
def vis_col_im(im, gt):
indices_0 = np.where(gt == 0) # nothing
indices_1 = np.where(gt == 1) # necrosis
indices_2 = np.where(gt == 2) # edema
indices_3 = np.where(gt == 3) # non-enhancing tumor
indices_4 = np.where(gt == 4) # enhancing tumor
im = np.asarray(im, dtype='float32')
im = im*1./im.max()
rgb_image = color.gray2rgb(im)
m0 = [1., 1., 1.]
m1 = [1., 0., 0.]
m2 = [0.2, 1., 0.2]
m3 = [1., 1., 0.2]
m4 = [1., 0.6, 0.2]
im = rgb_image.copy()
im[indices_0[0], indices_0[1], :] *= m0
im[indices_1[0], indices_1[1], :] *= m1
im[indices_2[0], indices_2[1], :] *= m2
im[indices_3[0], indices_3[1], :] *= m3
im[indices_4[0], indices_4[1], :] *= m4
plt.imshow(im)
plt.show()
plt.close()
def vis_result(image, seg, gt, title1='Segmentation', title2='Ground truth', savefile=None):
indices = np.where(seg >= 0.5)
indices_gt = np.where(gt >= 0.5)
im_norm = image / image.max()
rgb_image = color.gray2rgb(im_norm)
multiplier = [0., 1., 1.]
multiplier_gt = [1., 1., 0.]
im_seg = rgb_image.copy()
im_gt = rgb_image.copy()
im_seg[indices[0], indices[1], :] *= multiplier
im_gt[indices_gt[0], indices_gt[1], :] *= multiplier_gt
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
plt.imshow(im_seg)
a.set_title(title1)
a = fig.add_subplot(1, 2, 2)
plt.imshow(im_gt)
a.set_title(title2)
if savefile is None:
plt.show()
else:
plt.savefig(savefile)
plt.close()
def my_label2rgboverlay(labels, colors, image, bglabel=None,
bg_color=(0., 0., 0.), alpha=0.2):
image_float = gray2rgb(img_as_float(rgb2gray(image)))
label_image = my_label2rgb(labels, colors, bglabel=bglabel,
bg_color=bg_color)
output = image_float * alpha + label_image * (1 - alpha)
return output
# Save 3 images (Image, mask and result)
def my_label2rgboverlay(labels, colors, image, bglabel=None,
bg_color=(0., 0., 0.), alpha=0.2):
image_float = gray2rgb(img_as_float(rgb2gray(image)))
label_image = my_label2rgb(labels, colors, bglabel=bglabel,
bg_color=bg_color)
output = image_float * alpha + label_image * (1 - alpha)
return output
# Save 3 images (Image, mask and result)
def my_label2rgboverlay(labels, cmap, image, bglabel=None,
bg_color=(0., 0., 0.), alpha=0.2):
'''Superimpose a mask over an image
Convert a label mask to RGB applying a color map and superimposing it
over an image as a transparent overlay'''
image_float = gray2rgb(img_as_float(rgb2gray(image)))
label_image = my_label2rgb(labels, cmap, bglabel=bglabel,
bg_color=bg_color)
output = image_float * alpha + label_image * (1 - alpha)
return output
def vis_col_im(im, seg, gt, file_name='test.png'):
indices_0 = np.where(gt == 0)
indices_1 = np.where(gt == 1) # green - metacarpal - necrosis
indices_2 = np.where(gt == 2) # yellow - proximal - edema
indices_3 = np.where(gt == 3) # orange - middle - enhancing tumor
indices_4 = np.where(gt == 4) # red - distal - nonenhancing tumor
indices_s0 = np.where(seg == 0)
indices_s1 = np.where(seg == 1)
indices_s2 = np.where(seg == 2)
indices_s3 = np.where(seg == 3)
indices_s4 = np.where(seg == 4)
im = im * 1. / im.max()
rgb_image = color.gray2rgb(im)
m0 = [0.6, 0.6, 1.]
m1 = [0.2, 1., 0.2]
m2 = [1., 1., 0.2]
m3 = [1., 0.6, 0.2]
m4 = [1., 0., 0.]
im_gt = rgb_image.copy()
im_seg = rgb_image.copy()
im_gt[indices_0[0], indices_0[1], :] *= m0
im_gt[indices_1[0], indices_1[1], :] *= m1
im_gt[indices_2[0], indices_2[1], :] *= m2
im_gt[indices_3[0], indices_3[1], :] *= m3
im_gt[indices_4[0], indices_4[1], :] *= m4
im_seg[indices_s0[0], indices_s0[1], :] *= m0
im_seg[indices_s1[0], indices_s1[1], :] *= m1
im_seg[indices_s2[0], indices_s2[1], :] *= m2
im_seg[indices_s3[0], indices_s3[1], :] *= m3
im_seg[indices_s4[0], indices_s4[1], :] *= m4
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
plt.imshow(im_seg)
a.set_title('Segmentation')
a = fig.add_subplot(1, 2, 2)
plt.imshow(im_gt)
a.set_title('Ground truth')
plt.savefig(file_name)
plt.close()
def vis_col_result(im, seg, gt, savefile=None):
indices_0 = np.where(gt == 0)
indices_1 = np.where(gt == 1) # metacarpal
indices_2 = np.where(gt == 2) # proximal
indices_3 = np.where(gt == 3) # middle (thumb: distal)
indices_4 = np.where(gt == 4) # distal (thumb: none)
indices_s0 = np.where(seg == 0)
indices_s1 = np.where(seg == 1)
indices_s2 = np.where(seg == 2)
indices_s3 = np.where(seg == 3)
indices_s4 = np.where(seg == 4)
im = im * 1. / im.max()
rgb_image = color.gray2rgb(im)
m0 = [0.6, 0.6, 1.]
m1 = [0.2, 1., 0.2]
m2 = [1., 1., 0.2]
m3 = [1., 0.6, 0.2]
m4 = [1., 0., 0.]
im_gt = rgb_image.copy()
im_seg = rgb_image.copy()
im_gt[indices_0[0], indices_0[1], :] *= m0
im_gt[indices_1[0], indices_1[1], :] *= m1
im_gt[indices_2[0], indices_2[1], :] *= m2
im_gt[indices_3[0], indices_3[1], :] *= m3
im_gt[indices_4[0], indices_4[1], :] *= m4
im_seg[indices_s0[0], indices_s0[1], :] *= m0
im_seg[indices_s1[0], indices_s1[1], :] *= m1
im_seg[indices_s2[0], indices_s2[1], :] *= m2
im_seg[indices_s3[0], indices_s3[1], :] *= m3
im_seg[indices_s4[0], indices_s4[1], :] *= m4
fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
plt.imshow(im_seg)
a.set_title('Segmentation')
a = fig.add_subplot(1, 2, 2)
plt.imshow(im_gt)
a.set_title('Ground truth')
if savefile is not None:
plt.savefig(savefile)
else:
plt.show()
plt.close()
def save_segmented_image(self, filepath_image, modality='t1c', show=False):
'''
Creates an image of original brain with segmentation overlay and save it in ./predictions
INPUT (1) str 'filepath_image': filepath to test image for segmentation, including file extension
(2) str 'modality': imaging modality to use as background. defaults to t1c. options: (flair, t1, t1c, t2)
(3) bool 'show': If true, shows output image. defaults to False.
OUTPUT (1) if show is True, shows image of segmentation results
(2) if show is false, returns segmented image.
'''
modes = {'flair': 0, 't1': 1, 't1c': 2, 't2': 3}
segmentation = self.predict_image(filepath_image, show=False)
print 'segmentation = ' + str(segmentation)
img_mask = np.pad(segmentation, (16, 16), mode='edge')
ones = np.argwhere(img_mask == 1)
twos = np.argwhere(img_mask == 2)
threes = np.argwhere(img_mask == 3)
fours = np.argwhere(img_mask == 4)
test_im = io.imread(filepath_image)
test_back = test_im.reshape(5, 216, 160)[modes[modality]]
# overlay = mark_boundaries(test_back, img_mask)
gray_img = img_as_float(test_back)
# adjust gamma of image
image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
sliced_image = image.copy()
red_multiplier = [1, 0.2, 0.2]
yellow_multiplier = [1, 1, 0.25]
green_multiplier = [0.35, 0.75, 0.25]
blue_multiplier = [0, 0.25, 0.9]
print str(len(ones))
print str(len(twos))
print str(len(threes))
print str(len(fours))
# change colors of segmented classes
for i in xrange(len(ones)):
sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
for i in xrange(len(twos)):
sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
for i in xrange(len(threes)):
sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
for i in xrange(len(fours)):
sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier
#if show=True show the prediction
if show:
print 'Showing...'
io.imshow(sliced_image)
plt.show()
#save the prediction
print 'Saving...'
try:
mkdir_p('./predictions/')
io.imsave('./predictions/' + os.path.basename(filepath_image) + '.png', sliced_image)
print 'prediction saved.'
except:
io.imsave('./predictions/' + os.path.basename(filepath_image) + '.png', sliced_image)
print 'prediction saved.'
brain_tumor_segmentation_models.py 文件源码
项目:nn-segmentation-for-lar
作者: cvdlab
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def save_segmented_image(self, index, test_img, save=False):
"""
Creates an image of original brain with segmentation overlay
:param index: index of image to save
:param test_img: filepath to test image for segmentation, including file extension
:param save: If true, shows output image. (defaults to False)
:return: if show is True, shows image of segmentation results
if show is false, returns segmented image.
"""
segmentation = self.predict_image(test_img)
img_mask = np.pad(segmentation, (16, 16), mode='edge')
ones = np.argwhere(img_mask == 1)
twos = np.argwhere(img_mask == 2)
threes = np.argwhere(img_mask == 3)
fours = np.argwhere(img_mask == 4)
test_im = mpimg.imread(test_img).astype('float')
test_back = rgb2gray(test_im).reshape(5, 216, 160)[-2]
# overlay = mark_boundaries(test_back, img_mask)
gray_img = img_as_float(test_back)
# adjust gamma of image
image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
sliced_image = image.copy()
red_multiplier = [1, 0.2, 0.2]
yellow_multiplier = [1, 1, 0.25]
green_multiplier = [0.35, 0.75, 0.25]
blue_multiplier = [0, 0.25, 0.9]
# change colors of segmented classes
for i in xrange(len(ones)):
sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
for i in xrange(len(twos)):
sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
for i in xrange(len(threes)):
sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
for i in xrange(len(fours)):
sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier
if save:
try:
mkdir_p('./results/')
io.imsave('./results/result' + '_' + str(index) + '.png', sliced_image)
except:
io.imsave('./results/result' + '_' + str(index) + '.png', sliced_image)
else:
return sliced_image