Cornell datasets转coco .json格式

废话不说,直接上代码。

// cornell 2 coco
// An highlighted block
# -*- coding: UTF-8 -*-
import cv2
import json
import sys
from juli import Point, Line
from jiaodian_zhongxin import Point_1, Line_1
import math
import glob
import PIL.Image
import os,sys
# # zixiu #######
src_img_dir = "/home/dms/Documents/Cornell_Grasp_Detection_Dataset/one_label_annotation/jpg_xml/test2017/"

src_txt_dir = "/home/dms/Documents/Cornell_Grasp_Detection_Dataset/pos_label"
img_Lists = glob.glob(src_img_dir + '/*.jpg')
print('444' , img_Lists)
img_basenames = []  # e.g. 100.jpg
for item in img_Lists:
    img_basenames.append(os.path.basename(item))
    print(os.path.basename(item) + '-------------')
img_names = []  # e.g. 100
for item in img_basenames:
    temp1, temp2 = os.path.splitext(item)
    img_names.append(temp1[0:7])
    print(temp1[0:7] + '====' + temp2)
print('********************************************')

#########################################################################################

# process bar
def process_bar(count, total, status=''):
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)

    sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', status))
    sys.stdout.flush()
          
#root_path = "data_with_box_example/"
images, categories, annotations = [], [], []
         
category_dict = {"people": 1}
 
for cat_n in category_dict: 
    categories.append({"supercategory": "", "id": category_dict[cat_n], "name": cat_n})
img_id = 0
for img in img_names:
    try:
        gt = open(src_txt_dir + '/' + img + 'cpos.txt').read().splitlines()  # 把txt文件里每一行提取出来,我的txt有两行
        lines = len(open(src_txt_dir + '/' + img + 'cpos.txt').readlines())
        print('1********************************************', gt[0], 'lines = ', lines)
    except:
        continue  # 跳过这次循环,进入下一张图片循环
    
    with open(src_txt_dir + '/' + img + 'cpos.txt', 'r') as f:
        # img_id = 0
        anno_id_count = 0
        count = 1
        total = 100
        for line in range(1):
            process_bar(count, total)
            count += 1
            # line = line.split(' ')
            # img_name = line[0].replace('/', '_')
            img_name = img
            # bbox_num = int(line[1])
            bbox_num = 1
            # img_cv2 = cv2.imread(root_path + img_name)
            img_cv2 = cv2.imread(src_img_dir + '/' + img + 'r.jpg')
            [height, width, _] = img_cv2.shape

            # images info
            images.append({"file_name": img_name + 'r.jpg', "height": height, "width": width, "id": img_id})

            """
            annotation info:
            id : anno_id_count
            category_id : category_id
            bbox : bbox
            segmentation : [segment]
            area : area
            iscrowd : 0
            image_id : image_id
            """
            category_id = category_dict["people"]
            for i in range(1):

                spt1 = gt[i].split(' ')  # 这里如果txt里面是以逗号‘,’隔开的,那么就改为spt = img_each_label.split(',')。左上角
                spt2 = gt[i + 1].split(' ')  # 左下
                spt3 = gt[i + 2].split(' ')  # 右上
                spt4 = gt[i + 3].split(' ')  # 右下

                x1 = float(spt1[0])
                y1 = float(spt1[1])
                x2 = float(spt2[0])
                y2 = float(spt2[1])
                x3 = float(spt3[0])
                y3 = float(spt3[1])
                x4 = float(spt4[0])
                y4 = float(spt4[1])

                print('x1:=', x1, 'y1:=', y1, 'x2:=', x2, 'y2:=', y2, 'x3:=', x3, 'y3:=', y3, 'x4:=', x4, 'y4:=', y4)
                y1 = float(spt1[1])
                x2 = float(spt2[0])
                y2 = float(spt2[1])
                x3 = float(spt3[0])
                y3 = float(spt3[1])
                x4 = float(spt4[0])
                y4 = float(spt4[1])

                print('x1:=', x1, 'y1:=', y1, 'x2:=', x2, 'y2:=', y2, 'x3:=', x3, 'y3:=', y3, 'x4:=', x4, 'y4:=', y4)

                l1 = Line(x1, y1, x2, y2)
                l2 = Line(x1, y1, x4, y4)
                l3 = Line(x1, y1, x3, y3)
                l4 = Line(x2, y2, x3, y3)
                l5 = Line(x2, y2, x4, y4)
                l6 = Line(x3, y3, x4, y4)
                len_line = [l1.getlen(), l2.getlen(), l3.getlen(), l4.getlen(), l5.getlen(), l6.getlen()]
                len_line.sort(reverse=True)
                print('len_line:=', len_line)
                print('l1:=', l1.getlen(), 'l2:=', l2.getlen(), 'l3:=', l3.getlen(), 'l4:=', l4.getlen(), 'l5:=', l5.getlen(), 'l6:=', l6.getlen())

                zhongixndian_zuobiao = []

                if (l1.getlen() == len_line[0]) or  (l1.getlen() == len_line[1]):
                    duijiaoxian = Line_1(x1, y1, x2, y2, x3, y3, x4, y4)
                elif (l2.getlen() == len_line[0]) or (l2.getlen() == len_line[1]):
                    duijiaoxian = Line_1(x1, y1, x4, y4, x2, y2, x3, y3)
                elif (l3.getlen() == len_line[0]) or (l3.getlen() == len_line[1]):
                    duijiaoxian = Line_1(x1, y1, x3, y3, x2, y2, x4, y4)
                print('duijiaoxian:=',duijiaoxian)

                zhongixndian_zuobiao = duijiaoxian.cross_point()
                print('zhongixndian_zuobiao:=',zhongixndian_zuobiao)

                #x1 = float(line[i * 5 + 3])
                #y1 = float(line[i * 5 + 4])
                #x2 = float(line[i * 5 + 3]) + float(line[i * 5 + 5])
                #y2 = float(line[i * 5 + 4]) + float(line[i * 5 + 6])
                #width = float(line[i * 5 + 5])
                #height = float(line[i * 5 + 6])
                width = (len_line[2])
                print('width:=', len_line[2])
                height = (len_line[4])
                print('height:=', len_line[4])

                x1_zuoshang = float(zhongixndian_zuobiao[0] - width/2)
                y1_zuoshang = float(zhongixndian_zuobiao[1] - height/2)
                x2_zuoshang = float(zhongixndian_zuobiao[0] + width/2)
                y2_zuoshang = float(zhongixndian_zuobiao[1] + height/2)

                bbox = [math.ceil(x1_zuoshang), math.ceil(y1_zuoshang), math.ceil(width), math.ceil(height)]
                segment = [math.ceil(x1_zuoshang), math.ceil(y1_zuoshang), math.ceil(x2_zuoshang), math.ceil(y1_zuoshang), math.ceil(x2_zuoshang), math.ceil(y2_zuoshang), math.ceil(x1_zuoshang), math.ceil(y2_zuoshang)]
                #area = math.ceil(width * height)
                area = math.ceil(width) * math.ceil(height)

                anno_info = {'id': anno_id_count, 'category_id': category_id, 'bbox': bbox, 'segmentation': [segment],
                             'area': area, 'iscrowd': 0, 'image_id': img_id}
                annotations.append(anno_info)
                anno_id_count += 1

            img_id = img_id + 1

    all_json = {"images": images, "annotations": annotations, "categories": categories}

    with open("instances_test2017.json", "w") as outfile:
        json.dump(all_json, outfile)


