使用matplotlib.pyplot所画图片的二进制流获取方法以及如何将它转换为图片array(附代码)

【时间】2018.11.13

【题目】使用matplotlib.pyplot所画图片的二进制流获取方法以及如何将它转换为图片array(附代码)

概述

在python中,可以通过matplotlib.pyplot进行画图并可以使用plt.savefig(save_path, dpi= ])进行保存,但是要如何才能获取所画的图的数据呢?本文主要是通过输入输出流d的io.BytesIO()方法获得所画的图的二进制流数据,并可以将它转换为array数组,从而更好地获取所画图中的数据。

一、实现代码

【代码】

import matplotlib.pyplot as plt

import numpy as np

import io

from PIL import Image

import cv2



#使用plt进行画图

img = Image.open('00.jpg') #读取图片像素为512X512

fig=plt.figure("Image",frameon=False)  # 图像窗口名称

plt.imshow(img)

canvas = fig.canvas



# 去掉图片四周的空白

plt.axis('off') # 关掉坐标轴为 off

#设置画布大小(单位为英寸),每1英寸有100个像素

fig.set_size_inches(512/100,512/100)

plt.gca().xaxis.set_major_locator(plt.NullLocator())  # plt.gca()表示获取当前子图"Get Current Axes"。

plt.gca().yaxis.set_major_locator(plt.NullLocator())

plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)

plt.margins(0, 0)



#第一种保存方式(直接对plt 进行保存)

plt.savefig('01.jpg',dpi=100)



# 第二种保存方式(获取Plt的数据并使用cv2进行保存)

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()

【运行结果】

输入与输出图片:

部分print的结果:

二、代码思路分析

2.1使用Image读取图片并用plt进行画图

#使用plt进行画图

img = Image.open('00.jpg') #读取图片像素为512X512

fig=plt.figure("Image",frameon=False)  # 图像窗口名称

plt.imshow(img)

canvas = fig.canvas

2.2 去掉plt图的白边

plt.axis('off') # 关掉坐标轴为 off

#设置画布大小(单位为英寸),每1英寸有100个像素

fig.set_size_inches(512/100,512/100)

plt.gca().xaxis.set_major_locator(plt.NullLocator())  # plt.gca()表示获取当前子图"Get Current Axes"。

plt.gca().yaxis.set_major_locator(plt.NullLocator())

plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)

plt.margins(0, 0)

2.3 获取plt 图的数据

2.3.1  通过 io.BytesIO() 获取输入输出流对象,并通过canvas.print_png(buffer) 将画布上的内容打印到输入输出流对象,最后通过buffer.getvalue()获取流的数据

buffer = io.BytesIO()  # 获取输入输出流对象

canvas.print_png(buffer)  # 将画布上的内容打印到输入输出流对象

data = buffer.getvalue()  # 获取流的值

2.3.2  将上一步获得的二进制数据转换为array,先将它写入输入输出流,再用Image.open读取获得Image对象,在使用np.asarray将它转换为array

buffer.write(data)  # 将数据写入buffer

img = Image.open(buffer)  # 使用Image打开图片数据

img = np.asarray(img)

2.4. 使用cv2.imwrite保存图片

cv2.imwrite("02.jpg", img)

猜你喜欢

转载自blog.csdn.net/C_chuxin/article/details/84000438