Created
July 11, 2019 22:14
-
-
Save pculliton/209398a2a52867580c6103e25e55d93c to your computer and use it in GitHub Desktop.
Mask encoding example for Kaggle OpenImages Instance Segmentation Competition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import numpy as np | |
from pycocotools import _mask as coco_mask | |
import typing as t | |
import zlib | |
def encode_binary_mask(mask: np.ndarray) -> t.Text: | |
"""Converts a binary mask into OID challenge encoding ascii text.""" | |
# check input mask -- | |
if mask.dtype != np.bool: | |
raise ValueError( | |
"encode_binary_mask expects a binary mask, received dtype == %s" % | |
mask.dtype) | |
mask = np.squeeze(mask) | |
if len(mask.shape) != 2: | |
raise ValueError( | |
"encode_binary_mask expects a 2d mask, received shape == %s" % | |
mask.shape) | |
# convert input mask to expected COCO API input -- | |
mask_to_encode = mask.reshape(mask.shape[0], mask.shape[1], 1) | |
mask_to_encode = mask_to_encode.astype(np.uint8) | |
mask_to_encode = np.asfortranarray(mask_to_encode) | |
# RLE encode mask -- | |
encoded_mask = coco_mask.encode(mask_to_encode)[0]["counts"] | |
# compress and base64 encoding -- | |
binary_str = zlib.compress(encoded_mask, zlib.Z_BEST_COMPRESSION) | |
base64_str = base64.b64encode(binary_str) | |
return base64_str |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment