首页 > 解决方案 > 将 JSON 坐标转换为 numpy 数组

问题描述

我想将 JSON 文件转换回 png 图像或 NumPy 数组。文件 JSON 文件由坐标列表和其他元数据组成。举个例子。它看起来像这样:

 "firstEditDate": "2019-12-02T19:05:45.393Z",
 "lastEditDate": "2020-06-30T13:21:33.371Z",
 "folder": "/Pictures/poly",
 "objects": [
  {
   "classIndex": 5,
   "layer": 0,
   "polygon": [
    {
     "x": 0,
     "y": 0
    },
    {
     "x": 1699.7291626931146,
     "y": 0
    },
    {
     "x": 1699.7291626931146,
     "y": 1066.87392714095
    },
    {
     "x": 0,
     "y": 1066.87392714095
    }
   ],
  },
  {
   "classIndex": 2,
   "layer": 0,
   "polygon": [
    {
     "x": 844.2300556586271,
     "y": 711.8243676199173
    },
    {
     "x": 851.156462585034,
     "y": 740.5194820293175
    },
    {
     "x": 854.1249226963513,
     "y": 744.477428844407
    },
    {
     "x": 854.1249226963513,
     "y": 747.4458889557243
    },

 

(在创建数组或图像之前,坐标应四舍五入到最接近的值)

数组/图片的尺寸应为 1727 x 971

python中是否有任何函数可以将文件转换为数组,其中的值包含在数组中ClassIndex?或者进入一张图片,其中每个ClassIndex都分配给特定的颜色?

标签: pythonarraysjsonnumpypng

解决方案


这是一个解决方案:

import matplotlib.pyplot as plt
import numpy as np
import mahotas.polygon as mp

json_dict = {
  "firstEditDate": "2019-12-02T19:05:45.393Z",
  "lastEditDate": "2020-06-30T13:21:33.371Z",
  "folder": "/Pictures/poly",
  "objects": [{
    "classIndex": 1,
    "layer": 0,
    "polygon": [
      {"x": 170, "y": 674},
      {"x": 70, "y": 674},
      {"x": 70, "y": 1120},
      {"x": 870, "y": 1120},
      {"x": 870, "y": 674},
      {"x": 770, "y": 674},
      {"x": 770, "y": 1020},
      {"x": 170, "y": 1020},
    ],
  }, {
    "classIndex": 2,
    "layer": 0,
    "polygon": [
      {"x": 220, "y": 870},
      {"x": 220, "y": 970},
      {"x": 720, "y": 970},
      {"x": 720, "y": 870},
    ]
  }, {
    "classIndex": 3,
    "layer": 0,
    "polygon": [
      {"x": 250, "y": 615},
      {"x": 225, "y": 710},
      {"x": 705, "y": 840},
      {"x": 730, "y": 745},
    ]
  }, {
    "classIndex": 4,
    "layer": 0,
    "polygon": [
      {"x": 350, "y": 380},
      {"x": 300, "y": 465},
      {"x": 730, "y": 710},
      {"x": 780, "y": 630},
    ]
  }, {
    "classIndex": 5,
    "layer": 0,
    "polygon": [
      {"x": 505, "y": 180},
      {"x": 435, "y": 250},
      {"x": 790, "y": 605},
      {"x": 855, "y": 535},
    ]
  }, {
    "classIndex": 6,
    "layer": 0,
    "polygon": [
      {"x": 700, "y": 30},
      {"x": 615, "y": 80},
      {"x": 870, "y": 515},
      {"x": 950, "y": 465},
    ]
  }]
}

canvas = np.zeros((1000,1150))
for obj in json_dict["objects"]:
  pts = [(round(p["x"]),round(p["y"])) for p in obj["polygon"]]
  mp.fill_polygon(pts, canvas, obj["classIndex"])
plt.imshow(canvas.transpose())
plt.colorbar()
plt.show()

输出:

在此处输入图像描述


推荐阅读