亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Matplotlib:將圖保存到numpy數組

Matplotlib:將圖保存到numpy數組

大話西游666 2019-12-27 10:18:40
在Python和Matplotlib中,很容易將圖顯示為彈出窗口或將圖另存為PNG文件。我該如何將圖另存為RGB格式的numpy數組?
查看完整描述

2 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

當您需要對保存的圖進行像素間比較時,這對于單元測試等來說是一個方便的技巧。


一種方法是使用dtype fig.canvas.tostring_rgb,然后numpy.fromstring使用它。也有其他方法,但這是我傾向于使用的方法。


例如


import matplotlib.pyplot as plt

import numpy as np


# Make a random plot...

fig = plt.figure()

fig.add_subplot(111)


# If we haven't already shown or saved the plot, then we need to

# draw the figure first...

fig.canvas.draw()


# Now we can save it to a numpy array.

data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')

data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))


查看完整回答
反對 回復 2019-12-27
?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

有人提出這樣的方法


np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')

當然,此代碼有效。但是,輸出numpy數組圖像的分辨率太低。


我的提案代碼是這個。


import io

import cv2

import numpy as np

import matplotlib.pyplot as plt


# plot sin wave

fig = plt.figure()

ax = fig.add_subplot(111)


x = np.linspace(-np.pi, np.pi)


ax.set_xlim(-np.pi, np.pi)

ax.set_xlabel("x")

ax.set_ylabel("y")


ax.plot(x, np.sin(x), label="sin")


ax.legend()

ax.set_title("sin(x)")



# define a function which returns an image as numpy array from figure

def get_img_from_fig(fig, dpi=180):

    buf = io.BytesIO()

    fig.savefig(buf, format="png", dpi=180)

    buf.seek(0)

    img_arr = np.frombuffer(buf.getvalue(), dtype=np.uint8)

    buf.close()

    img = cv2.imdecode(img_arr, 1)

    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


    return img


# you can get a high-resolution image as numpy array!!

plot_img_np = get_img_from_fig(fig)

此代碼運行良好。

如果在dpi參數上設置較大的數字,則可以將高分辨率圖像作為numpy數組獲得。


查看完整回答
反對 回復 2019-12-27
  • 2 回答
  • 0 關注
  • 1339 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號