I have a piece of code which I use to visualize a graph:
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?
while this works, I want to have the end result (whatever is being shown) as an OpenCV image.
Since I don't even have the variable -image-, I have no idea how to achieve this.
Did anyone do something similar?
EDIT: I am actually getting close. Now I can create an OpenCV image out of a fig
, but the contents are not right. The fig is empty. I wonder where I go wrong? Why doesn't it get the plt
object from above and draw the actual content?
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)