在NYU40数据集上,将lableme标注的json文件转化为灰度图

可能的阻碍:

1.json文件读取

2.单通道图片的填充以及保存


编程思路:

1.生成一个单通道图片

2.读取json文件中的全部points即瞄点坐标

3.在生成的图片上绘制瞄点坐标表示的形状,并根据词表填充颜色

4.保存图片


这是lableme生成的一个json文件的基本格式,我把points部分折叠起来了,方便查看json文件全貌

points里面是全部瞄点信息


文件目录结构:

一个目录:
    json2image.py
    json(文件夹,存放所有的json文件)

文件命名为 json2image.py,执行

在这个目录里面打开终端执行json2image.py文件即可,没有参数

 


开始编程


输入输出目录的定义

output_dir = "./output/"
jsons_dir = "./json/"

定义每一种标签物体所对应的灰度值(0~255)


# 词表,千万不要动!!!!!!!!!!
word_dir = {
    'unlabeled':0,
    'wall':1,
    'floor' : 2,
    'cabinet' : 3, 
    'bed' : 4,
    'chair' : 5,
    'sofa' : 6, 
    'table' : 7, 
    'door' : 8, 
    'window' : 9, 
    'bookshelf' : 10, 
    'picture' : 11, 
    'counter' : 12, 
    'blinds' : 13, 
    'desk' : 14, 
    'shelves' : 15, 
    'curtain' : 16, 
    'dresser' : 17, 
    'pillow' : 18, 
    'mirror' : 19, 
    'floormat' : 20, 
    'clothes' : 21, 
    'ceiling' : 22, 
    'books' : 23, 
    'refrigerator' : 24, 
    'television' : 25, 
    'paper' : 26, 
    'towel' : 27, 
    'showercurtain' : 28, 
    'box' : 29, 
    'whiteboard' : 30, 
    'person' : 31,
    'nightstand' : 32,
    'toilet' : 33,
    'sink' : 34,
    'lamp' : 35,
    'bathtub' : 36,
    'bag' : 37,
    'otherstructure' : 38,
    'otherfurniture' :39,
    'otherprop' : 40 ,
}

读取字典{}类型的json文件,并返回形状信息以及图片宽高信息(宽高用作后续生成单通道图片)

# 读取字典{}类型的json文件,全部shape信息
def read_dir_json(filename):
    f = open(filename, encoding='utf-8')
    setting = json.load(f)
    # 获得shapes标签内容,即全部形状信息
    shapes = setting['shapes']
    # 获得图片宽高
    height = setting['imageHeight']
    width = setting['imageWidth']
    '''
    # 读取每一个shape
    for shape in shapes:
        # 读取label信息
        label = shape['label']
        print('label : ',label)

        # 读取点信息
        curr_points = shape['points']
        print(type(curr_points))
        print(len(curr_points))
        print(curr_points[0])
    '''
    # shapes是一个list,list的每一个元素都是一个字典,表示每一个shape
    return shapes, width, height

创建一个单通道图片

# 创建一个图片
def create_img(width=640, height=480, channel=1):
    # 创建一个全0矩阵
    img = np.zeros((height,width,channel), np.uint8)
    '''
    # draw a rectangle
    cv2.rectangle(img, (0,0), (255,255), (255), 5)
    cv2.imshow("img",img)
    cv2.imwrite('img_test3.png',img)
    cv2.waitKey(0)
    '''
    return img

根据瞄点画图形,points参数必须是一个三维列表,数据类型也要注意一下,我前面弄成uint8就报错

# 画一个封闭图形
def draw_points(img, points, color):
    # 强制类型转换,因为输入的是浮点数,不能是uint8类型
    points = np.array(points, dtype=np.int32)
    # b = np.array([[[100,100], [200,230], [150,200], [100,220]]], dtype = np.int32)
    cv2.fillPoly(img,points,color)
    return img

拿到文件夹中所有的json文件路径

