将JSON坐标转换为numpy数组

2024-10-03 06:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将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被指定为一种特定的颜色


Tags: 文件数据图像numpylayerjson列表png
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:27

以下是一个解决方案:

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()

输出:

enter image description here

相关问题 更多 >