import os
import time
import datetime
import mmcv
import cv2 as cv
import json
import numpy as np
import pycocotools.mask as maskutil
import pycocotools.coco as COCO
from itertools import groupby
from skimage import measure,draw,data
from PIL import Image def close_contour(contour):
if not np.array_equal(contour[0], contour[-1]):
contour = np.vstack((contour, contour[0]))
return contour def binary_mask_to_polygon(binary_mask, tolerance=0):
"""Converts a binary mask to COCO polygon representation
Args:
binary_mask: a 2D binary numpy array where '1's represent the object
tolerance: Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array is returned.
"""
polygons = []
# pad mask to close contours of shapes which start and end at an edge
padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
contours = measure.find_contours(padded_binary_mask, 0.5)
contours = np.subtract(contours, 1)
for contour in contours:
contour = close_contour(contour)
contour = measure.approximate_polygon(contour, tolerance)
if len(contour) < 3:
continue
contour = np.flip(contour, axis=1)
segmentation = contour.ravel().tolist()
# after padding and subtracting 1 we may get -0.5 points in our segmentation
segmentation = [0 if i < 0 else i for i in segmentation]
polygons.append(segmentation) return polygons def binary_mask_to_rle(binary_mask):
rle = {'counts': [], 'size': list(binary_mask.shape)}
counts = rle.get('counts')
for i, (value, elements) in enumerate(groupby(binary_mask.ravel(order='F'))):
if i == 0 and value == 1:
counts.append(0)
counts.append(len(list(elements)))
return rle def main2():
seg=np.array([312.29, 562.89, 402.25, 511.49, 400.96, 425.38, 398.39, 372.69, 388.11, 332.85, 318.71, 325.14, 295.58, 305.86, 269.88, 314.86, 258.31, 337.99, 217.19, 321.29, 182.49, 343.13, 141.37, 348.27, 132.37, 358.55, 159.36, 377.83, 116.95, 421.53, 167.07, 499.92, 232.61, 560.32, 300.72, 571.89])
compactedRLE = maskutil.frPyObjects([seg], 768, 768)
print(compactedRLE)
#compactedRLE=[
# {"size":[768, 768],
# "counts": "`eQ66ig02O1O000000000000000000000000001O00000000000000000000000000000000000000000000000000000000O2O0NbZj:"
# }]
mask = maskutil.decode(compactedRLE)
mask=np.reshape(mask,(768,768))
mask[:,:]=mask[:,:]*255
print(mask)
#mmcv.imshow(mask) '''
mask=np.array(
[
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]
)
print(mask)
''' poly=binary_mask_to_polygon(mask)
print(poly)
rle=binary_mask_to_rle(mask)
print(rle)
#mmcv.imshow(area) return 0 def class2color(classes=1,class_id=0):
sum = classes*12357
return [sum%(class_id+0),sum%(class_id+1),sum%(class_id+2)] def mainContour():
imgfile = "/home/wit/Pictures/7dd98d1001e9390100d9e95171ec54e737d19681.jpg"
img = cv.imread(imgfile)
h, w, _ = img.shape gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY) # Find Contour
_, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
print(contours) def main():
testimagepath = "/media/wit/WeiJX/AirbusShip/coco-labels/instances_ships_test2018.json"
compressedRLECOCOlabelpath = "/media/wit/WeiJX/workspace/out/maskrcnn.reorg.pkl.json"
imageprefix = "/media/wit/WeiJX/AirbusShip/test-images/" startTime = time.time()
trthset = json.load(open(testimagepath, 'r'))
assert type(trthset) == dict, 'annotation file format {} not supported'.format(type(trthset))
prdcset = json.load(open(compressedRLECOCOlabelpath, 'r'))
assert type(prdcset) == dict, 'annotation file format {} not supported'.format(type(prdcset))
print('Done (t={:0.2f}s)'.format(time.time() - startTime)) ann_Y0 = trthset['annotations']
ann_Y1 = prdcset['annotations'] for image in trthset['images']:
imagepath = imageprefix+image['file_name']
img = cv.imread(imagepath) src = np.zeros((768,768,3), np.uint8)
src[:,:,:]=img[:,:,:]
dst = np.zeros((768,768,3), np.uint8)
dst[:,:,:]=img[:,:,:] masks = np.zeros((768, 768, 1), np.uint8)
masks.fill(0)
id0 = image['id'] counts = 0 contours = []
for target in ann_Y0:
if target['image_id']==id0:
counts += 1
j=0
X=[]
Y=[]
for seg in target['segmentation'][0]:
if j == 0:
x = float(seg)
X.append(x)
else:
y = float(seg)
Y.append(y)
j = 1-j rr, cc = draw.polygon(Y, X)
draw.set_color(src, [rr, cc], [0, 0, 255], 0.4) Point = np.zeros((len(Y), 2), dtype='int32')
Point [:, 0] = X[:]
Point [:, 1] = Y[:]
#print(Point)
cv.fillPoly(masks, np.array([Point],'int32'), 1)
src[:, :, 0] = img[:, :, 0] #* 0.9 + masks[:, :, 0] * 0.1 * 255.0 / counts
src[:, :, 1] = img[:, :, 1] #* 0.9 + masks[:, :, 0] * 0.1 * 255.0 / counts
src[:, :, 2] = img[:, :, 2] * 0.2 + masks[:, :, 0] * 0.8 * 255.0 / counts mmcv.imshow(src,"Y",1) masks.fill(0)
counts = 0
for target in ann_Y1:
if target['image_id']==id0:
counts += 1
CRLE = target['segmentation']
#print(CRLE)
mask = maskutil.decode(CRLE)
mask = np.reshape(mask, (img.shape[1], img.shape[0], 1))
masks[:, :] = masks[:, :] + mask[:, :] dst[:, :, 0] = img[:, :, 0] * 0.2 + masks[:, :, 0] * 0.8 * 255.0/counts
dst[:, :, 1] = img[:, :, 1] #* 0.5 + masks[:, :, 0] * 0.5 * 255.0/counts
dst[:, :, 2] = src[:, :, 2] * 0.9 + masks[:, :, 0] * 0.1 * 255.0/counts
mmcv.imshow(dst,"Y'") return 0 if __name__ == '__main__':
main()

绘制COCO数据集结果的更多相关文章

  1. [PocketFlow]解决TensorFLow在COCO数据集上训练挂起无输出的bug

    1. 引言 因项目要求,需要在PocketFlow中添加一套PeleeNet-SSD和COCO的API,具体为在datasets文件夹下添加coco_dataset.py, 在nets下添加pelee ...

  2. COCO 数据集的使用

    Windows 10 编译 Pycocotools 踩坑记 COCO数据库简介 微软发布的COCO数据库, 除了图片以外还提供物体检测, 分割(segmentation)和对图像的语义文本描述信息. ...

  3. COCO数据集深入理解

    TensorExpand/TensorExpand/Object detection/Data_interface/MSCOCO/ 深度学习数据集介绍及相互转换 Object segmentation ...

  4. COCO 数据集使用说明书

    下面的代码改写自 COCO 官方 API,改写后的代码 cocoz.py 被我放置在 Xinering/cocoapi.我的主要改进有: 增加对 Windows 系统的支持: 替换 defaultdi ...

  5. Pascal VOC & COCO数据集介绍 & 转换

    目录 Pascal VOC & COCO数据集介绍 Pascal VOC数据集介绍 1. JPEGImages 2. Annotations 3. ImageSets 4. Segmentat ...

  6. 在ubuntu1604上使用aria2下载coco数据集效率非常高

    简单的下载方法: 所以这里介绍一种能照顾大多数不能上外网的同学的一种简单便捷,又不会中断的下载方法:系统环境: Ubuntu 14.04 方法: a. 使用aria2 搭配命令行下载.需要先安装: s ...

  7. MS coco数据集下载

    2017年12月02日 23:12:11 阅读数:10411 登录ms-co-co数据集官网,一直不能进入,FQ之后开看到下载链接.有了下载链接下载还是很快的,在我这儿晚上下载,速度能达到7M/s,所 ...

  8. coco数据集标注图转为二值图python(附代码)

    coco数据集大概有8w张以上的图片,而且每幅图都有精确的边缘mask标注. 后面后分享一个labelme标注的json或xml格式转二值图的源码(以备以后使用) 而我现在在研究显著性目标检测,需要的 ...

  9. COCO数据集使用

    一.简介 官方网站:http://cocodataset.org/全称:Microsoft Common Objects in Context (MS COCO)支持任务:Detection.Keyp ...

随机推荐

  1. 【CF613D】Kingdom and its Cities 虚树+树形DP

    [CF613D]Kingdom and its Cities 题意:给你一棵树,每次询问给出k个关键点,问做多干掉多少个非关键点才能使得所有关键点两两不连通. $n,\sum k\le 10^5$ 题 ...

  2. R 540

    好久没写题解了嘻嘻嘻,昨天补edu自闭了一天还没补完fg这div3令人愉悦. A: #include <bits/stdc++.h> #define mk(a,b) make_pair(a ...

  3. Java课程寒假之开发记账本软件(网页版)之四

    一.实现基础功能之一(删除) 在删除的功能实现之前,要明白删除的条件是什么,一开始我是以去向和时间作为条件删除,但是删除的语句好像有问题,好像是因为出现了非法字符(应该是中文吧,不太清楚,因为这不是我 ...

  4. linux 的基本操作(编写shell 脚本)

    终于到shell 脚本这章了,在以前笔者卖了好多关子说shell脚本怎么怎么重要,确实shell脚本在linux系统管理员的运维工作中非常非常重要.下面笔者就带你正式进入shell脚本的世界吧. 到现 ...

  5. 微信小程序开发笔记03

    今天基本实现了微信小程序主要功能,页面还没有进行优化,有些功能还需完善. 页面之间的信息转化部分还未实现.

  6. JavaScript基础知识(DOM)

    获取元素的方法 要操作谁,就要先获取谁: 获取元素 1.document.getElementById:通过ID名来获取元素 兼容性: 在IE8以下,会默认把name属性当做id来获取: docume ...

  7. Java-idea-安装配置优化等

    1.属性配置 使用版本,winzip解压版,开发工具安装目录下idea.properties文件,自定义配置路径 # idea.config.path=${user.home}/.IntelliJId ...

  8. java框架之SpringBoot(7)-异常处理

    前言 在 SpringBoot 项目中,默认情况下,使用浏览器访问一个不存在的地址会返回如下错误页面: 而当客户端未非浏览器时,错误信息则会以 json 数据返回,如下: 会出现如上效果的原因是 Sp ...

  9. 小程序 navigator 无法跳转 tabBar上的页面

    解决方法一: navigator 的 open-type 设置为 switchTab 解决方法二: 使用 wx.switchTab({ url: ‘../cart/index’ }) 进行跳转

  10. git pull 冲突拉取不到新的代码

    本地文件已经有冲突或者在pull的过程中拉取的文件和本地文件冲突时,拉取不到新的代码,git pull出现报错,如下: 这个时候,如果你有两种选择,如果你需要这些改动,那个你就需要手动解决冲突,然后a ...