How to create a Run Length Encoding from mask image

Viewed 22

I have an masked image predicted by U-Net. I would like to know how to use it to create a RLE encoding file and save it to a csv along with the mask id please. This is to submit to a kaggle competition. I have some code that I got from here:

Read the image:

example_path = "../input/masked-img/62.tiff"
mask_image = cv2.imread(example_path)

Code for the conversion (fastest one I belive):

def rle_encode(mask_image):
    pixels = mask_image.flatten()
    # We avoid issues with '1' at the start or end (at the corners of 
    # the original image) by setting those pixels to '0' explicitly.
    # We do not expect these to be non-zero for an accurate mask, 
    # so this should not harm the score.
    pixels[0] = 0
    pixels[-1] = 0
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
    runs[1::2] = runs[1::2] - runs[:-1:2]
    return runs


def rle_to_string(runs):
    return ' '.join(str(x) for x in runs)

Would anyone be able to help me in this regards.

Thanks & Best Regards

Schroter Michael

0 Answers
Related