Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import numpy as np
  2. from matplotlib import pyplot as plt
  3.  
  4.  
  5. def rle_encode(mask):
  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[0] 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])[0] + 2
  16. if use_padding:
  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.
  29. def rle_decode(rle_str, mask_shape, mask_dtype):
  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
  34. mask = np.zeros(np.prod(mask_shape), dtype=mask_dtype)
  35. for lo, hi in zip(starts, ends):
  36. mask[lo:hi] = 1
  37. return mask.reshape(mask_shape[::-1]).T
  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[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.  
  55. def plt_mask(data):
  56. plt.imshow(data, interpolation='nearest')
  57. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement