在python中从图中提取点

2024-07-07 07:32:08 发布

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

我正在寻找一种从我用Python绘制的4张图中提取点的方法,以便在这些点上运行Ramer-Douglas-peucker算法。理想情况下,由于当前数据集的呈现方式不同,数据将以一系列x和y坐标表示。每个图形由大约2000个点组成,但它们在数据集中没有被格式化为X和Y坐标。我已经附上了用于绘制图表的代码以及数据集,如果有人有任何建议。在

干杯!!在


Tags: 数据方法代码算法图形方式图表绘制
1条回答
网友
1楼 · 发布于 2024-07-07 07:32:08

插入代码行plt.gca().lines[-1].get_xydata()(就在创建绘图的那一行下方:plt.plot(distances, alts, color='blue'))将允许您提取所绘制的每条线的所有点的x-y坐标。在

然后我创建了一个空列表line_coords,用于存储四条线中每一条的x-y坐标,然后使用RDP算法迭代这四组坐标:

rdp_res = []
for line in line_coords:
    rdp_res.append(rdp(line))

列表rdp_res包含RDP算法对四行中每一行的输出:

^{pr2}$

我们可以比较每行的坐标数:

line_coords[0].shape, line_coords[1].shape, line_coords[2].shape, line_coords[3].shape

((1167, 2), (2133, 2), (2869, 2), (3597, 2))

每行运行RDP后剩余的坐标数:

rdp_res[0].shape, rdp_res[1].shape, rdp_res[2].shape, rdp_res[3].shape

((1080, 2), (1947, 2), (2643, 2), (3360, 2))

下面我粘贴了您的原始代码,包括我的所有修改:

"""
File for importing route data from a json file
"""

import json
import os
import matplotlib.pyplot as plt
from rdp import rdp
import numpy as np

def get_data(file_name):
    """
    method to retrieve JSON data from "file"
    :param file_name: string representing file in which JSON data is stored
    :return data: Pyhonic data created from JSON file information
    """
    with open(os.path.join(os.sys.path[0], file_name), "r") as data_file:
        data = json.load(data_file)  # load data from JSON file
        return data

if __name__== "__main__":
    file_name = 'json_data.json'
    routes = get_data(file_name)

print("Total Time")
print(routes[0]["totalTime"])
print("Total Distance")
print(routes[0]["totalDistance"])

routesPos = 0
edgePos = 0
edgeDistance = 0
alts = []
distances = []
line_coords = []

while routesPos < len(routes):
    while edgePos < len(routes[routesPos]["edges"]):
        edgeDistance = edgeDistance + routes[routesPos]["edges"][edgePos]["edgeDistance"]
        distances.append(edgeDistance)
        alts.append(routes[routesPos]["edges"][edgePos]["endLocation"]["alt"])
        edgePos += 1
    plt.plot(distances, alts, color='blue')
    coords = plt.gca().lines[-1].get_xydata() # Get coords for most recently plotted line
    line_coords.append(coords)
    edgeDistance = 0
    routesPos += 1
    edgePos = 0


rdp_res = []
for line in line_coords:
    rdp_res.append(rdp(line))

相关问题 更多 >