【问题标题】:Calculating and displaying a ConvexHull计算和显示 ConvexHull
【发布时间】:2020-10-04 03:30:22
【问题描述】:

我正在尝试计算并显示 python 中一些随机点的凸包。

这是我当前的代码:

import numpy as np
import random
import matplotlib.pyplot as plt
import cv2

points = np.random.rand(25,2)   

hull = ConvexHull(points)

plt.plot(points[:,0], points[:,1], 'o',color='c')

for simplex in hull.simplices:
    plt.plot(points[simplex, 0], points[simplex, 1], 'r')

plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r', lw=-1)
plt.plot(points[hull.vertices[0],0], points[hull.vertices[0],1], 'r-')
plt.show()

我的问题:

  • 如何在 0 到 9 之间更改 X、Y 标签和点数限制?例如 (0,1,2,3,4,5,6,7,8,9)
  • 如何用圆圈标记凸包上的点? As in example

【问题讨论】:

    标签: python matplotlib scipy convex-hull


    【解决方案1】:

    np.rand() 替换为randint(0, 10) 将生成从0,1,...9 的整数坐标。

    使用“。”作为标记将导致给定点的标记更小。

    使用 'o' 作为标记,设置 markeredgecolor 并将主颜色设置为 'none' 将产生一个圆形标记,可用于船体上的点。标记的大小可以通过markersize=调整。

    fig, axes = plt.subplots(ncols=..., nrows=...) 是创建多个子图的便捷方式。

    下面是一些最小示例的代码:

    from scipy.spatial import ConvexHull
    import matplotlib.pyplot as plt
    import numpy as np
    
    points = np.random.randint(0, 10, size=(15, 2))  # Random points in 2-D
    
    hull = ConvexHull(points)
    
    fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 3))
    
    for ax in (ax1, ax2):
        ax.plot(points[:, 0], points[:, 1], '.', color='k')
        if ax == ax1:
            ax.set_title('Given points')
        else:
            ax.set_title('Convex hull')
            for simplex in hull.simplices:
                ax.plot(points[simplex, 0], points[simplex, 1], 'c')
            ax.plot(points[hull.vertices, 0], points[hull.vertices, 1], 'o', mec='r', color='none', lw=1, markersize=10)
        ax.set_xticks(range(10))
        ax.set_yticks(range(10))
    plt.show()
    

    PS:要在单独的窗口中显示绘图:

    from scipy.spatial import ConvexHull
    import matplotlib.pyplot as plt
    import numpy as np
    
    points = np.random.randint(0, 10, size=(15, 2))  # Random points in 2-D
    hull = ConvexHull(points)
    for plot_id in (1, 2):
        fig, ax = plt.subplots(ncols=1, figsize=(5, 3))
        ax.plot(points[:, 0], points[:, 1], '.', color='k')
        if plot_id == 1:
            ax.set_title('Given points')
        else:
            ax.set_title('Convex hull')
            for simplex in hull.simplices:
                ax.plot(points[simplex, 0], points[simplex, 1], 'c')
            ax.plot(points[hull.vertices, 0], points[hull.vertices, 1], 'o', mec='r', color='none', lw=1, markersize=10)
        ax.set_xticks(range(10))
        ax.set_yticks(range(10))
        plt.show()
    

    【讨论】:

    • 我还有一个小问题。我怎样才能得到另一个输出,只显示点?
    • 另一个显示,但必须只显示点。像这样 ; --> 第一个显示只显示点 --> 第二个显示计算凸包并显示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多