gpt4 book ai didi

python - 算法的动画可视化

转载 作者:行者123 更新时间:2023-12-04 10:18:56 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以为涉及图形的算法创建漂亮的可视化(在 Python 中)。

如果有一种方法可以在 Python 中做到这一点,这将非常好,这将有助于将算法代码的每个执行的逻辑步骤转换为简洁的实时插图。

在维基百科上阅读 TSP 时,我发现了这一点:

enter image description here

最佳答案

我一直通过使用从 matplotlib 创建的单个图来做到这一点。

一个示例程序是:

  • 创建多个绘图并将它们保存为图像文件
  • 遍历每个保存的图像文件并使用 opencv 读取它们
  • 使用 opencv将所有图像文件编译成一个视频文件。

  • 这是一些简化的示例代码
    import cv2
    import os
    import matplotlib.pyplot as plt

    # create a single plot
    plt.plot([1,2,3], [3, 7, 11])
    # save plot as an image
    plt.savefig(plot_directory\plot_name.jpg, format='jpg', dpi=250)
    plt.show()


    def create_video(image_folder, video_name, fps=8, reverse=False):
    """Create video out of images saved in a folder."""
    images = [img for img in os.listdir(image_folder) if img.endswith('.jpg')]
    if reverse: images = images[::-1]
    frame = cv2.imread(os.path.join(image_folder, images[0]))
    height, width, layers = frame.shape
    video = cv2.VideoWriter(video_name, -1, fps, (width,height))
    for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))
    cv2.destroyAllWindows()
    video.release()

    # use opencv to read all images in a directory and compile them into a video
    create_video('plot_directory', 'my_video_name.avi')

    create_video功能,我添加了反转帧顺序和设置每秒帧数 (fps) 的选项。
    This video on Youtube正是使用这种方法创建的。

    要应用于您的示例代码,请尝试将所有绘图函数放在您的 for 中。环形。这应该会生成您在边缘上迭代的每个大部头的图。然后每次生成绘图时,您都可以将该绘图保存到文件中。像这样的东西:
    import random
    from itertools import combinations
    from math import sqrt
    import itertools
    from _collections import OrderedDict
    import networkx as nx
    import numpy as np
    from matplotlib import pyplot as plt

    random.seed(42)
    n_points = 10


    def dist(p1, p2):
    return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)


    points = [(random.random(), random.random()) for _ in range(n_points)]
    named_points = {i: j for i, j in zip(itertools.count(), points)}

    weighted_edges = dict()
    tree_id = [None] * n_points
    min_tree = []

    for v1, v2 in combinations(named_points.values(), 2):
    d = dist(v1, v2)
    weighted_edges.update({d: ((list(named_points.keys())[list(named_points.values()).index(v1)]),
    (list(named_points.keys())[list(named_points.values()).index(v2)]))
    }
    )

    for i in range(n_points):
    tree_id[i] = i

    sorted_edges = OrderedDict(sorted(weighted_edges.items(), key=lambda t: t[0]))
    list_edges = sorted_edges.values()


    for edge in list_edges:
    if tree_id[edge[0]] != tree_id[edge[1]]:
    min_tree.append(edge)

    old_id = tree_id[edge[0]]
    new_id = tree_id[edge[1]]

    for j in range(n_points):
    if tree_id[j] == old_id:
    tree_id[j] = new_id

    print(min_tree)


    G = nx.Graph()
    G.add_nodes_from(range(n_points))
    G.add_edges_from(list_edges)

    green_edges = min_tree



    G = nx.Graph()
    G.add_nodes_from(range(n_points))
    G.add_edges_from(list_edges)
    edge_colors = ['black' if not edge in green_edges else 'red' for edge in G.edges()]
    pos = nx.spiral_layout(G)

    G2 = nx.Graph()
    G2.add_nodes_from(range(n_points))
    G2.add_edges_from(min_tree)
    pos2 = nx.spiral_layout(G2)


    plt.figure(1)
    nx.draw(G, pos, node_size=700, edge_color=edge_colors, edge_cmap=plt.cm.Reds, with_labels = True)

    plt.figure(2)
    nx.draw(G2, pos2, node_size=700, edge_color='green', edge_cmap=plt.cm.Reds, with_labels = True)

    plt.show()

    关于python - 算法的动画可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60958425/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com