靠数据做事当然首先要知道数据是什么样的
本文的可视化是基于pycocotools来实现的(有方便的轮子为什么不用),网上的大多数教程就是把pycocotools的demo拿来说了一下,而demo中标签的可视化都需要指定一个类,只显示这个类的标签,但我想可视化一张图片中所有目标的标签该怎么办。。。。
一时半会在网上没找到想要的 👉 自己写一个算了 👉 所以有了本文
默认已经安装了pycocotools
直接上代码:
下面的代码可以直接可视化 train的标签,其中’test‘模式是为了打比赛的时候测试集没有label, 检测完的结果文件和train.json
格式有所差异(只是个List,而不是pycocotools要求的字典,还需要添加{'images': ...},{'annotations': ...},
等等),所以在test模式下还需要进行格式转换。
import os
from pycocotools.coco import COCO
from skimage import io
from matplotlib import pyplot as plt
import json
import cv2
if __name__=='__main__':
mode = 'test'
test_json_file = '你的路径/data/test/annotations/test.json'
train_json_file = '你的路径/data/train/annotations/train.json'
# train模式下 json_file 与train_json_file 相同
# test模式下 json_file 是你的检测结果文件
json_file = '你的路径/xx.json'
# test模式下格式转换完后的结果文件,train模式下用不到
newJsonSaveName = '你的路径/result/test_result_visual.json'
imgsPath = '你的路径/data/train/images/'
jsonFile = json.load(open(json_file))
# 测试结果可视化
if mode == 'test':
imgsPath = '你的路径/data/test/images/'
test_json_file = json.load(open(test_json_file))
for i,_ in enumerate(jsonFile):
jsonFile[i]['id'] = i
jsonFile[i]['iscrowd'] = 0
test_json_file['annotations'] = jsonFile
jsonFile = test_json_file.copy()
json_str = json.dumps(jsonFile, indent=4)
with open(newJsonSaveName, 'w') as json_file:
json_file.write(json_str)
json_file = newJsonSaveName
classId2className = jsonFile['categories']
imId2imageNames = {}
for imgs in jsonFile['images']:
imId2imageNames[imgs['id']] = imgs['file_name']
imgId2labels = {}
for label in jsonFile['annotations']:
imgId = label['image_id']
if imgId not in imgId2labels:
imgId2labels[imgId] = []
imgId2labels[imgId].append(label)
coco = COCO(json_file)
for imgId in imgId2labels:
imgName = imId2imageNames[imgId]
img = io.imread(imgsPath + imgName)
# for label in imgId2labels[imgId]:
plt.axis('off')
plt.imshow(img) # 绘制图像,显示交给plt.show()处理
coco.showAnns(imgId2labels[imgId])
plt.show() # 显示图像
最终效果如下所示: