Plt绘图到OpenCV图像/数字数组

时间:2019-03-20 13:12:54

标签: opencv matplotlib

我有一段代码用于可视化图形:

if (visualize == True):
    # Black removed and is used for noise instead.
    unique_labels = set(db.labels_)
    colors = [plt.cm.Spectral(each)
            for each in np.linspace(0, 1, len(unique_labels))]
    for k, col in zip(unique_labels, colors):
        if k == -1:
            # Black used for noise.
            col = [0, 0, 0, 1]

        class_member_mask = (db.labels_ == k)

        xy = scaled_points[class_member_mask & core_samples_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
                markeredgecolor='k', markersize=14)

        xy = scaled_points[class_member_mask & ~core_samples_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
                markeredgecolor='k', markersize=6)

    # display the graph
    plt.title('Estimated number of clusters: %d' % n_clusters_)
    plt.show()

    # get the image into a variable that OpenCV likes
    # uh, how?

在此有效的同时,我希望将最终结果(无论显示的内容)作为OpenCV图像。

由于我什至没有变量-image-,所以我不知道该如何实现。

有人做过类似的事情吗?

编辑:我实际上正在接近。现在,我可以用fig创建一个OpenCV映像,但是内容不正确。无花果是空的。我想知道哪里出问题了?为什么它没有从上方获取plt对象并绘制实际内容?

fig = plt.figure()
canvas = FigureCanvas(fig)
canvas.draw()

# convert canvas to image
graph_image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
graph_image  = graph_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))

# it still is rgb, convert to opencv's default bgr
graph_image = cv2.cvtColor(graph_image,cv2.COLOR_RGB2BGR)

1 个答案:

答案 0 :(得分:0)

好吧,我终于明白了!必须从一开始就创建fig对象,然后使用必要的绘图功能,然后转换为canvas,然后转换为OpenCV图像。

编辑:由于@ImportanceOfBeingErnest的建议,现在的代码更加简单了!

这是完整的代码:

if (visualize == True):
    # create a figure
    fig = plt.figure()

    # Black removed and is used for noise instead.
    unique_labels = set(db.labels_)
    colors = [plt.cm.Spectral(each)
            for each in np.linspace(0, 1, len(unique_labels))]
    for k, col in zip(unique_labels, colors):
        if k == -1:
            # Black used for noise.
            col = [0, 0, 0, 1]

        class_member_mask = (db.labels_ == k)

        xy = scaled_points[class_member_mask & core_samples_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
                markeredgecolor='k', markersize=14)

        xy = scaled_points[class_member_mask & ~core_samples_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
                markeredgecolor='k', markersize=6)

    # convert it to an OpenCV image/numpy array
    canvas = FigureCanvas(fig)
    canvas.draw()

    # convert canvas to image
    graph_image = np.array(fig.canvas.get_renderer()._renderer)

    # it still is rgb, convert to opencv's default bgr
    graph_image = cv2.cvtColor(graph_image,cv2.COLOR_RGB2BGR)