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()
其中标注为关键字样的地方最为重要