本文整理汇总了Python中pycocotools.mask.area方法的典型用法代码示例。如果您正苦于以下问题:Python mask.area方法的具体用法?Python mask.area怎么用?Python mask.area使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pycocotools.mask
的用法示例。
在下文中一共展示了mask.area方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __get_annotation__
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [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: __init__
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def __init__(self, groundtruth=None, detections=None, agnostic_mode=False,
iou_type='bbox'):
"""COCOEvalWrapper constructor.
Note that for the area-based metrics to be meaningful, detection and
groundtruth boxes must be in image coordinates measured in pixels.
Args:
groundtruth: a coco.COCO (or coco_tools.COCOWrapper) object holding
groundtruth annotations
detections: a coco.COCO (or coco_tools.COCOWrapper) object holding
detections
agnostic_mode: boolean (default: False). If True, evaluation ignores
class labels, treating all detections as proposals.
iou_type: IOU type to use for evaluation. Supports `bbox` or `segm`.
"""
cocoeval.COCOeval.__init__(self, groundtruth, detections,
iouType=iou_type)
if agnostic_mode:
self.params.useCats = 0
示例3: _extract_bbox_annotation
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def _extract_bbox_annotation(prediction, b, obj_i):
"""Constructs COCO format bounding box annotation."""
height = prediction['height'][b]
width = prediction['width'][b]
bbox = _denormalize_to_coco_bbox(
prediction['groundtruth_boxes'][b][obj_i, :], height, width)
if 'groundtruth_area' in prediction:
area = float(prediction['groundtruth_area'][b][obj_i])
else:
# Using the box area to replace the polygon area. This value will not affect
# real evaluation but may fail the unit test.
area = bbox[2] * bbox[3]
annotation = {
'id': b * 1000 + obj_i, # place holder of annotation id.
'image_id': int(prediction['source_id'][b]), # source_id,
'category_id': int(prediction['groundtruth_classes'][b][obj_i]),
'bbox': bbox,
'iscrowd': int(prediction['groundtruth_is_crowd'][b][obj_i]),
'area': area,
'segmentation': [],
}
return annotation
示例4: _create_anno
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [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
示例5: _create_ann
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def _create_ann(whole_m, lbl, sc, img_id, ann_id, crw=None, ar=None):
H, W = whole_m.shape
if crw is None:
crw = False
whole_m = np.asfortranarray(whole_m.astype(np.uint8))
rle = mask_tools.encode(whole_m)
# Surprisingly, ground truth ar can be different from area(rle)
if ar is None:
ar = mask_tools.area(rle)
ann = {
'image_id': img_id, 'category_id': lbl,
'segmentation': rle,
'area': ar,
'id': ann_id,
'iscrowd': crw}
if sc is not None:
ann.update({'score': sc})
return ann
示例6: eval_video
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def eval_video(final_solution,input_images,ground_truth_anns):
_,example_prop = final_solution[0]
scores = np.zeros(len(example_prop))
for image_fn,selected_props in final_solution[1:-1]:
gt_fn = image_fn.replace(input_images, ground_truth_anns).replace('.jpg', '.png')
gt_props = read_ann(gt_fn)
segs = [prop['segmentation'] for prop in selected_props]
gt_segs = [templ['segmentation'] for templ in gt_props]
gt_ids = [templ['id'] for templ in gt_props]
for temp_id,seg in enumerate(segs):
gt_id = temp_id + 1
if gt_id not in gt_ids:
if area(seg)==0:
score = 1
else:
score = 0
else:
gt_seg = [c_seg for c_seg,c_id in zip(gt_segs,gt_ids) if c_id == gt_id][0]
score = iou([seg,], [gt_seg,], np.array([0], np.uint8))[0,0]
scores[temp_id]+=score
final_scores = scores/(len(final_solution)-2)
return final_scores
示例7: encode_mask_to_poly
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [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
}
示例8: _annotation_generator
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def _annotation_generator(self):
"""
Generates sample_size annotations. No pre/post-processing
:return: coco annotation (dictionary)
"""
annotation_counter = 0
for img_id in self._image_ids:
annotation_ids = self._coco.getAnnIds(imgIds=img_id)
for annotation in self._coco.loadAnns(annotation_ids):
if annotation['area'] > self._config.area_threshold:
annotation_counter += 1
yield annotation
if annotation_counter == 0:
errmsg = 'Every annotation has been filtered out. ' \
'Decrease area threshold or increase image dimensions.'
raise Exception(errmsg)
示例9: mask_to_mscoco
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [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
示例10: __init__
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def __init__(self, groundtruth=None, detections=None, agnostic_mode=False,
iou_type='bbox', oks_sigmas=None):
"""COCOEvalWrapper constructor.
Note that for the area-based metrics to be meaningful, detection and
groundtruth boxes must be in image coordinates measured in pixels.
Args:
groundtruth: a coco.COCO (or coco_tools.COCOWrapper) object holding
groundtruth annotations
detections: a coco.COCO (or coco_tools.COCOWrapper) object holding
detections
agnostic_mode: boolean (default: False). If True, evaluation ignores
class labels, treating all detections as proposals.
iou_type: IOU type to use for evaluation. Supports `bbox', `segm`,
`keypoints`.
oks_sigmas: Float numpy array holding the OKS variances for keypoints.
"""
cocoeval.COCOeval.__init__(self, groundtruth, detections, iouType=iou_type)
if oks_sigmas is not None:
self.params.kpt_oks_sigmas = oks_sigmas
if agnostic_mode:
self.params.useCats = 0
self._iou_type = iou_type
示例11: __get_image_annotation_pairs__
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def __get_image_annotation_pairs__(self, image_set):
images = []
annotations = []
for imId, paths in enumerate(image_set):
impath, annotpath = paths[0], paths[1]
print (impath)
name = impath.split("/")[3]
img = np.array(Image.open(os.path.join(self.datapath + impath)).convert('RGB'))
mask = np.array(Image.open(os.path.join(self.datapath + annotpath)).convert('L'))
if np.all(mask == 0):
continue
segmentation, bbox, area = self.__get_annotation__(mask, img)
images.append({"date_captured" : "2016",
"file_name" : impath[1:], # remove "/"
"id" : imId+1,
"license" : 1,
"url" : "",
"height" : mask.shape[0],
"width" : mask.shape[1]})
annotations.append({"segmentation" : segmentation,
"area" : np.float(area),
"iscrowd" : 0,
"image_id" : imId+1,
"bbox" : bbox,
"category_id" : self.cat2id[name],
"id": imId+1})
return images, annotations
示例12: load_txt
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def load_txt(path):
objects_per_frame = {}
track_ids_per_frame = {} # To check that no frame contains two objects with same id
combined_mask_per_frame = {} # To check that no frame contains overlapping masks
with open(path, "r") as f:
for line in f:
line = line.strip()
fields = line.split(" ")
frame = int(fields[0])
if frame not in objects_per_frame:
objects_per_frame[frame] = []
if frame not in track_ids_per_frame:
track_ids_per_frame[frame] = set()
if int(fields[1]) in track_ids_per_frame[frame]:
assert False, "Multiple objects with track id " + fields[1] + " in frame " + fields[0]
else:
track_ids_per_frame[frame].add(int(fields[1]))
class_id = int(fields[2])
if not(class_id == 1 or class_id == 2 or class_id == 10):
assert False, "Unknown object class " + fields[2]
mask = {'size': [int(fields[3]), int(fields[4])], 'counts': fields[5].encode(encoding='UTF-8')}
if frame not in combined_mask_per_frame:
combined_mask_per_frame[frame] = mask
elif rletools.area(rletools.merge([combined_mask_per_frame[frame], mask], intersect=True)) > 0.0:
assert False, "Objects with overlapping masks in frame " + fields[0]
else:
combined_mask_per_frame[frame] = rletools.merge([combined_mask_per_frame[frame], mask], intersect=False)
objects_per_frame[frame].append(SegmentedObject(
mask,
class_id,
int(fields[1])
))
return objects_per_frame
示例13: fix_mask_overlap
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def fix_mask_overlap(self, thresh=0.3):
for t in range(self.timesteps):
for id in range(self.get_num_ids()):
if self.masks[t][id] is not None:
ref_mask = self.masks[t][id]
for k in range(id+1, self.get_num_ids()):
if self.masks[t][k] is not None:
overlap = cocomask.area(cocomask.merge([self.masks[t][k], ref_mask], intersect=True))
if overlap > 0.0:
if overlap > thresh * np.minimum(cocomask.area(ref_mask), cocomask.area(self.masks[t][k])):
if cocomask.area(ref_mask) < cocomask.area(self.masks[t][k]):
ref_mask = None
break
else:
self.remove_from_track(t, k)
else:
if cocomask.area(ref_mask) < cocomask.area(self.masks[t][k]):
self.masks[t][k] = cut(self.masks[t][k], ref_mask)
else:
ref_mask = cut(ref_mask, self.masks[t][k])
self.masks[t][id] = ref_mask
if self.masks[t][id] is None:
self.remove_from_track(t, id)
示例14: getAnnIds
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [as 别名]
def getAnnIds(self, imgIds=[], catIds=[], areaRng=[], iscrowd=None):
"""
Get ann ids that satisfy given filter conditions. default skips that filter
:param imgIds (int array) : get anns for given imgs
catIds (int array) : get anns for given cats
areaRng (float array) : get anns for given area range (e.g. [0 inf])
iscrowd (boolean) : get anns for given crowd label (False or True)
:return: ids (int array) : integer array of ann ids
"""
imgIds = imgIds if _isArrayLike(imgIds) else [imgIds]
catIds = catIds if _isArrayLike(catIds) else [catIds]
if len(imgIds) == len(catIds) == len(areaRng) == 0:
anns = self.dataset['annotations']
else:
if not len(imgIds) == 0:
lists = [self.imgToAnns[imgId] for imgId in imgIds if imgId in self.imgToAnns]
anns = list(itertools.chain.from_iterable(lists))
else:
anns = self.dataset['annotations']
anns = anns if len(catIds) == 0 else [ann for ann in anns if ann['category_id'] in catIds]
anns = anns if len(areaRng) == 0 else [ann for ann in anns if ann['area'] > areaRng[0] and ann['area'] < areaRng[1]]
if not iscrowd == None:
ids = [ann['id'] for ann in anns if ann['iscrowd'] == iscrowd]
else:
ids = [ann['id'] for ann in anns]
return ids
示例15: loadRes
# 需要导入模块: from pycocotools import mask [as 别名]
# 或者: from pycocotools.mask import area [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