本文整理汇总了Python中pycocotools.mask.decode方法的典型用法代码示例。如果您正苦于以下问题:Python mask.decode方法的具体用法?Python mask.decode怎么用?Python mask.decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.mask
的用法示例。
在下文中一共展示了mask.decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testSingleImageDetectionMaskExport
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def testSingleImageDetectionMaskExport(self):
masks = np.array(
[[[1, 1,], [1, 1]],
[[0, 0], [0, 1]],
[[0, 0], [0, 0]]], dtype=np.uint8)
classes = np.array([1, 2, 3], dtype=np.int32)
scores = np.array([0.8, 0.2, 0.7], dtype=np.float32)
coco_annotations = coco_tools.ExportSingleImageDetectionMasksToCoco(
image_id='first_image',
category_id_set=set([1, 2, 3]),
detection_classes=classes,
detection_scores=scores,
detection_masks=masks)
expected_counts = ['04', '31', '4']
for i, mask_annotation in enumerate(coco_annotations):
self.assertEqual(mask_annotation['segmentation']['counts'],
expected_counts[i])
self.assertTrue(np.all(np.equal(mask.decode(
mask_annotation['segmentation']), masks[i])))
self.assertEqual(mask_annotation['image_id'], 'first_image')
self.assertEqual(mask_annotation['category_id'], classes[i])
self.assertAlmostEqual(mask_annotation['score'], scores[i])
示例2: polys_to_mask_wrt_box
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def polys_to_mask_wrt_box(polygons, box, M):
"""Convert from the COCO polygon segmentation format to a binary mask
encoded as a 2D array of data type numpy.float32. The polygon segmentation
is understood to be enclosed in the given box and rasterized to an M x M
mask. The resulting mask is therefore of shape (M, M).
"""
w = box[2] - box[0]
h = box[3] - box[1]
w = np.maximum(w, 1)
h = np.maximum(h, 1)
polygons_norm = []
for poly in polygons:
p = np.array(poly, dtype=np.float32)
p[0::2] = (p[0::2] - box[0]) * M / w
p[1::2] = (p[1::2] - box[1]) * M / h
polygons_norm.append(p)
rle = mask_util.frPyObjects(polygons_norm, M, M)
mask = np.array(mask_util.decode(rle), dtype=np.float32)
# Flatten in case polygons was a list
mask = np.sum(mask, axis=2)
mask = np.array(mask > 0, dtype=np.float32)
return mask
示例3: to_mask
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def to_mask(polys, size):
"""Convert list of polygons to full size binary mask
Parameters
----------
polys : list of numpy.ndarray
Numpy.ndarray with shape (N, 2) where N is the number of bounding boxes.
The second axis represents points of the polygons.
Specifically, these are :math:`(x, y)`.
size : tuple
Tuple of length 2: (width, height).
Returns
-------
numpy.ndarray
Full size binary mask of shape (height, width)
"""
try_import_pycocotools()
import pycocotools.mask as cocomask
width, height = size
polys = [p.flatten().tolist() for p in polys]
rles = cocomask.frPyObjects(polys, height, width)
rle = cocomask.merge(rles)
return cocomask.decode(rle)
示例4: polys2mask_wrt_box
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def polys2mask_wrt_box(polygons, box, target_size):
"""Convert from the COCO polygon segmentation format to a binary mask
encoded as a 2D array of data type numpy.float32. The polygon segmentation
is understood to be enclosed in the given box and rasterized to an M x M
mask. The resulting mask is therefore of shape (M, M).
"""
w = box[2] - box[0]
h = box[3] - box[1]
w = np.maximum(w, 1)
h = np.maximum(h, 1)
polygons_norm = []
for poly in polygons:
p = np.array(poly, dtype=np.float32)
p[0::2] = (p[0::2] - box[0]) * target_size[0] / w
p[1::2] = (p[1::2] - box[1]) * target_size[1] / h
polygons_norm.append(p)
rle = mask_util.frPyObjects(polygons_norm, target_size[1], target_size[0])
mask = np.array(mask_util.decode(rle), dtype=np.float32)
# Flatten in case polygons was a list
mask = np.sum(mask, axis=2)
mask = np.array(mask > 0, dtype=np.float32)
return mask
示例5: polys_to_mask_wrt_box
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def polys_to_mask_wrt_box(polygons, box, M):
"""Convert from the COCO polygon segmentation format to a binary mask
encoded as a 2D array of data type numpy.float32. The polygon segmentation
is understood to be enclosed in the given box and rasterized to an M x M
mask. The resulting mask is therefore of shape (M, M).
"""
w = box[2] - box[0]
h = box[3] - box[1]
w = np.maximum(w, 1)
h = np.maximum(h, 1)
polygons_norm = []
for poly in polygons:
p = np.array(poly, dtype=np.float32)
p[0::2] = (p[0::2] - box[0]) * M / w
p[1::2] = (p[1::2] - box[1]) * M / h
polygons_norm.append(p)
rle = mask_util.frPyObjects(polygons_norm, M, M)
mask = np.array(mask_util.decode(rle), dtype=np.float32)
# Flatten in case polygons was a list
mask = np.sum(mask, axis=2)
mask = np.array(mask > 0, dtype=np.float32)
return mask
示例6: load_ann
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def load_ann(img,img_filename,annotation_filename):
img_filename = img_filename.decode('utf-8')
anns_for_img = self.filename_to_coco_anns[img_filename.split("/")[-1]]
ann_id = int(annotation_filename.decode('utf-8'))
ann = anns_for_img[ann_id]
img_h, img_w = img.shape[:-1]
if ann['area'] > 1 and isinstance(ann['segmentation'], list):
segs = ann['segmentation']
valid_segs = [np.asarray(p).reshape(-1, 2) for p in segs if len(p) >= 6]
if len(valid_segs) < len(segs):
print("Image {} has invalid polygons!".format(img_filename))
output_ann = np.asarray(self.segmentation_to_mask(valid_segs, img_h, img_w), dtype='uint8')[
..., np.newaxis] # Should be 1s and 0s
else:
output_ann = np.zeros((img_h, img_w, 1), dtype="uint8")
return output_ann
示例7: _poly2mask
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def _poly2mask(self, mask_ann, img_h, img_w):
"""Private function to convert masks represented with polygon to
bitmaps.
Args:
mask_ann (list | dict): Polygon mask annotation input.
img_h (int): The height of output mask.
img_w (int): The width of output mask.
Returns:
numpy.ndarray: The decode bitmap mask of shape (img_h, img_w).
"""
if isinstance(mask_ann, list):
# polygon -- a single object might consist of multiple parts
# we merge all parts into one mask rle code
rles = maskUtils.frPyObjects(mask_ann, img_h, img_w)
rle = maskUtils.merge(rles)
elif isinstance(mask_ann['counts'], list):
# uncompressed RLE
rle = maskUtils.frPyObjects(mask_ann, img_h, img_w)
else:
# rle
rle = mask_ann
mask = maskUtils.decode(rle)
return mask
示例8: polygon_to_bitmap
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def polygon_to_bitmap(polygons, height, width):
"""Convert masks from the form of polygons to bitmaps.
Args:
polygons (list[ndarray]): masks in polygon representation
height (int): mask height
width (int): mask width
Return:
ndarray: the converted masks in bitmap representation
"""
rles = maskUtils.frPyObjects(polygons, height, width)
rle = maskUtils.merge(rles)
bitmap_mask = maskUtils.decode(rle).astype(np.bool)
return bitmap_mask
示例9: binary_from_rle
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def binary_from_rle(rle):
return cocomask.decode(rle)
示例10: convert
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def convert(self, mode):
width, height = self.size
if mode == "mask":
rles = mask_utils.frPyObjects(
[p.numpy() for p in self.polygons], height, width
)
rle = mask_utils.merge(rles)
mask = mask_utils.decode(rle)
mask = torch.from_numpy(mask)
# TODO add squeeze?
return mask
示例11: show_result
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def show_result(img, result, class_names, score_thr=0.3, out_file=None):
"""Visualize the detection results on the image.
Args:
img (str or np.ndarray): Image filename or loaded image.
result (tuple[list] or list): The detection result, can be either
(bbox, segm) or just bbox.
class_names (list[str] or tuple[str]): A list of class names.
score_thr (float): The threshold to visualize the bboxes and masks.
out_file (str, optional): If specified, the visualization result will
be written to the out file instead of shown in a window.
"""
assert isinstance(class_names, (tuple, list))
img = mmcv.imread(img)
if isinstance(result, tuple):
bbox_result, segm_result = result
else:
bbox_result, segm_result = result, None
bboxes = np.vstack(bbox_result)
# draw segmentation masks
if segm_result is not None:
segms = mmcv.concat_list(segm_result)
inds = np.where(bboxes[:, -1] > score_thr)[0]
for i in inds:
color_mask = np.random.randint(0, 256, (1, 3), dtype=np.uint8)
mask = maskUtils.decode(segms[i]).astype(np.bool)
img[mask] = img[mask] * 0.5 + color_mask * 0.5
# draw bounding boxes
labels = [
np.full(bbox.shape[0], i, dtype=np.int32)
for i, bbox in enumerate(bbox_result)
]
labels = np.concatenate(labels)
mmcv.imshow_det_bboxes(
img.copy(),
bboxes,
labels,
class_names=class_names,
score_thr=score_thr,
show=out_file is None,
out_file=out_file)
示例12: seg2poly_old
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def seg2poly_old(rle):
# TODO: debug for this function
"""
This function transform a single encoded RLE to a single poly
:param seg: RlE
:return: poly
"""
# try:
# binary_mask = mask_utils.decode(rle)
# contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL)
# contour_lens = np.array(list(map(len, contours)))
# max_id = contour_lens.argmax()
# max_contour = contours[max_id]
# rect = cv2.minAreaRect(max_contour)
# poly = cv2.boxPoints(rect)
# return poly
# except:
# return -1
try:
binary_mask = mask_utils.decode(rle)
contours, hierarchy = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# len is not appropriate
# contour_lens = np.array(list(map(len, contours)))
# max_id = contour_lens.argmax()
contour_areas = np.array(list(map(cv2.contourArea, contours)))
max_id = contour_areas.argmax()
max_contour = contours[max_id]
rect = cv2.minAreaRect(max_contour)
poly = cv2.boxPoints(rect)
poly = TuplePoly2Poly(poly)
return poly
except:
return []
示例13: testExportSegmentsToCOCO
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def testExportSegmentsToCOCO(self):
image_ids = ['first', 'second']
detection_masks = [np.array(
[[[0, 1, 0, 1], [0, 1, 1, 0], [0, 0, 0, 1], [0, 1, 0, 1]]],
dtype=np.uint8), np.array(
[[[0, 1, 0, 1], [0, 1, 1, 0], [0, 0, 0, 1], [0, 1, 0, 1]]],
dtype=np.uint8)]
for i, detection_mask in enumerate(detection_masks):
detection_masks[i] = detection_mask[:, :, :, None]
detection_scores = [np.array([.8], np.float), np.array([.7], np.float)]
detection_classes = [np.array([1], np.int32), np.array([1], np.int32)]
categories = [{'id': 0, 'name': 'person'},
{'id': 1, 'name': 'cat'},
{'id': 2, 'name': 'dog'}]
output_path = os.path.join(tf.test.get_temp_dir(), 'segments.json')
result = coco_tools.ExportSegmentsToCOCO(
image_ids,
detection_masks,
detection_scores,
detection_classes,
categories,
output_path=output_path)
with tf.gfile.GFile(output_path, 'r') as f:
written_result = f.read()
written_result = json.loads(written_result)
mask_load = mask.decode([written_result[0]['segmentation']])
self.assertTrue(np.allclose(mask_load, detection_masks[0]))
self.assertAlmostEqual(result, written_result)
示例14: annToMask
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def annToMask(self, ann, height, width):
"""
Convert annotation which can be polygons, uncompressed RLE, or RLE to binary mask.
:return: binary mask (numpy 2D array)
"""
rle = self.annToRLE(ann, height, width)
m = maskUtils.decode(rle)
return m
############################################################
# COCO Evaluation
############################################################
示例15: _decodeUvData
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import decode [as 别名]
def _decodeUvData(self, dt):
from PIL import Image
from io import StringIO
uvData = dt['uv_data']
uvShape = dt['uv_shape']
fStream = StringIO.StringIO(uvData.decode('base64'))
im = Image.open(fStream)
data = np.rollaxis(np.array(im.getdata(), dtype=np.uint8), -1, 0)
dt['uv'] = data.reshape(uvShape)
del dt['uv_data']
del dt['uv_shape']