• 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.
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.
10.     if pixels[0] or pixels[-1]:
12.         pixel_padded = np.zeros([len(pixels) + 2], dtype=pixels.dtype)
15.     rle = np.where(pixels[1:] != pixels[:-1])[0] + 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):
38.
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.     '''
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[0]*shape[1], dtype=np.uint8)
51.     for lo, hi in zip(starts, ends):
52.         img[lo:hi] = 1
53.     return img.reshape(shape)
54.