matplotlib figure转为numpy array或者PIL图像进行显示
生活随笔
收集整理的這篇文章主要介紹了
matplotlib figure转为numpy array或者PIL图像进行显示
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
matplotlib figure轉(zhuǎn)為numpy array或者PIL圖像進行顯示
實現(xiàn)將matplotlib繪制的圖像轉(zhuǎn)換為numpy數(shù)組,并使用PIL或者OpenCV進行顯示
參考資料:http://www.icare.univ-lille1.fr/tutorials/convert_a_matplotlib_figure
# -*- coding: utf-8 -*- """ # -------------------------------------------------------- # @Author : panjq # @E-mail : pan_jinquan@163.com # @Date : 2020-02-05 11:01:49 # -------------------------------------------------------- """import matplotlib.pyplot as plt import numpy as np import cv2def fig2data(fig):"""fig = plt.figure()image = fig2data(fig)@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it@param fig a matplotlib figure@return a numpy 3D array of RGBA values"""import PIL.Image as Image# draw the rendererfig.canvas.draw()# Get the RGBA buffer from the figurew, h = fig.canvas.get_width_height()buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)buf.shape = (w, h, 4)# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA modebuf = np.roll(buf, 3, axis=2)image = Image.frombytes("RGBA", (w, h), buf.tostring())image = np.asarray(image)return imageif __name__ == "__main__":# Generate a figure with matplotlib</font>figure = plt.figure()plot = figure.add_subplot(111)# draw a cardinal sine plotx = np.arange(1, 100, 0.1)y = np.sin(x) / xplot.plot(x, y)plt.show()##image = fig2data(figure)cv2.imshow("image", image)cv2.waitKey(0)如果在Pycharm中運行出現(xiàn)"AttributeError: 'FigureCanvasInterAgg' object has no attribute 'renderer'"?的錯誤,請參考修改:
https://stackoverflow.com/questions/51214140/attributeerror-figurecanvasinteragg-object-has-no-attribute-renderer解決
總結(jié)
以上是生活随笔為你收集整理的matplotlib figure转为numpy array或者PIL图像进行显示的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OpenCV cv2.putText实现
- 下一篇: 世界坐标系,相机坐标系和图像坐标系的转换