前言
开发的时候,遇到一个标注的json文件中多边形的框的表示,一时忘记不知道如何解析,此处主要使用eval函数,故记录之。
json文件多边形框的描述
"result": [ { "tagtype": "circle_green", "obstructed": false, "labelId": 1, "data": "[[\"M\",475.7550000000001,362.453],[\"L\",476.69799999999987,383.6790000000001],[\"L\",485.18899999999985,383.2080000000001],[\"L\",484.7170000000001,361.981],[\"Z\"]]" }, { "tagtype": "circle_green", "obstructed": false, "labelId": 2, "data": "[[\"M\",561.1320000000001,361.509],[\"L\",562.547,383.2080000000001],[\"L\",570.5659999999998,382.7360000000001],[\"L\",569.623,361.038],[\"Z\"]]" } ]
其中,
bbox是xywh格式的; 带mlz的是由点组成的线; 是否有z代表是否是闭合图形; 有的是末尾有两个z,和一个z表示的意思一样
解析
def parse_data(data): if isinstance(data, str): data = eval(data) assert isinstance(data, list) if isinstance(data[0], list): pts = [] for i, d in enumerate(data): if d[0] != 'Z': pts.append(d[1:]) # remove 'M' if len(pts) == 1: return pts[0], 'point' if data[-1][0] == 'Z': return pts, 'area' return pts, 'line' else: if len(data) == 4: return data, 'bbox' #xywh else: warnings.warn('3d bbox not supported yet')
具体地
>>> a=eval("[[\"M\",560.9090000000001,361.818],[\"L\",569.6970000000001,361.818],[\"L\",569.6970000000001,383.3330000000001],[\"L\",561.5149999999999,383.9390000000001],[\"Z\"]]") >>> a[0] ['M', 560.9090000000001, 361.818] >>> len(a) 5 >>> a[4] ['Z'] >>> b=[] >>> b.append(a[0][1:]) >>> b.append(a[1][1:]) >>> b [[560.9090000000001, 361.818], [569.6970000000001, 361.818]] >>> b.append(a[3][1:]) >>> b.append(a[2][1:]) >>> b [[560.9090000000001, 361.818], [569.6970000000001, 361.818], [561.5149999999999, 383.9390000000001], [569.6970000000001, 383.3330000000001]]View Code
参考
1. Python:eval函数 - 概念、用法、注意事项;
完
标签:361.818,python,pts,基础,569.6970000000001,eval,data,append From: https://www.cnblogs.com/happyamyhope/p/17262398.html