import matplotlib.pyplot as plt
import numpy as np
import io
from PIL import Image
import cv2
fig = plt.figure("Image", frameon=False)# 圖像窗口名稱
canvas = fig.canvas#關鍵
name_list = ['0', "1", "2", "3", "4", "5", "6"]
num_list = [round(random.random() * 100, 2), round(random.random() * 100, 2), round(random.random() * 100, 2),
round(random.random() * 100, 2), round(random.random() * 100, 2), round(random.random() * 100, 2),
round(random.random() * 100, 2)]
rects = plt.bar(range(len(num_list)), num_list, color='rgby')
index = [0, 1, 2, 3, 4, 5, 6]
index = [float(c) for c in index]
plt.ylim(ymax=110, ymin=0)
plt.xticks(index, name_list)
plt.ylabel("arrucay(%)") # X軸標籤
for rect in rects:
height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2, height, str(height) + '%', ha='center', va='bottom')
#關鍵
buffer = io.BytesIO()# 獲取輸入輸出流對象
canvas.print_png(buffer)# 將畫布上的內容打印到輸入輸出流對象
data = buffer.getvalue()# 獲取流的值
# print("plt的二進制流爲:\n", data)
buffer.write(data)# 將數據寫入buffer
img = Image.open(buffer)# 使用Image打開圖片數據
img = np.asarray(img)
print("轉換的圖片array的尺寸爲:\n", img.shape)
# print("轉換的圖片array爲:\n", img)
cv2.imwrite("02.jpg", img)
buffer.close()
其中標註爲關鍵字樣的地方最爲重要