本文整理汇总了Python中pycocotools.mask.encode方法的典型用法代码示例。如果您正苦于以下问题:Python mask.encode方法的具体用法?Python mask.encode怎么用?Python mask.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.mask
的用法示例。
在下文中一共展示了mask.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __get_annotation__
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def __get_annotation__(self, mask, image=None):
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
segmentation = []
for contour in contours:
# Valid polygons have >= 6 coordinates (3 points)
if contour.size >= 6:
segmentation.append(contour.flatten().tolist())
RLEs = cocomask.frPyObjects(segmentation, mask.shape[0], mask.shape[1])
RLE = cocomask.merge(RLEs)
# RLE = cocomask.encode(np.asfortranarray(mask))
area = cocomask.area(RLE)
[x, y, w, h] = cv2.boundingRect(mask)
if image is not None:
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
cv2.drawContours(image, contours, -1, (0,255,0), 1)
cv2.rectangle(image,(x,y),(x+w,y+h), (255,0,0), 2)
cv2.imshow("", image)
cv2.waitKey(1)
return segmentation, [x, y, w, h], area
示例2: build_coco_results
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def build_coco_results(dataset, image_ids, rois, class_ids, scores, masks):
"""Arrange resutls to match COCO specs in http://cocodataset.org/#format
"""
# If no results, return an empty list
if rois is None:
return []
results = []
for image_id in image_ids:
# Loop through detections
for i in range(rois.shape[0]):
class_id = class_ids[i]
score = scores[i]
bbox = np.around(rois[i], 1)
mask = masks[:, :, i]
result = {
"image_id": image_id,
"category_id": dataset.get_source_class_id(class_id, "coco"),
"bbox": [bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0]],
"score": score,
"segmentation": maskUtils.encode(np.asfortranarray(mask))
}
results.append(result)
return results
示例3: forward
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def forward(self, x, boxes):
import pycocotools.mask as mask_util
import numpy as np
results = super(MaskPostProcessorCOCOFormat, self).forward(x, boxes)
for result in results:
masks = result.get_field("mask").cpu()
rles = [
mask_util.encode(np.array(mask[0, :, :, np.newaxis], order="F"))[0]
for mask in masks
]
for rle in rles:
rle["counts"] = rle["counts"].decode("utf-8")
result.add_field("mask", rles)
return results
# the next two functions should be merged inside Masker
# but are kept here for the moment while we need them
# temporarily gor paste_mask_in_image
示例4: load_image
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def load_image(filename, id_divisor=1000):
img = np.array(Image.open(filename))
obj_ids = np.unique(img)
objects = []
mask = np.zeros(img.shape, dtype=np.uint8, order="F") # Fortran order needed for pycocos RLE tools
for idx, obj_id in enumerate(obj_ids):
if obj_id == 0: # background
continue
mask.fill(0)
pixels_of_elem = np.where(img == obj_id)
mask[pixels_of_elem] = 1
objects.append(SegmentedObject(
rletools.encode(mask),
obj_id // id_divisor,
obj_id
))
return objects
示例5: _create_anno
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def _create_anno(msk, lb, sc, img_id, anno_id, ar=None, crw=None):
H, W = msk.shape
if crw is None:
crw = False
msk = np.asfortranarray(msk.astype(np.uint8))
rle = mask_tools.encode(msk)
if ar is None:
# We compute dummy area to pass to pycocotools.
# Note that area dependent scores are ignored afterwards.
ar = mask_tools.area(rle)
if crw is None:
crw = False
# Rounding is done to make the result consistent with COCO.
anno = {
'image_id': img_id, 'category_id': lb,
'segmentation': rle,
'area': ar,
'id': anno_id,
'iscrowd': crw}
if sc is not None:
anno.update({'score': sc})
return anno
示例6: encode_mask_results
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def encode_mask_results(mask_results):
"""Encode bitmap mask to RLE code.
Args:
mask_results (list | tuple[list]): bitmap mask results.
In mask scoring rcnn, mask_results is a tuple of (segm_results,
segm_cls_score).
Returns:
list | tuple: RLE encoded mask.
"""
if isinstance(mask_results, tuple): # mask scoring
cls_segms, cls_mask_scores = mask_results
else:
cls_segms = mask_results
num_classes = len(cls_segms)
encoded_mask_results = [[] for _ in range(num_classes)]
for i in range(len(cls_segms)):
for cls_segm in cls_segms[i]:
encoded_mask_results[i].append(
mask_util.encode(
np.array(
cls_segm[:, :, np.newaxis], order='F',
dtype='uint8'))[0]) # encoded with RLE
if isinstance(mask_results, tuple):
return encoded_mask_results, cls_mask_scores
else:
return encoded_mask_results
示例7: rle_from_binary
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def rle_from_binary(prediction):
prediction = np.asfortranarray(prediction)
return cocomask.encode(prediction)
示例8: _RleCompress
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def _RleCompress(masks):
"""Compresses mask using Run-length encoding provided by pycocotools.
Args:
masks: uint8 numpy array of shape [mask_height, mask_width] with values in
{0, 1}.
Returns:
A pycocotools Run-length encoding of the mask.
"""
return mask.encode(np.asfortranarray(masks))
示例9: DensePoseMask2Polys
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def DensePoseMask2Polys(MaskGen):
Polys = []
for i in range(1, 15):
current_polys = []
current_mask = np.zeros([256, 256], dtype='uint8', order='F')
idx = (MaskGen == i)
current_mask[idx] = MaskGen[idx]
if len(idx):
current_polys = mask_utils.encode(current_mask)
Polys.append(current_polys)
return Polys
示例10: process_panoptic_prediction
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def process_panoptic_prediction(panoptic_pred, num_stuff, idx, img_size, original_size):
# Extract panoptic prediction
msk_pred, cat_pred, obj_pred, iscrowd_pred = panoptic_pred
bbx_pred = extract_boxes(msk_pred, cat_pred.numel())
# Convert bbx and redo clamping
bbx_pred[:, [0, 2]] = (bbx_pred[:, [0, 2]] / img_size[0] * original_size[0]).clamp(min=0, max=original_size[0])
bbx_pred[:, [1, 3]] = (bbx_pred[:, [1, 3]] / img_size[1] * original_size[1]).clamp(min=0, max=original_size[1])
bbx_pred_size = bbx_pred[:, 2:] - bbx_pred[:, :2]
outs = []
for i, (obj_i, cat_i, bbx_i, iscrowd_i, bbx_size_i) in enumerate(zip(
obj_pred, cat_pred, bbx_pred, iscrowd_pred, bbx_pred_size)):
if iscrowd_i.item() == 1 or cat_i.item() < num_stuff or cat_i.item() == 255:
continue
out = dict(image_id=idx, category_id=int(cat_i.item()), score=float(obj_i.item()))
out["bbox"] = [
float(bbx_i[1].item()),
float(bbx_i[0].item()),
float(bbx_size_i[1].item()),
float(bbx_size_i[0].item()),
]
segmentation = msk_pred == i
segmentation = Image.fromarray(segmentation.numpy()).resize(original_size[::-1], Image.NEAREST)
out["segmentation"] = mask_encode(np.asfortranarray(np.array(segmentation)))
out["segmentation"]["counts"] = str(out["segmentation"]["counts"], "utf-8")
outs.append(out)
return outs
示例11: build_coco_results
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def build_coco_results(dataset, image_ids, rois, class_ids, scores, masks):
"""Arrange resutls to match COCO specs in http://cocodataset.org/#format
"""
# If no results, return an empty list
if rois is None:
return []
results = []
for image_id in image_ids:
# Loop through detections
for i in range(rois.shape[0]):
class_id = class_ids[i]
score = scores[i]
bbox = np.around(rois[i], 1)
mask = masks[:, :, i]
encodedMask = maskUtils.encode(np.asfortranarray(mask))
encodedMask['counts'] = encodedMask['counts'].decode('utf8')
result = {
"image_id": image_id,
"category_id": dataset.get_source_class_id(class_id, "coco"),
"bbox": [bbox[1].item(), bbox[0].item(), (bbox[3] - bbox[1]).item(), (bbox[2] - bbox[0]).item()],
"score": score.item(),
"segmentation": encodedMask,
}
results.append(result)
return results
示例12: convert_panoptic_to_detection_coco_format_single_core
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def convert_panoptic_to_detection_coco_format_single_core(
proc_id, annotations_set, categories, segmentations_folder, things_only
):
annotations_detection = []
for working_idx, annotation in enumerate(annotations_set):
if working_idx % 100 == 0:
print('Core: {}, {} from {} images processed'.format(proc_id,
working_idx,
len(annotations_set)))
file_name = '{}.png'.format(annotation['file_name'].rsplit('.')[0])
try:
pan_format = np.array(
Image.open(os.path.join(segmentations_folder, file_name)), dtype=np.uint32
)
except IOError:
raise KeyError('no prediction png file for id: {}'.format(annotation['image_id']))
pan = rgb2id(pan_format)
for segm_info in annotation['segments_info']:
if things_only and categories[segm_info['category_id']]['isthing'] != 1:
continue
mask = (pan == segm_info['id']).astype(np.uint8)
mask = np.expand_dims(mask, axis=2)
segm_info.pop('id')
segm_info['image_id'] = annotation['image_id']
segm_info['segmentation'] = COCOmask.encode(np.asfortranarray(mask))[0]
annotations_detection.append(segm_info)
print('Core: {}, all {} images processed'.format(proc_id, len(annotations_set)))
return annotations_detection
示例13: prepare_for_coco_segmentation
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def prepare_for_coco_segmentation(self, predictions):
coco_results = []
for original_id, prediction in predictions.items():
if len(prediction) == 0:
continue
scores = prediction["scores"]
labels = prediction["labels"]
masks = prediction["masks"]
masks = masks > 0.5
scores = prediction["scores"].tolist()
labels = prediction["labels"].tolist()
rles = [
mask_util.encode(
np.array(mask[0, :, :, np.newaxis], order="F")
)[0]
for mask in masks
]
for rle in rles:
rle["counts"] = rle["counts"].decode("utf-8")
coco_results.extend(
[
{
"image_id": original_id,
"category_id": labels[k],
"segmentation": rle,
"score": scores[k],
}
for k, rle in enumerate(rles)
]
)
return coco_results
示例14: flip_segms
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def flip_segms(segms, height, width):
"""Left/right flip each mask in a list of masks."""
def _flip_poly(poly, width):
flipped_poly = np.array(poly)
flipped_poly[0::2] = width - np.array(poly[0::2]) - 1
return flipped_poly.tolist()
def _flip_rle(rle, height, width):
if 'counts' in rle and type(rle['counts']) == list:
# Magic RLE format handling painfully discovered by looking at the
# COCO API showAnns function.
rle = mask_util.frPyObjects([rle], height, width)
mask = mask_util.decode(rle)
mask = mask[:, ::-1, :]
rle = mask_util.encode(np.array(mask, order='F', dtype=np.uint8))
return rle
flipped_segms = []
for segm in segms:
if is_poly(segm):
# Polygon format
flipped_segms.append([_flip_poly(poly, width) for poly in segm])
else:
# RLE format
flipped_segms.append(_flip_rle(segm, height, width))
return flipped_segms
示例15: flip_segms
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import encode [as 别名]
def flip_segms(self, segms, height, width):
"""Left/right flip each mask in a list of masks."""
flipped_segms = []
for segm in segms:
mask = np.fliplr(annToMask(segm, height, width))
rle = mask_util.encode(np.array(mask, order='F', dtype=np.uint8))
flipped_segms.append(rle)
return flipped_segms