# 得到所有的json文件
def get_all_json_file(jsons_dir):
    file_name = []
    for f in os.listdir(jsons_dir):
        curr_path = path.join(jsons_dir, f)
        if(not path.isfile(curr_path)):
            print("警告!文件\""+curr_path+"\"是文件夹")
            continue
        if(not f.split('.')[-1] == 'json'):
            print("警告!文件\""+curr_path+"\"不是json文件")
            continue
        file_name.append(curr_path)
    return file_name

至此,基本的模块都有了,下面进行模块的拼接


通过一个json文件生成对应的单通道图片

# 处理一个json文件
def deal_json(json_file):
    if(not path.exists(json_file)):
        print("错误!文件\""+json_file+"\"不存在")
        assert(0)
    # 拿到json数据
    shapes, width, height = read_dir_json(json_file)
    # 创建图片
    img = create_img(width=width, height=height)
    # 拿到标签
    # 拿到所有的区域
    for shape in shapes:
        points = []
        points.append(shape['points'])
        # 拿到标签颜色
        try:
            color = word_dir[shape['label']]
        except:
            color = 0
            print("错误!没有\""+shape['label']+"\"这个标签")
            assert(0)
        # 画
        img = draw_points(img, points, color)
    return img

主函数读取目录,将整个文件夹的json文件转化为单通道图片

def main():
    if(not path.exists(jsons_dir)):
        print("错误!json文件目录\""+jsons_dir+"\"不存在")
        assert(0)
    if(not path.exists(output_dir)):
        print("警告!输出文件目录不存在")
        os.mkdir(output_dir)
        print("输出文件目录创建成功")
    jsons_path = get_all_json_file(jsons_dir)
    length = len(jsons_path)
    index = 0
    for json_path in jsons_path:
        print("\r正在处理文件:\""+json_path+"\"")
        img = deal_json(json_path)
        img_name = path.basename(json_path).split('.')[0]+".png"
        img_path = path.join(output_dir,img_name)
        cv2.imwrite(img_path,img)
        index += 1
        print("\r当前进度:{:2f}%".format((index/length)*100),end=' ')
    print("\n")
    pass

执行主函数


if __name__ == "__main__":
    main()
    # test_func()
    pass

代码全部完成,下面是整个文件代码


import json
# 使用numpy创建图片
import numpy as np
# 使用opencv保存图片
import cv2
# 使用os进行路径管理
import os
import os.path as path

'''
超参数
'''
output_dir = "./output/"
jsons_dir = "./json/"


# 词表,千万不要动!!!!!!!!!!
word_dir = {
    'unlabeled':0,
    'wall':1,
    'floor' : 2,
    'cabinet' : 3, 
    'bed' : 4,
    'chair' : 5,
    'sofa' : 6, 
    'table' : 7, 
    'door' : 8, 
    'window' : 9, 
    'bookshelf' : 10, 
    'picture' : 11, 
    'counter' : 12, 
    'blinds' : 13, 
    'desk' : 14, 
    'shelves' : 15, 
    'curtain' : 16, 
    'dresser' : 17, 
    'pillow' : 18, 
    'mirror' : 19, 
    'floormat' : 20, 
    'clothes' : 21, 
    'ceiling' : 22, 
    'books' : 23, 
    'refrigerator' : 24, 
    'television' : 25, 
    'paper' : 26, 
    'towel' : 27, 
    'showercurtain' : 28, 
    'box' : 29, 
    'whiteboard' : 30, 
    'person' : 31,
    'nightstand' : 32,
    'toilet' : 33,
    'sink' : 34,
    'lamp' : 35,
    'bathtub' : 36,
    'bag' : 37,
    'otherstructure' : 38,
    'otherfurniture' :39,
    'otherprop' : 40 ,
}

# 读取字典{}类型的json文件,全部shape信息
def read_dir_json(filename):
    f = open(filename, encoding='utf-8')
    setting = json.load(f)
    # 获得shapes标签内容,即全部形状信息
    shapes = setting['shapes']
    # 获得图片宽高
    height = setting['imageHeight']
    width = setting['imageWidth']
    '''
    # 读取每一个shape
    for shape in shapes:
        # 读取label信息
        label = shape['label']
        print('label : ',label)

        # 读取点信息
        curr_points = shape['points']
        print(type(curr_points))
        print(len(curr_points))
        print(curr_points[0])
    '''
    # shapes是一个list,list的每一个元素都是一个字典,表示每一个shape
    return shapes, width, height

# 创建一个图片
def create_img(width=640, height=480, channel=1):
    # 创建一个全0矩阵
    img = np.zeros((height,width,channel), np.uint8)
    '''
    # draw a rectangle
    cv2.rectangle(img, (0,0), (255,255), (255), 5)
    cv2.imshow("img",img)
    cv2.imwrite('img_test3.png',img)
    cv2.waitKey(0)
    '''
    return img

# 画一个封闭图形
def draw_points(img, points, color):
    # 强制类型转换,因为输入的是浮点数,不能是uint8类型
    points = np.array(points, dtype=np.int32)
    # b = np.array([[[100,100], [200,230], [150,200], [100,220]]], dtype = np.int32)
    cv2.fillPoly(img,points,color)
    return img

# 处理一个json文件
def deal_json(json_file):
    if(not path.exists(json_file)):
        print("错误!文件\""+json_file+"\"不存在")
        assert(0)
    # 拿到json数据
    shapes, width, height = read_dir_json(json_file)
    # 创建图片
    img = create_img(width=width, height=height)
    # 拿到标签
    # 拿到所有的区域
    for shape in shapes:
        points = []
        points.append(shape['points'])
        # 拿到标签颜色
        try:
            color = word_dir[shape['label']]
        except:
            color = 0
            print("错误!没有\""+shape['label']+"\"这个标签")
            assert(0)
        # 画
        img = draw_points(img, points, color)
    return img

# 得到所有的json文件
def get_all_json_file(jsons_dir):
    file_name = []
    for f in os.listdir(jsons_dir):
        curr_path = path.join(jsons_dir, f)
        if(not path.isfile(curr_path)):
            print("警告!文件\""+curr_path+"\"是文件夹")
            continue
        if(not f.split('.')[-1] == 'json'):
            print("警告!文件\""+curr_path+"\"不是json文件")
            continue
        file_name.append(curr_path)
    return file_name

# 测试函数
def test_func():
    a = np.array([[[10,10], [100,10], [100,100], [10,100]]], dtype = np.int32)
    b = np.array([[[100,100], [200,230], [150,200], [100,220]]], dtype = np.int32)
    print(a.shape)
    im = np.zeros([240, 320, 1], dtype = np.uint8)
    # 画线
    # cv2.polylines(im, a, 1, 255)
    # 画一个区域并填充
    cv2.fillPoly(im, b, 255)
    cv2.imshow("img",im)
    cv2.waitKey(0)
    return 0

def main():
    if(not path.exists(jsons_dir)):
        print("错误!json文件目录\""+jsons_dir+"\"不存在")
        assert(0)
    if(not path.exists(output_dir)):
        print("警告!输出文件目录不存在")
        os.mkdir(output_dir)
        print("输出文件目录创建成功")
    jsons_path = get_all_json_file(jsons_dir)
    length = len(jsons_path)
    index = 0
    for json_path in jsons_path:
        print("\r正在处理文件:\""+json_path+"\"")
        img = deal_json(json_path)
        img_name = path.basename(json_path).split('.')[0]+".png"
        img_path = path.join(output_dir,img_name)
        cv2.imwrite(img_path,img)
        index += 1
        print("\r当前进度:{:2f}%".format((index/length)*100),end=' ')
    print("\n")
    pass

if __name__ == "__main__":
    main()
    # test_func()
    pass

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值