1

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?

3
  • You could try to check this following link. It might help Commented Jun 13, 2021 at 6:24
  • @soothy Thanks for the comment. The link works, but the problem is that it takes the image's input as a small-windowed image. If I try to make it a full-windowed image as mentioned here: link. However, it still saves as in small-windowed image. Commented Jun 13, 2021 at 7:27
  • I got it. Thanks. Commented Jun 13, 2021 at 7:30

2 Answers 2

0
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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for sharing complete code snippet.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.