Is there a way to convert a pyplot.imshow () object to a numpy array?

I need to render a 2D numpy array. For this I use pyplot. Here is the code:

import cv2 as cv
import numpy as np
from matplotlib import pyplot

img = pyplot.imshow( radiance_val )
#radiance_val is a 2D numpy array of size = ( 512, 512 ) 
#filled with np.float32 values

pyplot.show()

I get the output as expected.

Now my question is: is there a way to convert "img" in the above code from pyplot to numpy type. I need this so that I can load the visualization as an opencv image and do further processing on it. I am using python 2.7, 32 bit.

Request for help

thank


EDIT 1: Following Thorsten Kranz Solution

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
import PIL
from cStringIO import StringIO

frame1 = plt.gca()
frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
plt.imshow(np.random.random((10,10)))

buffer_ = StringIO()
plt.savefig( buffer_, format = "png", bbox_inches = 'tight', pad_inches = 0 )
buffer_.seek(0)

image = PIL.Image.open( buffer_ )

ar = np.asarray(image)
cv.imshow( 'a', ar )
cv.waitKey(0)
cv.destroyAllWindows()

Here I get a runtime error from the MS VC ++ runtime library after the program terminates. Better to guess that this is because of the open "buffer_". But I get the desired result.


EDIT 2: closing a buffer with

buffer_.close()

did not resolve the runtime error


:

+4
2

..,

im._rgba_cache

MxNx4 numpy, .

, imshow (. guide )

my_cm = maplotlib.cm.get_cmap('Reds')
normed_data = (data - np.min(data)) / (np.max(data) - np.min(data))
mapped_data = my_cm(normed_data)

MxNx4, 0 1,

mapped_datau8 = (255 * my_cm(normed_data)).astype('uint8')

mapped_data = my_cm(normed_data, bytes=True)

unsigned ints.

matplotlib , . .

get_cmap doc

edit: fooobar.com/questions/1149313/...

+9

, ?

:

  • StringIO- savefig
  • , PIL opencv
  • numpy

. :

import numpy as np
import matplotlib.pyplot as plt
import PIL
from cStringIO import StringIO

plt.imshow(np.random.random((20,20)))
buffer_ = StringIO()
plt.savefig(buffer_, format = "png")
buffer_.seek(0)
image = PIL.Image.open(buffer_)
ar = np.asarray(image)
buffer_.close()

savefig - *args **kwargs , , dpi, , , ..

, , .., ,

plt.subplots_adjust(0,0,1,1)

. aspect , mpl .

+4

All Articles