下面试juli 子程序 `内联代码片`。
下面展示一些 `内联代码片`。

``

// juli

// An highlighted block
import math


class Point():
    def __init__(self, x1, y1, x2, y2):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2


class Line(Point):
    def __init__(self, x1, y1, x2, y2):
        super().__init__(x1, y1, x2, y2)

    def getlen(self):
        changdu = math.sqrt(math.pow((self.x1 - self.x2), 2) + math.pow((self.y1 - self.y2), 2))
        return changdu


下面展示一些 `内联代码片`。

// jiaodian_zhongxin.py

``

// An highlighted block
import math
class Point_1():
    def __init__(self, x1, y1, x2, y2, x3, y3, x4, y4):
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        self.x3 = x3
        self.y3 = y3
        self.x4 = x4
        self.y4 = y4

class Line_1(Point_1):

    def __init__(self, x1, y1, x2, y2, x3, y3, x4, y4):
            super().__init__(x1, y1, x2, y2, x3, y3, x4, y4)

    def cross_point(self):#计算交点函数
        x1=self.x1    # 取四点坐标
        y1=self.y1
        x2=self.x2
        y2=self.y2

        x3=self.x3
        y3=self.y3
        x4=self.x4
        y4=self.y4

        k1=(y2-y1)*1.0/((x2-x1) + 0.001)#计算k1,由于点均为整数,需要进行浮点数转化
        b1=y1*1.0-x1*k1*1.0#整型转浮点型是关键
        if (x4-x3)==0:#L2直线斜率不存在操作
            k2=None
            b2=0
        else:
            k2=(y4-y3)*1.0/(x4-x3)#斜率存在操作
            b2=y3*1.0-x3*k2*1.0
        if k2==None:
            x=x3
            x = math.ceil(x)
        else:
            x=(b2-b1)*1.0/(k1-k2)
            x = math.ceil(x)

        y=k1*x*1.0+b1*1.0
        y = math.ceil(y)
        return [x,y]

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值