coco数据集生成-原本有mask标注的单类多bbox--转换为每一个bbox扩边两倍为单独一个图生成新的coco形式json文件

# -*- coding: utf-8 -*-
import sys, getopt
import os
import json
import cv2
import random
import numpy as np
np.random.seed(41)
import glob
import shutil
import os

# -*- coding: utf-8 -*-
import os
import sys, getopt
from pycocotools.coco import COCO, maskUtils
import cv2
import numpy as np


def mkdir_os(path):
    if not os.path.exists(path):
        os.makedirs(path)

def groberect(points, ww, hh):
    x1 = points[0]
    y1 = points[1]
    w = points[2]
    h = points[3]

    x2 = x1 + w - 1
    y2 = y1 + h - 1

    px = float(x1 + x2) / 2
    py = float(y1 + y2) / 2

    w = w * 2
    h = h * 2

    l = max(0, px - w / 2)
    r = min(ww - 1, px + w / 2) #x2
    t = max(0, py - h / 2)
    b = min(hh - 1, py + h / 2) #y2

    w = r - l + 1
    h = b - t + 1

    # x1y1 x2y2
    return [int(l), int(t), int(w), int(h)]

def main(argv):
    # json_file = './data/coco/annotations/instances_val2017.json'
    # dataset_dir = './data/coco/val2017/'
    # save_dir = './data/coco/vis/'

    inputfile = ''
    jsonfile = ''
    outputfile = ''

    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)


    images = []
    annotations = []

    mkdir_os(outputfile)

    coco = COCO(jsonfile)
    catIds = coco.getCatIds(catNms=['wires'])  # catIds=1 表示人这一类
    imgIds = coco.getImgIds(catIds=catIds)  # 图片id,许多值

    image_id = 0
    annotations_id = 0

    for i in range(len(imgIds)):
        if i % 100 == 0:
            print(i, "/", len(imgIds))
        img_info = coco.loadImgs(imgIds[i])[0]

        cvImage = cv2.imread(os.path.join(inputfile, img_info['file_name']), -1)
        cvImage = cv2.cvtColor(cvImage, cv2.COLOR_BGR2GRAY)
        cvImage = cv2.cvtColor(cvImage, cv2.COLOR_GRAY2BGR)

        ori_H, ori_W = cvImage.shape[:2]

        annIds = coco.getAnnIds(imgIds=img_info['id'], catIds=catIds, iscrowd=None)
        anns = coco.loadAnns(annIds)


        #原来一幅图可能拆成多个,需要保存多个图像,生成多个image信息,多个annotation信息
        img_info_append = []
        for index in range(len(anns)):

            ann = anns[index]
            img_temp = img_info.copy()
            if 'segmentation' in ann: #只处理存在annotation的情况
                if type(ann['segmentation']) == list: #只处理points这种形式的mask标注的情况
                    bbox = ann['bbox']
                    new_bbox = groberect(bbox, ori_W, ori_H)

                    img_temp['width'] = new_bbox[2]
                    img_temp['height'] = new_bbox[3]
                    img_temp['file_name'] = img_temp['file_name'].split('.')[0] + "_" + str(index) + ".jpg"
                    img_temp['id'] = image_id

                    #cropImg = img[(y):(y + hh), (x):(x + ww)]
                    save_cvImage = cvImage[new_bbox[1]:(new_bbox[1] + new_bbox[3]), new_bbox[0]:(new_bbox[0] + new_bbox[2])]
                    cv2.imwrite(os.path.join(outputfile, img_temp['file_name']), save_cvImage)

                    img_info_append.append(img_temp)

                    ann['bbox'] = [bbox[0]-new_bbox[0], bbox[1]-new_bbox[1], bbox[2], bbox[3]]
                    for seg in range(len(ann['segmentation'])):
                        ori_seg = ann['segmentation'][seg]
                        for k in range(len(ori_seg)//2):
                            ori_seg[2 * k] = ori_seg[2 * k] - new_bbox[0]
                            ori_seg[2 * k + 1] = ori_seg[2 * k + 1] - new_bbox[1]
                        ann['segmentation'][seg] = ori_seg

                    ann['image_id'] = int(image_id)
                    #anns[index] = ann
                else:
                    exit()
            else:
                exit()

            image_id += 1
            #annotations_id += 1

        annotations.extend(anns)
        images.extend(img_info_append)
    instance = {}
    instance['info'] = 'spytensor created'
    instance['license'] = ['license']
    instance['images'] = images
    instance['annotations'] = annotations
    instance['categories'] = coco.dataset['categories']

    import io
    #json.dump(instance, io.open("./result.json", 'w', encoding='utf-8'), ensure_ascii=False, indent=1)  # indent=2 更加美观显示
    with io.open("./new_json.json", 'w', encoding="utf-8") as outfile:
        my_json_str = json.dumps(instance, ensure_ascii=False, indent=1)
        #python3 无
        # if isinstance(my_json_str, str):
        #     my_json_str = my_json_str.decode("utf-8")
        outfile.write(my_json_str)


if __name__ == "__main__":
    main(sys.argv[1:])

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 由于COCO数据集和Labelme数据集JSON格式不同,因此需要进行转换。以下是一个示例代码: ``` import json # 读取COCO JSON文件 with open('coco.json', 'r') as f: coco_json = json.load(f) # 初始化Labelme JSON字典 labelme_json = { 'version': '4.5.6', 'flags': {}, 'shapes': [], 'imagePath': coco_json['image_path'], 'imageData': None } # 遍历COCO JSON中的标注 for annotation in coco_json['annotations']: # 初始化Labelme shape字典 shape = { 'label': annotation['category_id'], 'points': [], 'group_id': None, 'shape_type': 'polygon', 'flags': {} } # 遍历标注的坐标点 for point in annotation['segmentation']: shape['points'].append([point[0], point[1]]) labelme_json['shapes'].append(shape) # 将Labelme JSON写入文件 with open('labelme.json', 'w') as f: json.dump(labelme_json, f) ``` 这段代码将COCO JSON文件中的标注转换为Labelme JSON格式并写入文件。请注意,这只是一个示例,您可能需要根据您的实际情况进行修改。 ### 回答2: 你可以使用Python来实现将coco数据集中的json标注转化为labelme的json格式。以下是一个示例代码: ```python import json def convert_to_labelme(coco_json, output_file): with open(coco_json, 'r') as f: coco_data = json.load(f) labelme_data = {'version': '4.2.10', 'flags': {}, 'shapes': []} for annotation in coco_data['annotations']: image_id = annotation['image_id'] category_id = annotation['category_id'] image_filename = coco_data['images'][image_id]['file_name'] image_height = coco_data['images'][image_id]['height'] image_width = coco_data['images'][image_id]['width'] labelme_shape = {'label': str(category_id), 'points': [], 'group_id': None, 'shape_type': 'rectangle', 'flags': {}} bbox = annotation['bbox'] x, y, w, h = bbox[0], bbox[1], bbox[2], bbox[3] x_min = x y_min = y x_max = x + w y_max = y + h labelme_shape['points'].append([x_min, y_min]) labelme_shape['points'].append([x_max, y_min]) labelme_shape['points'].append([x_max, y_max]) labelme_shape['points'].append([x_min, y_max]) labelme_data['shapes'].append(labelme_shape) with open(output_file, 'w') as f: json.dump(labelme_data, f, indent=4) # 使用示例 coco_json = 'coco.json' output_file = 'labelme.json' convert_to_labelme(coco_json, output_file) ``` 代码中,我们首先读取coco数据集json文件,然后遍历其中的标注信息。对于每个标注,我们提取相应的像信息,包括文件名、高度和宽度。然后,我们根据标注的边界框信息计算出在labelme中需要的矩形坐标。最后,将这些信息添加到一个的labelme数据结构中,并将其保存为一个json文件。 你需要将`coco.json`替换为你的coco数据集json文件路径,将`labelme.json`替换为你想要保存的output文件路径。 请注意,这只是一个示例代码,具体实现可能会依赖于你的具体数据集标注格式,你可能需要根据自己的情况进行修改。 ### 回答3: 要将COCO数据集中的类别片和JSON标注转换为Labelme的JSON格式,你可以按照如下步骤进行: 1. 导入所需的库: ``` import json import os import cv2 ``` 2. 定义函数用于转换: ``` def coco_to_labelme(coco_image_path, coco_json_path, output_path): with open(coco_json_path, 'r') as f: coco_json = json.load(f) labelme_json = { "flags": {}, "shapes": [], "imagePath": coco_json['images'][0]['file_name'], "imageData": None, "imageHeight": coco_json['images'][0]['height'], "imageWidth": coco_json['images'][0]['width'] } for annotation in coco_json['annotations']: labelme_shapes = { "label": coco_json['categories'][annotation['category_id'] - 1]['name'], "points": [], "group_id": None, "shape_type": "polygon", "flags": {} } for bbox in annotation['segmentation'][0]: labelme_shapes['points'].append(bbox) labelme_json['shapes'].append(labelme_shapes) with open(output_path, 'w') as f: json.dump(labelme_json, f, indent=4) ``` 3. 执行转换操作: ``` coco_image_path = "path/to/coco/image.jpg" coco_json_path = "path/to/coco/annotation.json" output_path = "path/to/output/labelme.json" coco_to_labelme(coco_image_path, coco_json_path, output_path) ``` 这些步骤将使用提供的COCO像路径、COCO JSON路径和输出路径,加载COCO JSON文件并提取有关像和标注的信息。然后将转换后的数据保存为Labelme的JSON格式文件。这样就可以将COCO数据集中的单独像和JSON标注转换为Labelme的JSON格式了。请注意,标注转换成多边形形状,适用于多边形或自由形状的目标。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值