日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

matplotlib figure转为numpy array或者PIL图像进行显示

發布時間:2024/4/15 编程问答 57 豆豆
生活随笔 收集整理的這篇文章主要介紹了 matplotlib figure转为numpy array或者PIL图像进行显示 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

matplotlib figure轉為numpy array或者PIL圖像進行顯示

實現將matplotlib繪制的圖像轉換為numpy數組,并使用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中運行出現"AttributeError: 'FigureCanvasInterAgg' object has no attribute 'renderer'"?的錯誤,請參考修改:

https://stackoverflow.com/questions/51214140/attributeerror-figurecanvasinteragg-object-has-no-attribute-renderer解決

總結

以上是生活随笔為你收集整理的matplotlib figure转为numpy array或者PIL图像进行显示的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。