自定义coco JSON文件 (instances_val2017.json)
1. 读取JSON文件
json_path = 'instances_val2017.json'
main = open(json_path)
main = json.load(main)
2. 根据mask查找
solov2源码(mmdet/datasets/pipelines/loading.py)进行了简单修改
def _poly2mask(mask_ann, img_h, img_w):
if isinstance(mask_ann, list):
rles = maskUtils.frPyObjects(mask_ann, img_h, img_w)
rle = maskUtils.merge(rles)
elif isinstance(mask_ann['counts'], list):
rle = maskUtils.frPyObjects(mask_ann, img_h, img_w)
else:
rle = mask_ann
mask = maskUtils.decode(rle)
return mask
def check_mask(main):
for i in range(len(main['annotations'])):
h, w = main['annotations'][i]['height'], main['annotations'][i]['width']
gt_masks = main['annotations'][i]['segmentation']
gt_masks = _poly2mask(gt_masks, h, w)
image_np = gt_masks
contours, hierarchy = cv2.findContours(image_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
image_show = image_np * 255
image_show = cv2.cvtColor(image_show, cv2.COLOR_GRAY2BGR)
image_show = cv2.drawContours(image_show, contours, -1, (0, 0, 255), 3)
cv2.namedWindow('1', 0)
cv2.resizeWindow('1', 1024, 1300)
cv2.imshow("1", image_show)
cv2.waitKey(0)
cv2.destroyAllWindows()
print('i:', i)
3.所有需要调用的库
import json
import os
import cv2
import pycocotools.mask as maskUtils
4.整体代码
import json
import os
import cv2
import pycocotools.mask as maskUtils
def _poly2mask(mask_ann, img_h, img_w):
if isinstance(mask_ann, list):
rles = maskUtils.frPyObjects(mask_ann, img_h, img_w)
rle = maskUtils.merge(rles)
elif isinstance(mask_ann['counts'], list):
rle = maskUtils.frPyObjects(mask_ann, img_h, img_w)
else:
rle = mask_ann
mask = maskUtils.decode(rle)
return mask
def cho_class(main):
for i in range(len(main['annotations'])):
h, w = main['annotations'][i]['height'], main['annotations'][i]['width']
gt_masks = main['annotations'][i]['segmentation']
gt_masks = _poly2mask(gt_masks, h, w)
image_np = gt_masks
contours, hierarchy = cv2.findContours(image_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))
image_show = image_np * 255
image_show = cv2.cvtColor(image_show, cv2.COLOR_GRAY2BGR)
image_show = cv2.drawContours(image_show, contours, -1, (0, 0, 255), 3)
cv2.namedWindow('demo', 0)
cv2.resizeWindow('demo', 1024, 1300)
cv2.imshow("demo", image_show)
cv2.waitKey(0)
cv2.destroyAllWindows()
print('i:', i)
if __name__ == '__main__':
json_path = 'instances_val2017.json'
main = open(json_path)
main = json.load(main)
cho_class(main)
|