Issue
I would like to know how convert a matplotlib figure to a cv2 image, this is my python3 code:
import cv2
import matplotlib.pyplot as plt
# Generating matplotlib figure and save it as a png image
plt.plot([0, 5], [0, 5])
plt.savefig('plot.png')
# Reading figure saved as png image
img_plot = cv2.imread("plot.png")
# Displaying image using opencv imshow
cv2.imshow('Image', img_plot)
# Waiting for any key to terminate image window
cv2.waitKey(0)
and the result after executing it:
Is it possible to display the figure without having to save it first?, something like this:
import cv2
import matplotlib.pyplot as plt
# Generating matplotlib plot
img_plot = plt.plot([0, 5], [0, 5])
# Displaying image using opencv imshow
cv2.imshow('Image', img_plot)
# Waiting for any key to terminate image window
cv2.waitKey(0)
but this leads to an error.
I know it's possible to display the image with plt.show()
as well, but I would like to use cv2.imshow
Solution
You can display a Matplotlib figure in OpenCV without saving it first. You need to convert the Matplotlib figure to a NumPy array before using cv2.imshow()
.
Below is an example:
import cv2
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ax.plot([0, 5], [0, 5])
fig.canvas.draw()
img_plot = np.array(fig.canvas.renderer.buffer_rgba())
cv2.imshow('Image', cv2.cvtColor(img_plot, cv2.COLOR_RGBA2BGR))
cv2.waitKey(0)
Answered By - Jake Zappin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.