Skip to content

Instantly share code, notes, and snippets.

@dmitrysarov
Last active January 11, 2019 09:31
Show Gist options
  • Select an option

  • Save dmitrysarov/8aced6cc3467d366900f50e9471b9cb1 to your computer and use it in GitHub Desktop.

Select an option

Save dmitrysarov/8aced6cc3467d366900f50e9471b9cb1 to your computer and use it in GitHub Desktop.
These lines can help some one to transform grayscale mask to multichannel (equal to number of classes) one hot mask.
def gray2hot(graymask, num_classes=2, include_background=True):
'''Convert grayscale image of mask to multichannel mask
if include_background=True number of channels in output will be
num_classes + 1
'''
graymask = graymask.astype(np.int32)
onehot_mask = np.zeros((graymask.shape[0], graymask.shape[1], num_classes+include_background), dtype=np.int32) # +1 relate to background
if include_background:
onehot_mask[:, :, 0] = 1 # initialize all as background at first
if np.all(graymask == 0):
return onehot_mask
indx = list(np.nonzero(graymask))
indx.append((graymask[np.nonzero(graymask)]-(not include_background)))
onehot_mask[tuple(indx)] = 1
if include_background:
onehot_mask[:, :, 0] = onehot_mask[:, :, 0] - np.sum(onehot_mask[...,1:], axis=-1) # remove backgound from where foreground exist
return onehot_mask
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment