Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. import numpy
  2. class RLECoder():
  3.     def __init__(self):
  4.         pass
  5.    
  6.     def encode(self, binary_image):
  7.         start = None
  8.         length = None
  9.        
  10.         result = [*binary_image.shape]
  11.  
  12.         for index in range(len(binary_image.flat)):
  13.  
  14.             if binary_image.flat[index] > 0.5:
  15.                 if start is None:
  16.                     start = index
  17.                     length = 1
  18.  
  19.                 else:
  20.                     length += 1
  21.             else:
  22.                 if start is not None:
  23.                     result.append(start + 1)
  24.                     result.append(length)
  25.                     start = None
  26.                     length = None
  27.         if start is not None:
  28.             result.append(start + 1)
  29.             result.append(length)
  30.         return result
  31.  
  32.     def decode(self, rle):
  33.         shape = rle[:2]
  34.         code = rle[2:]
  35.         image = numpy.zeros(shape)
  36.         image = image.flatten()
  37.  
  38.         for index in range(0, len(code), 2):
  39.             start = code[index] - 1
  40.             length = code[index + 1]
  41.             image[start:start+length] = 1
  42.  
  43.         image = image.reshape(shape)
  44.         return image
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement