本文整理汇总了Python中pycocotools.mask.toBbox方法的典型用法代码示例。如果您正苦于以下问题:Python mask.toBbox方法的具体用法?Python mask.toBbox怎么用?Python mask.toBbox使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.mask
的用法示例。
在下文中一共展示了mask.toBbox方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: group2mmdetection
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def group2mmdetection(group: dict) -> dict:
image_id, group = group
assert group['Width'].max() == group['Width'].min()
assert group['Height'].max() == group['Height'].min()
height, width = group['Height'].max(), group['Width'].max()
rles = group['EncodedPixels'].apply(lambda x: kaggle2coco(list(map(int, x.split())), height, width)).tolist()
rles = mutils.frPyObjects(rles, height, width)
masks = mutils.decode(rles)
bboxes = mutils.toBbox(mutils.encode(np.asfortranarray(masks.astype(np.uint8))))
bboxes[:, 2] += bboxes[:, 0]
bboxes[:, 3] += bboxes[:, 1]
return {
'filename': image_id,
'width': width,
'height': height,
'ann':
{
'bboxes': np.array(bboxes, dtype=np.float32),
'original_labels': group['ClassId'].values,
'labels': group['ClassId'].apply(lambda x: x.split('_')[0]).values.astype(np.int) + 1,
'masks': rles
}
}
示例2: encode_mask_to_poly
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def encode_mask_to_poly(mask, mask_id, image_id):
if len(mask.shape) == 3:
mask = cv.cvtColor(mask, cv.COLOR_BGR2GRAY)
kernel = np.ones((2, 2), np.uint8)
mask = cv.dilate(mask, kernel, iterations=1)
_, C, h = cv.findContours(mask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)
seg = [[float(x) for x in contour.flatten()] for contour in C]
seg = [cont for cont in seg if len(cont) > 4] # filter all polygons that are boxes
rle = mask_util.frPyObjects(seg, mask.shape[0], mask.shape[1])
return {
'area': float(sum(mask_util.area(rle))),
'bbox': list(mask_util.toBbox(rle)[0]),
'category_id': 1,
'id': mask_id,
'image_id': image_id,
'iscrowd': 0,
'segmentation': seg
}
示例3: mask_to_mscoco
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def mask_to_mscoco(alpha, annotations, img_id, mode='rle'):
if mode == 'rle':
in_ = np.reshape(np.asfortranarray(alpha), (alpha.shape[0], alpha.shape[1], 1))
in_ = np.asfortranarray(in_)
rle = mask.encode(in_)
segmentation = rle[0]
else:
raise ValueError('Unknown mask mode "{}"'.format(mode))
for idx, c in enumerate(np.unique(alpha)):
area = mask.area(rle).tolist()
if isinstance(area, list):
area = area[0]
bbox = mask.toBbox(rle).tolist()
if isinstance(bbox[0], list):
bbox = bbox[0]
annotation = {
'area': area,
'bbox': bbox,
'category_id': c,
'id': len(annotations)+idx,
'image_id': img_id,
'iscrowd': 0,
'segmentation': segmentation}
annotations.append(annotation)
return annotations
示例4: masktoBbox
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def masktoBbox(mask):
[x,y,w,h] = cocomask.toBbox(mask)
return np.asarray([x,y, x+w, y+h])
示例5: loadRes
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def loadRes(self, predictions):
"""Loads result file and return a result api object.
Args:
predictions: a list of dictionary each representing an annotation in COCO
format. The required fields are `image_id`, `category_id`, `score`,
`bbox`, `segmentation`.
Returns:
res: result COCO api object.
Raises:
ValueError: if the set of image id from predctions is not the subset of
the set of image id of the groundtruth dataset.
"""
res = coco.COCO()
res.dataset['images'] = copy.deepcopy(self.dataset['images'])
res.dataset['categories'] = copy.deepcopy(self.dataset['categories'])
image_ids = [ann['image_id'] for ann in predictions]
if set(image_ids) != (set(image_ids) & set(self.getImgIds())):
raise ValueError('Results do not correspond to the current dataset!')
for ann in predictions:
x1, x2, y1, y2 = [ann['bbox'][0], ann['bbox'][0] + ann['bbox'][2],
ann['bbox'][1], ann['bbox'][1] + ann['bbox'][3]]
if self._eval_type == 'box':
ann['area'] = ann['bbox'][2] * ann['bbox'][3]
ann['segmentation'] = [
[x1, y1, x1, y2, x2, y2, x2, y1]]
elif self._eval_type == 'mask':
ann['bbox'] = mask_utils.toBbox(ann['segmentation'])
ann['area'] = mask_utils.area(ann['segmentation'])
res.dataset['annotations'] = copy.deepcopy(predictions)
res.createIndex()
return res
示例6: create_annotation_info
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def create_annotation_info(annotation_id, image_id, category_info, binary_mask,
image_size=None, tolerance=2, bounding_box=None):
if image_size is not None:
binary_mask = resize_binary_mask(binary_mask, image_size)
binary_mask_encoded = mask.encode(np.asfortranarray(binary_mask.astype(np.uint8)))
area = mask.area(binary_mask_encoded)
if area < 1:
return None
if bounding_box is None:
bounding_box = mask.toBbox(binary_mask_encoded)
if category_info["is_crowd"]:
is_crowd = 1
segmentation = binary_mask_to_rle(binary_mask)
else :
is_crowd = 0
segmentation = binary_mask_to_polygon(binary_mask, tolerance)
if not segmentation:
return None
annotation_info = {
"id": annotation_id,
"image_id": image_id,
"category_id": category_info["id"],
"iscrowd": is_crowd,
"area": area.tolist(),
"bbox": bounding_box.tolist(),
"segmentation": segmentation,
"width": binary_mask.shape[1],
"height": binary_mask.shape[0],
}
return annotation_info
示例7: bbox
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def bbox(self):
p = mask_util.frPyObjects(self.polygons, self.height, self.width)
p = mask_util.merge(p)
bbox = mask_util.toBbox(p)
bbox[2] += bbox[0]
bbox[3] += bbox[1]
return bbox
示例8: bounding_box_from_rle
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def bounding_box_from_rle(rle):
return list(cocomask.toBbox(rle))
示例9: __init__
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def __init__(self, config, subset, coord):
# old_proposal_directory = "/home/luiten/vision/PReMVOS/first_frame_no_ReID/%s/"
old_proposal_directory = config.str("bb_input_dir", None)
data_directory = config.str("image_input_dir", None)
# old_proposal_directory = "/home/luiten/vision/PReMVOS/proposals_with_flow/%s/"
# old_proposal_directory = "/home/luiten/vision/PReMVOS/post_proposal_expansion_json_with_flow/%s/"
# sets = ['test-challenge/', 'val/', 'test-dev/']
# sets = ['val/',]
annotations = []
# Read in all proposals
# for set_id, set in enumerate(sets):
# folders = sorted(glob.glob(old_proposal_directory.split('%s')[0] + set + '*/'))
folders = sorted(glob.glob(old_proposal_directory + '*/'))
for folder in folders:
seq = folder.split('/')[-2]
# name = set + seq
name = seq
# files = sorted(glob.glob(old_proposal_directory % name + "*.json"))
files = sorted(glob.glob(old_proposal_directory + name + "/*.json"))
for file in files:
timestep = file.split('/')[-1].split('.json')[0]
with open(file, "r") as f:
proposals = json.load(f)
for prop_id, proposal in enumerate(proposals):
# img_file = "/home/luiten/vision/PReMVOS/home_data/"+name+"/images/"+timestep+".jpg"
img_file = data_directory + name + "/" + timestep + ".jpg"
catagory_id = 1
tag = name+'/'+timestep+'___'+str(prop_id)
segmentation = proposal["segmentation"]
bbox = toBbox(segmentation)
ann = {"img_file":img_file,"category_id":catagory_id,"bbox":bbox,"tag":tag}
if bbox[2] <= 0 or bbox[3] <= 0:
continue
annotations.append(ann)
super(DAVISForwardSimilarityDataset, self).__init__(config, subset, coord, annotations, n_train_ids=1)
示例10: read_ann
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def read_ann(ann_fn):
ann = np.array(Image.open(ann_fn))
ids = np.unique(ann)
ids = [id for id in ids if id != 0]
ann_masks = [(ann == id_).astype(np.uint8) for id_ in ids if id_ != 0]
new_proposals = []
for ann_mask,id in zip(ann_masks,ids):
encoded_mask = encode(np.asfortranarray(ann_mask))
encoded_mask['counts'] = encoded_mask['counts'].decode("utf-8")
bbox = toBbox(encoded_mask)
new_proposals.append({'id':id, 'bbox': bbox, 'segmentation': encoded_mask,'conf_score':"1.0",'score':1.0})
return new_proposals
示例11: calculate_selected_props
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def calculate_selected_props(proposals,weighted_scores,templates,score_thresh,object_scores):
empty_mask = np.zeros_like(decode(proposals[0]['segmentation']))
empty_seg = encode(np.asfortranarray(empty_mask))
empty_seg['counts'] = empty_seg['counts'].decode("utf-8")
empty_prop = dict()
empty_prop['segmentation'] = empty_seg
empty_prop['bbox'] = toBbox(empty_seg)
proposals.append(empty_prop)
# print(weighted_scores.shape,(score_thresh*np.ones_like(weighted_scores[:,0])).shape)
weighted_scores = np.append(weighted_scores,score_thresh*np.ones((weighted_scores.shape[0],1)), axis=1)
weighted_scores[np.logical_not(np.isfinite(weighted_scores))] = 0
best_scores = weighted_scores.max(axis=1)
best_scores_index = weighted_scores.argmax(axis=1)
best_object_scores = object_scores.max(axis=1)
selected_props = [proposals[i].copy() for i in best_scores_index]
for order_id,(prop,score,template,object_score) in enumerate(zip(selected_props,best_scores,templates,best_object_scores)):
prop['final_score'] = score
prop['object_score'] = object_score
prop['id'] = template['id'] #todo Check if the ID here works
# prop['id'] = order_id
return selected_props
示例12: remove_mask_overlap
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def remove_mask_overlap(proposals):
scores = [prop['final_score'] if prop['final_score'] else 0 for prop in proposals]
masks = [decode(prop['segmentation']) for prop in proposals]
object_scores = [prop['object_score'] if prop['object_score'] else 0 for prop in proposals]
ids = [prop['id'] for prop in proposals]
proposal_order = np.argsort(scores)[::-1]
# proposal_order = np.argsort(scores)
labels = np.arange(1, len(proposal_order) + 1)
png = np.zeros_like(masks[0])
for i in proposal_order[::-1]:
png[masks[i].astype("bool")] = labels[i]
refined_masks = [(png == id_).astype(np.uint8) for id_ in labels]
refined_segmentations = [encode(np.asfortranarray(refined_mask)) for refined_mask in refined_masks]
selected_props = []
for refined_segmentation,score,mask,id,object_score in zip(refined_segmentations,scores,refined_masks,ids,object_scores):
refined_segmentation['counts'] = refined_segmentation['counts'].decode("utf-8")
prop = dict()
prop['segmentation']=refined_segmentation
prop['bbox']=toBbox(refined_segmentation)
prop['final_score'] = score
prop['object_score'] = object_score
prop['mask'] = mask
prop['id'] = id
selected_props.append(prop)
return selected_props
示例13: rle_to_boxes
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def rle_to_boxes(rles):
boxes_from_polys = np.zeros((len(rles), 4), dtype=np.float32)
for i in range(len(rles)):
rle = rles[i]
x0, y0, w, h = mask_util.toBbox(rle)
x1, y1 = x0 + w, y0 + h
boxes_from_polys[i, :] = [x0, y0, x1, y1]
return boxes_from_polys
示例14: encode_rle
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def encode_rle(rle, mask_id, image_id):
rle['counts'] = rle['counts'].decode('utf-8')
return {
'image_id': image_id,
'segmentation': rle,
'category_id': 1,
'id': mask_id,
'area': int(mask_util.area(rle)),
'bbox': list(mask_util.toBbox(rle)),
'iscrowd': 0
}
示例15: save_im_masks
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import toBbox [as 别名]
def save_im_masks(im, M, id, dir):
from utils.boxes import xywh_to_xyxy
import os
try:
os.mkdir(os.path.join('vis', dir))
except:
pass
M[M > 0] = 1
aug_rles = mask_util.encode(np.asarray(M, order='F'))
boxes = xywh_to_xyxy(np.asarray(mask_util.toBbox(aug_rles)))
boxes = np.append(boxes, np.ones((len(boxes), 2)), 1)
from utils.vis import vis_one_image
vis_one_image(im, str(id), os.path.join('vis', dir), boxes, segms=aug_rles, keypoints=None, thresh=0.9,box_alpha=0.8, show_class=False,)