gpt4 book ai didi

opencv - Plt图到OpenCV图像/数字数组

转载 作者:行者123 更新时间:2023-12-02 17:31:41 37 4
gpt4 key购买 nike

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

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)

最佳答案

好吧,我终于明白了!必须从一开始就创建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)

关于opencv - Plt图到OpenCV图像/数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55261576/

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