Skip to content

coerce to list for serialization

Matthew Bernstein requested to merge fix_encode_run_length into master

A small change to encode_run_length to match the expected behavior seen in Mask.to_array_rle.

Motivating example:

import numpy as np
import kwimage as ki
import kwcoco as kc

ki.imwrite('img.png', np.zeros((10,10,3)))
ki.imwrite('seg.png', np.zeros((10,10,1)))

dset = kc.CocoDataset()
cid = dset.add_category(name='name')

gid = dset.add_image(file_name='img.png')

mask = ki.imread('seg.png')
rle = ki.encode_run_length(mask, binary=True)

ann = {
    category_id: cid,
    image_id: gid,
    segmentation: rle
}

dset.add_annotation(**ann)

# this is a valid CocoDataset
assert not dset.validate()['errors']

# but...
dset.dump('dset.kwcoco.json')
TypeError: Object of type ndarray is not JSON serializable

The problem is in rle:

{'shape': (10, 10), 'counts': array([100]), 'binary': True, 'order': 'C'}

Setting rle['counts'] = rle['counts'].tolist() fixes it. This both changes it from np.ndarray to list and coerces it from np.int64 to base python's int, neither of which are sufficient alone.

Merge request reports