Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- from matplotlib import pyplot as plt
- def rle_encode(mask):
- pixels = mask.T.flatten()
- # We need to allow for cases where there is a '1' at either end of the sequence.
- # We do this by padding with a zero at each end when needed.
- use_padding = False
- if pixels[0] or pixels[-1]:
- use_padding = True
- pixel_padded = np.zeros([len(pixels) + 2], dtype=pixels.dtype)
- pixel_padded[1:-1] = pixels
- pixels = pixel_padded
- rle = np.where(pixels[1:] != pixels[:-1])[0] + 2
- if use_padding:
- rle = rle - 1
- rle[1::2] = rle[1::2] - rle[:-1:2]
- return rle
- def rle_to_string(runs):
- return ' '.join(str(x) for x in runs)
- # Used only for testing.
- # This is copied from https://www.kaggle.com/paulorzp/run-length-encode-and-decode.
- # Thanks to Paulo Pinto.
- def rle_decode(rle_str, mask_shape, mask_dtype):
- s = rle_str.split()
- starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
- starts -= 1
- ends = starts + lengths
- mask = np.zeros(np.prod(mask_shape), dtype=mask_dtype)
- for lo, hi in zip(starts, ends):
- mask[lo:hi] = 1
- return mask.reshape(mask_shape[::-1]).T
- def rle_decode2(mask_rle, shape):
- '''
- mask_rle: run-length as string formated (start length)
- shape: (height,width) of array to return
- Returns numpy array, 1 - mask, 0 - background
- '''
- s = mask_rle.split()
- starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
- starts -= 1
- ends = starts + lengths
- img = np.zeros(shape[0]*shape[1], dtype=np.uint8)
- for lo, hi in zip(starts, ends):
- img[lo:hi] = 1
- return img.reshape(shape)
- def plt_mask(data):
- plt.imshow(data, interpolation='nearest')
- plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement