首页 > 编程语言 >【cv-python基础】不同数据集的解析

【cv-python基础】不同数据集的解析

时间:2024-06-17 18:44:56浏览次数:13  
标签:python tagtype 2D print points np 解析 data cv

前言

数据集使用之前需要对标注文件进行解析,故此记录。

代码实现

1. APA数据集解析

# 20240612: parse jsonfile to labeled image.
import argparse
import json
import os
import os.path as osp
import cv2 as cv
import numpy as np

jsonfilename = "freespace_3Dbox_APA.json"
imagepath = "image_APA"
polygon = {'Chock block', 'Convex Mirror', 'Crosswalk', 'Curb', 'Dashed line', 'Directional arrow', 'Fire Extinguisher', 'Fire hydrant', 'Floating edge', 'Free space', 'Motor vehicle', 'Non-motorized vehicle', 'Other Obstacles', 'Parking line', 'Parking number', 'Pedestrian', 'Pylon', 'Solid line', 'Speed bump', 'Steel pipe', 'Traffic cone', 'Wheel lock', 'background'}
bbox2d = {'Chock block 2D', 'Convex Mirror 2D', 'Fire Extinguisher 2D', 'Fire hydrant 2D', 'Motor vehicle 2D', 'Non-motorized vehicle 2D', 'Other Obstacles 2D', 'Pedestrian 2D', 'Steel pipe 2D', 'Traffic cone 2D', 'Tyre', 'Wheel lock 2D'}
bbox3d = {'Motor vehicle 3D'}

colors = {# BGR
        'Chock block'              : (251, 56, 56), 
        'Chock block 2D'           : (247,136, 58), 
        'Convex Mirror'            : ( 48,132, 48), 
        'Convex Mirror 2D'         : ( 56,148,228), 
        'Crosswalk'                : (243, 27,243), 
        'Curb'                     : ( 22,220,220), 
        'Dashed line'              : (255,192,203), 
        'Directional arrow'        : (  0,  0,128), 
        'Fire Extinguisher'        : (  0,255,  0), 
        'Fire Extinguisher 2D'     : (255,255,  0), 
        'Fire hydrant'             : (247, 72,249), 
        'Fire hydrant 2D'          : (103,198,209), 
        'Floating edge'            : ( 88,139, 70), 
        'Free space'               : (172,227, 65), 
        'Motor vehicle'            : ( 76,213,174), 
        'Motor vehicle 2D'         : ( 50, 83, 83), 
        'Motor vehicle 3D'         : (159,156, 73), 
        'Non-motorized vehicle'    : ( 10,239,189), 
        'Non-motorized vehicle 2D' : (183, 68,121), 
        'Other Obstacles'          : (193, 52,240), 
        'Other Obstacles 2D'       : ( 53,223, 54), 
        'Parking line'             : (  4,178,106), 
        'Parking number'           : (104, 28,162), 
        'Pedestrian'               : (  8,197,115),
        'Pedestrian 2D'            : ( 61,205,183),
        'Pylon'                    : (  5,129,227), 
        'Solid line'               : (239, 18, 44), 
        'Speed bump'               : (107,251,229), 
        'Steel pipe'               : (101, 49,243), 
        'Steel pipe 2D'            : ( 26,130, 36), 
        'Traffic cone'             : ( 54,175,167), 
        'Traffic cone 2D'          : ( 39,219,102), 
        'Tyre'                     : (142, 16,198),
        'Wheel lock'               : (174,143,124), 
        'Wheel lock 2D'            : (229,208,251), 
        'background'               : (  0,  0,  0)
    }
def parse_data_polygon(tagtype, datastr):
    # print('datastr: ', datastr)
    if isinstance(datastr, str):
        data = eval(datastr)
    assert isinstance(data, list)
    # print('data: ', data)

    pts = []
    # list - list - float
    # print('data len: ', len(data))
    # print('data[-1] len: ', len(data[-1]))
    # print('data: ', data)
    # print('data type: ', type(data))
    if len(data)==4 and isinstance(data[0], float):
        print("BBOX2D ANNOtation ERRORRRRRR, error tagtype is: ", tagtype)
    else:
        for onedata in data:
            if len(onedata) == 1:
                break
            pts.append(list(map(int, onedata[1:]))) # [x,y]
    return pts

def parse_data_bbox2d(datastr):
    # print('datastr: ', datastr)
    if isinstance(datastr, str):
        data = eval(datastr)
    assert isinstance(data, list)
    # print('data: ', data)
    box = list(map(int, data)) # [x, y, w, h]
    return box

def parse_json(path, dataset):
    i = 0
    for imgdata in dataset:
        # one image anno data.
        result = imgdata['result']
        i = i + 1
        # if not result or (i>1):
        if not result:
            # break
            continue
        file_obj = imgdata['file_obj']
        imgname = osp.split(file_obj)[-1]
        imgdata= cv.imread(osp.join(path, imagepath, imgname))
        # print("file_obj: ", file_obj)
        print("imgname: ", imgname)
        sgname = imgname.replace('.png', '_sg.png')
        odname = imgname.replace('.png', '_od.png')
        sgfile = osp.join(path, 'sg', sgname)
        odfile = osp.join(path, 'od', odname)
        # sgimg = cv.imread(osp.join(path, imagepath, imgname))
        sgimg = np.zeros_like(imgdata)
        odimg = cv.imread(osp.join(path, imagepath, imgname))
        mask = np.zeros_like(imgdata)
        maskname = imgname.replace('.png', '_mask.png')
        maskfile = osp.join(path, 'mask', maskname)
        # print("result type: ", type(result))
        # print("result len: ", len(result))
        # print("result[0]: ", result[0])

        # draw Free space
        for res in result:
            tagtype = res['tagtype']
            # print("tagtype--------------------------------------------------------------: \n\n", tagtype)
            if tagtype != 'Free space':
                continue
            # Free space
            points= parse_data_polygon(tagtype, res['data'])
            # plot polygon in seg image
            points_np = np.array(points, np.int32)
            if points:
                cv.fillPoly(mask, [points_np], colors[tagtype])

        for res in result:
            tagtype = res['tagtype']
            if tagtype == 'Free space':
                continue
            if tagtype == 'Motor vehicle 3D': 
                # print("tagtype--------------------------------------------------------------: ", tagtype)
                points= parse_data_polygon(tagtype, res['data'])
                # plot bbox3d in od image
                points_np = np.array(points, np.int32)
                if points:
                    cv.polylines(odimg, [points_np], True, colors[tagtype])
            elif tagtype == 'Floating edge': 
                # print("tagtype--------------------------------------------------------------: ", tagtype)
                points= parse_data_polygon(tagtype, res['data'])
                # plot floating edge in seg image
                points_np = np.array(points, np.int32)
                if points:
                    cv.polylines(mask, [points_np], False, colors[tagtype], 5)
            elif tagtype in polygon: 
                # print("tagtype--------------------------------------------------------------: ", tagtype)
                points= parse_data_polygon(tagtype, res['data'])
                # plot polygon in seg image
                points_np = np.array(points, np.int32)
                # print('points_np: ', points_np)
                if points:
                    cv.fillPoly(mask, [points_np], colors[tagtype])
            elif tagtype in bbox2d: 
                x, y, w, h = parse_data_bbox2d(res['data']) # Rect(xywh)
                # rect = cv.Rect(x, y, w, h)
                # plot bbox2d in od image
                cv.rectangle(odimg, (x,y), (x+w, y+h), colors[tagtype]) # (leftup, rightdown) 
                # cv.rectangle(odimg, rect, color) #  
        cv.addWeighted(imgdata, 0.7, mask, 0.3, 0, sgimg)
        # save seg and od image.
        cv.imwrite(sgfile, sgimg)
        cv.imwrite(odfile, odimg)
        cv.imwrite(maskfile, mask)

def json2annoimg(path):
    jsonfile=os.path.join(path, jsonfilename)
    dataset=json.load(open(jsonfile, 'r'))
    num=len(dataset)
    parse_json(path, dataset)

if __name__ == "__main__":
    path = os.path.dirname(os.path.realpath(__file__))
    json2annoimg(path)
View Code

 数据集特点:标注文件中含有语义分割、目标检测的类别,语义分割一般使用polygon标注,目标检测使用box标注,悬空边使用brokenline标注,解析标注文件的目的是将标注的信息绘制到图像。

参考

1. RGB颜色查询 第3页 - 在线工具 - 字客网

标签:python,tagtype,2D,print,points,np,解析,data,cv
From: https://www.cnblogs.com/happyamyhope/p/18252570

相关文章

  • 【CV基础】理解woodscape数据集
    前言最近需要用到鱼眼图像做语义分割、目标检测等任务,最开始先使用woodscape数据集进行训练、测试,故此记录学习woodscape数据集。学习woodscape数据集1.随机划分数据集shell脚本#!/bin/sh#20240617:splitwoodscapedatasetof10classesrandomlybasedoncityscape......
  • 2024华为OD机试真题-出租车计费 、靠谱的车-(C++/Python)-C卷D卷-100分
    2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++) 题目描述:程序员小明打了一辆出租车去上班。出于职业敏感,他注意到这辆出租车的计费表有点问题,总是偏大。出租车司机解释说他不喜欢数字4,所以改装了计费表,任何数字位置遇到数字4就直接跳过,其余功能都正常。比如:23再多......
  • 2024华为OD机试真题-API集群负载统计-(C++/Python)-C卷D卷-100分
     2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++)题目描述某个产品的RESTfulAPI集合部署在服务器集群的多个节点上,近期对客户端访问日志进行了采集,需要统计各个API的访问频次,根据热点信息在服务器节点之间做负载均衡,现在需要实现热点信息统计查询功能。RESTfulAPI是......
  • 用Python实现学生信息管理系统
    哈喽......
  • 基于springboot的南门桥社区疫情防疫系统-48138(免费领源码+数据库)可做计算机毕业设计J
    Springboot南门桥社区疫情防疫系统的设计与实现摘 要信息化社会内需要与之针对性的信息获取途径,但是途径的扩展基本上为人们所努力的方向,由于站在的角度存在偏差,人们经常能够获得不同类型信息,这也是技术最为难以攻克的课题。针对南门桥社区疫情防疫系统等问题,对南门桥社区......
  • python中的魔法方法
    魔法方法,重载方法,重载了一些内置的操作,一些等价于重载运算符__new__为构造函数__init__为初始化函数点击查看代码classMyClass:"""静态成员变量静态成员变量是被类的所有实例共享的访问方式:通过类名."""my_static_variable=0"""......
  • 抖音直播间弹幕解析:点赞,评论,送礼,进入提示,粉丝团,关注,在线人数等
    声明:本文以教学为基准、本文提供的可操作性不得用于任何商业用途和违法违规场景。本人对任何原因在使用本人中提供的代码和策略时可能对用户自己或他人造成的任何形式的损失和伤害不承担责任。包含关注,点赞等简介这是一个用Python编写的抖音直播间信息获取工具。该服务的......
  • Java JSON组成和解析
    本框架JSON元素组成和分析,JsonElement分三大类型JsonArray,JsonObject,JsonString。JsonArray:数组和Collection子类,指定数组的话,使用ArrayList来add元素,遍历ArrayList再使用Array.newInstance生成数组并添加元素即可.JsonObject:带有泛型的封装类,给带有泛型的字段赋......
  • Python工具箱系列(五十三)
    ​​水印水印是一种常见的图片处理需求。当既需要展示,又需要保护知识产权时,就需要使用文字或者图片来打水印。下面的代码展示了文字水印与图片水印的过程。​--javascripttypescriptbashsqljsonhtmlcssccppjavarubypythongorustmarkdownfrompathlibimportPathfromPILimp......
  • 高速公路视频监控系统与车牌抓拍:EasyCVR视频监控技术助力交通道路安全监控
    随着科技的不断发展,高速公路视频监控与车牌抓拍系统作为智能交通的重要组成部分,日益发挥着不可或缺的作用。这些先进的技术不仅提高了道路交通的管理效率,也为保障行车安全提供了新的手段。高速公路视频监控系统的应用,极大地增强了道路监控的实时性和全面性。通过安装在关键路段的......