我正在开发一个在容器上运行的flask应用程序,从那里我必须将一些绘图保存到google云平台存储桶中。
例如,我有以下代码来绘制一个混淆矩阵:
cm = confusion_matrix(target, predictions, labels=classes)
np.set_printoptions(precision=2)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.tight_layout()
file_name = self.data_dir + self.name + file_name
plt.savefig(file_name)在最后一行中,将图像保存在' file_name‘中,即file_name= 'data/my_plot.png’
如果我单独运行flask应用程序,这会起作用,但如果它在容器中,我就没有权限写入永久文件,除非我绑定了一个目录或类似的东西。
我的计划是将图像直接保存在存储桶中,因此我有以下代码:
from google.cloud import storage
bucket_name='models'
source_file_name='jobdesc.zip'
destination_blob_name='jobdesc.zip'
credentials = 'xx.json'
def upload_blob(bucket_name, source_file_name, destination_blob_name,credentials):
"""Uploads a file to the bucket."""
client = storage.Client.from_service_account_json(credentials)
bucket = client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print('File {} uploaded to {}.'.format(
source_file_name,
destination_blob_name))但是在其他情况下,我必须已经保存了文件,因为我只是发送我想要上传的文件的路径。
是否可以跳过这一步,直接将镜像从容器保存到存储桶中?
或者是否有必要首先绑定目录并从那里上传文件?
发布于 2019-09-10 11:41:10
matplotlib可以将图形保存为字节,但您需要提供format参数,因为它不再能从文件扩展名推断格式:
In [35]: import io
In [36]: buffer = io.BytesIO()
In [37]: plt.plot(range(10))
Out[37]: [<matplotlib.lines.Line2D at 0x102d06f4a8>]
In [39]: plt.savefig(buffer, format='png')
In [40]: buffer.getvalue()
Out[40]: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x02\x80\x00\x00\x01\xe0\x08\x06\x00\x00\x005\xd1\xdc\xe4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\x00\tpHYs\x00\x00\x0fa\x00\x00\x0fa\x01\xa8?\xa7i\x00\x00\x009tEXtSoftware\x00matplotlib version 3.0.0, http://matplotlib.org/\xa8\xe6\x1d\xf0\x00\x00 \x00IDATx\x9c\xed\xddyx\x94\x85\xbd\xf6\xf1{f\xb2\xaf\x90@\xc2\x16 \xac\x01\x02Y\x00然后使用upload_from_string而不是upload_from_file将buffer.getvalue()的结果上传到google blob存储中。
https://stackoverflow.com/questions/57863607
复制相似问题