将json的标注文件的bbox显示在图片上

1.准备要索引的图片的image_id

将自己需要显示的图片image_id做成一个txt文件如下图所示:
在这里插入图片描述
就是把图片的image_id罗列在txt文件里面就可以了

2.准备好json的标注文件

3. 使用以下代码


from pycocotools.coco import COCO
import cv2
import os
import json

def showresultimages(imageidFile, annFile, imageFile, resultFile, cls_id_name, cls_id):

    """



    Note : If you want to show all the bboxes in a single picture,just use Method2
    Or if you want show bboxes page by page, just use Method1
    The differences between these two method is just the location of:
    
    image = cv2.imread(os.path.join(imageFile, '{}.jpg'.format(str(data[i]))))
    
    Because cv2.imread set a fixed picture when u use this command
    and when you rewrite a bbox in the same pic, it actually in the latest pic



    :param imageidFile: 要查看的图片imageid,存储一列在txt文件里
    :param annFile:使用的标注文件
    :param imageFile:要读取的image所在文件夹
    :param resultFile:画了标注之后的image存储文件夹
    :param cls_id_name:Dict type, such as {1: "airplane", 2: "airport"......}
    :return:
    """
# Method1
    with open(imageidFile, 'r') as f:
        data = f.readlines()
    font = cv2.FONT_HERSHEY_SIMPLEX

    # Remove the Enter at the end of each line
    for i, k in enumerate(data):
        split_data = k.strip(' \r\n')
        data[i] = split_data

    for i in range(len(data)):
        # image = cv2.imread(os.path.join(imageFile, '{}.jpg'.format(str(data[i]))))
        ann = []
        image_id = int(data[i])
        anns = json.load(open(annFile, 'r'))
        for k in anns:
            if k['image_id'] == image_id:
                if k['category_id'] == cls_id:
                    ann.append(k)
        num = 1
        for n in range(len(ann)):
            image = cv2.imread(os.path.join(imageFile, '{}.jpg'.format(str(data[i]))))
            x, y, w, h = ann[n]['bbox']
            x, y, w, h = int(x), int(y), int(w), int(h)
            # print(x, y, w, h)
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 255), thickness=1)
            cv2.putText(image, cls_id_name[cls_id] + ' ' + str(ann[n]['score']), (x+w, y), font, 0.4,
                                                            (0, 0, 255))
            cv2.imwrite(os.path.join(resultFile, '{0}_result_{1}.jpg'.format(str(data[i]), num)), image)
        # cv2.imwrite(os.path.join(resultFile, '{}_result.jpg'.format(str(data[i]))), image)
            num += 1
        print('Processing:%d\n' %i)
    print("The new iamges is in :{}".format(resultFile))

# Method2
    with open(imageidFile, 'r') as f:
        data = f.readlines()
    font = cv2.FONT_HERSHEY_SIMPLEX

    # Remove the Enter at the end of each line
    for i, k in enumerate(data):
        split_data = k.strip(' \r\n')
        data[i] = split_data

    for i in range(len(data)):
        image = cv2.imread(os.path.join(imageFile, '{}.jpg'.format(str(data[i]))))
        ann = []
        image_id = int(data[i])
        anns = json.load(open(annFile, 'r'))
        for k in anns:
            if k['image_id'] == image_id:
                if k['category_id'] == cls_id:
                    ann.append(k)
        num = 1
        for n in range(len(ann)):
            x, y, w, h = ann[n]['bbox']
            x, y, w, h = int(x), int(y), int(w), int(h)
            # print(x, y, w, h)
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 255), thickness=1)
            cv2.putText(image, cls_id_name[cls_id] + ' ' + str(ann[n]['score']), (x+w, y), font, 0.4,
                                                            (0, 0, 255))
            cv2.imwrite(os.path.join(resultFile, '{0}_result_{1}.jpg'.format(str(data[i]), num)), image)
        # cv2.imwrite(os.path.join(resultFile, '{}_result.jpg'.format(str(data[i]))), image)
            num += 1
        print('Processing:%d\n' %i)
    print("The new iamges is in :{}".format(resultFile))

def _2dict(result_path, out, anno_path):
    file = json.load(open(result_path, 'r'))
    a = {}
    a['annotations'] = file
    file = json.load(open(anno_path, 'r'))
    key_value = [
        'annotations', 'categories', 'images'
    ]
    for key in key_value:
        if key != 'annotations':
            a[key] = file[key]
    json_fp = open(out, 'w')
    json_str = json.dumps(a)
    json_fp.write(json_str)
    json_fp.close()
    return out

if __name__ == "__main__":
    cls_id = 12
    imageidfile = '/disk6/kurt/dataset/dior2voc/ImageSets/Main/pick-test.txt'
    # Note: This is a class type file
    annfile = 'your annotations file path(must be a file)'
    imagefile = 'your image file path(just a parent directory)'
    resultfile = 'the directory path you want to save the results images'
    cls_id_name = {
        1: 'airplane', 2: 'airport', 3: 'baseballfield', 4: 'basketballcourt',
        5: 'bridge', 6: 'chimney', 7: 'dam', 8: 'Expressway-Service-area', 9: 'Expressway-toll-station',
        10: 'golffield', 11: 'groundtrackfield', 12: 'harbor', 13: 'overpass',
        14: 'ship', 15: 'stadium', 16: 'storagetank', 17: 'tenniscourt', 18: 'trainstation',
        19: 'vehicle', 20: 'windmill'
    }
    # It's a dictionary contains the category_id and classes' name
    showresultimages(imageidFile=imageidfile, annFile=annfile, imageFile=imagefile, resultFile=resultfile, cls_id_name=cls_id_name, cls_id=cls_id)

参考资料

https://blog.csdn.net/zhuoyuezai/article/details/84315113
https://www.cnblogs.com/gongxijun/p/6824494.html
https://blog.csdn.net/qq_21997625/article/details/86558178

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值