• API
• FAQ
• Tools
• Archive
SHARE
TWEET # Untitled a guest May 23rd, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import numpy as np
2. from matplotlib import pyplot as plt
3.
4.
6.     pixels = mask.T.flatten()
7.     # We need to allow for cases where there is a '1' at either end of the sequence.
8.     # We do this by padding with a zero at each end when needed.
9.     use_padding = False
10.     if pixels or pixels[-1]:
11.         use_padding = True
12.         pixel_padded = np.zeros([len(pixels) + 2], dtype=pixels.dtype)
13.         pixel_padded[1:-1] = pixels
14.         pixels = pixel_padded
15.     rle = np.where(pixels[1:] != pixels[:-1]) + 2
17.         rle = rle - 1
18.     rle[1::2] = rle[1::2] - rle[:-1:2]
19.     return rle
20.
21.
22. def rle_to_string(runs):
23.     return ' '.join(str(x) for x in runs)
24.
25.
26. # Used only for testing.
27. # This is copied from https://www.kaggle.com/paulorzp/run-length-encode-and-decode.
28. # Thanks to Paulo Pinto.
30.     s = rle_str.split()
31.     starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
32.     starts -= 1
33.     ends = starts + lengths
35.     for lo, hi in zip(starts, ends):
36.         mask[lo:hi] = 1
38.
39. def rle_decode2(mask_rle, shape):
40.     '''
41.     mask_rle: run-length as string formated (start length)
42.     shape: (height,width) of array to return
43.     Returns numpy array, 1 - mask, 0 - background
44.
45.     '''
46.     s = mask_rle.split()
47.     starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]
48.     starts -= 1
49.     ends = starts + lengths
50.     img = np.zeros(shape*shape, dtype=np.uint8)
51.     for lo, hi in zip(starts, ends):
52.         img[lo:hi] = 1
53.     return img.reshape(shape)
54.