from pycocotools.coco import COCO
import numpy as np
import skimage.io as io
import matplotlib.pyplot as plt
import pylab
pylab.rcParams['figure.figsize'] = (8.0, 10.0)
dataDir = r'D:\xunleixiazai\train2014'
dataType = 'train2014'
annFile = '{}/annotations/person_keypoints_{}.json'.format(r'D:\xunleixiazai', 'train2014')
coco_kps = COCO(annFile)
# initialize COCO api for instance annotations
coco=COCO(annFile)
catIds = coco.getCatIds(catNms=['person', 'dog', 'skateboard'])
imgIds = coco.getImgIds(catIds=catIds)
imgIds = coco.getImgIds(imgIds=[1407])
img = coco.loadImgs(imgIds[np.random.randint(0, len(imgIds))])[0]
I = io.imread('%s/%s' % (dataDir, img['file_name']))
plt.imshow(I)
plt.axis('off')
ax = plt.gca()
annIds = coco_kps.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco_kps.loadAnns(annIds)
coco_kps.showAnns(anns)
plt.imshow(I)
plt.axis('off')
plt.show()
显示mask
import os
import sys, getopt
from pycocotools.coco import COCO
import cv2
import matplotlib.pyplot as plt
def mkdir_os(path):
if not os.path.exists(path):
os.makedirs(path)
def main(argv):
inputfile = '/home/lixuan/workspace/project/dectetion/mmdetection/data/icecream/train' # './data/coco/val2017/'
jsonfile = '/home/lixuan/workspace/project/dectetion/centernet_Rotating_rectangle/icecream_coco.json' # './data/coco/annotations/instances_val2017.json'
outputfile = '/home/lixuan/workspace/project/dectetion/mmdetection/data/icecream/result' # './data/coco/vis/'
try:
opts, args = getopt.getopt(argv, "hi:j:o:", ["ifile=", "jfile=", "ofile="])
except getopt.GetoptError:
print('test.py -i <inputfile> -j <jsonfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print('test.py -i <inputfile> -j <jsonfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-j", "--jfile"):
jsonfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print('\n输入的文件为:', inputfile)
print('\n输入的json为:', jsonfile)
print('\n输出的文件为:', outputfile)
mkdir_os(outputfile)
coco = COCO(jsonfile)
catIds = coco.getCatIds(catNms=['wires']) # catIds=1 表示人这一类
imgIds = coco.getImgIds(catIds=catIds) # 图片id,许多值
print(imgIds)
for i, imgId in enumerate(imgIds):
print(i, "/", len(imgIds))
img = coco.loadImgs(imgId)[0]
cvImage = cv2.imread(os.path.join(inputfile, img['file_name']), -1)
cvImage = cv2.cvtColor(cvImage, cv2.COLOR_BGR2GRAY)
cvImage = cv2.cvtColor(cvImage, cv2.COLOR_GRAY2BGR)
plt.cla()
plt.axis('off')
plt.imshow(cvImage)
annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None)
anns = coco.loadAnns(annIds)
for an in anns:
if not 'counts' in str(an):
coco.showAnns([an])
plt.savefig(os.path.join(outputfile, img['file_name']))
if __name__ == "__main__":
main(sys.argv[1:])
显示bbox:
import cv2
import os
import numpy as np
from pycocotools.coco import COCO
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
img_path = '/home/lixuan/workspace/project/dectetion/mmdetection/data/icecream/train'
annFile = '/home/lixuan/workspace/project/dectetion/mmdetection/data/icecream/anno/train.json'
save_path = '/home/lixuan/workspace/project/dectetion/mmdetection/data/icecream/result'
if not os.path.exists(save_path):
os.makedirs(save_path)
def draw_rectangle(coordinates, image, image_name):
for coordinate in coordinates:
left, top, right, bottom, label = map(int, coordinate)
color = colors[label % len(colors)]
cv2.rectangle(image, (left, top), (right, bottom), color, 2)
cv2.putText(image, str(label), (left, top), cv2.FONT_HERSHEY_SIMPLEX, 1.2, color, 2)
cv2.imwrite(save_path + '/' + image_name, image)
coco = COCO(annFile)
# catIds = coco.getCatIds(catNms=['Crack','Manhole', 'Net', 'Pothole','Patch-Crack', "Patch-Net", "Patch-Pothole", "other"])
# catIds = coco.getCatIds()
# imgIds = coco.getImgIds(catIds=catIds)
imgIds = coco.getImgIds()
for imgId in imgIds:
img = coco.loadImgs(imgId)[0]
image_name = img['file_name']
annIds = coco.getAnnIds(imgIds=img['id'], catIds=[], iscrowd=None)
anns = coco.loadAnns(annIds)
# coco.showAnns(anns)
coordinates = []
img_raw = cv2.imread(os.path.join(img_path, image_name))
for j in range(len(anns)):
coordinate = anns[j]['bbox']
coordinate[2] += coordinate[0]
coordinate[3] += coordinate[1]
coordinate.append(anns[j]['category_id'])
coordinates.append(coordinate)
draw_rectangle(coordinates, img_raw, image_name)