Reputation: 1067
I am plotting figure as:
plt.imshow(image, cmap='gray', interpolation='none')
plt.imshow(masked_contour, cmap='cool', interpolation='none', alpha=0.7)
plt.show()
The figure shows in greyscale with a blue contour inside it.
Now I want to get this figure as a numpy
array (also not as a masked array). One way can be, save the plot as an image, then read it from there. Is there any better approach?
Upvotes: 1
Views: 2932
Reputation: 1153
I found that all matplotlib approaches need frombuffer canvas tostring_rgb()/buffer_rgba()
hoopla and sometimes end up displaying unneeded plots or have surprising behavior when same code run on a different os(matplotlib code behaves differently depending on backend/os); They also very slow
I had to write my own plotter, justpyplot, and you can control the figure parameters, color, size of points/thickness of lines in vectorized way all in numpy:
import numpy as np
import cv2
import time
import justpyplot as jplt
xs, ys = [], []
while(cv2.waitKey(1) != 27):
xt = time.perf_counter() - t0
yx = np.sin(xt)
xs.append(xt)
ys.append(yx)
frame = np.full((500,470,3), (255,255,255), dtype=np.uint8)
vals = np.array(ys)
plotted_in_array = jplt.just_plot(frame, vals,title="sin() from Clock")
cv2.imshow('np array plot', plotted_in_array)
Upvotes: 0
Reputation: 1067
fig = plt.figure(figsize=(20, 20)) # this is imp for sizing
# plot
plt.imshow(image, cmap='gray', interpolation='none')
plt.imshow(masked_contour, cmap='cool', interpolation='none', alpha=0.7)
# get image as np.array
canvas = plt.gca().figure.canvas
canvas.draw()
data = np.frombuffer(canvas.tostring_rgb(), dtype=np.uint8)
image = data.reshape(canvas.get_width_height()[::-1] + (3,))
# (Optional) show image
plt.imshow(image)
plt.show()
Upvotes: 0