如何将matplotlib.pyplot保存为特定大小的变量/ image / numpy.array((1280,720,3)或(1280,720,1))
import matplotlib.pyplot as plt
import random
data = [random.randint(1, 100) for _ in range(100)]
fig = plt.figure()
plt.hist(data)
plt.show()
# Pseudo code below
img = fig.save_as_image(1280, 720, 3)
您可以尝试以下技巧(使用PIL /枕头库):
import matplotlib.pyplot as plt
import random
import io
from scipy import misc
from PIL import Image
import numpy as np
data = [random.randint(1, 100) for _ in range(100)]
fig = plt.figure(figsize=(16, 9)) # Add figsize= to be matched with the dpi
plt.hist(data)
# Trick to write PNG into memory buffer and read it using PIL
with io.BytesIO() as out:
fig.savefig(out, format="png", dpi=80) # Add dpi= to match your figsize
pic = Image.open(out)
pix = np.array(pic.getdata(), dtype=np.uint8).reshape(pic.size[1], pic.size[0], -1)
pix