python-3.x - 如何将图像保存在由 python matplotlib 生成的 AWS Lambda 函数中?
问题描述
我有下面的python代码。它.wav
通过邮递员将文件作为输入。它在此处作为 base64 字符串接收,然后从 base64 解码回来。代码进一步处理.wav
文件并生成.png
图像。我必须将其保存在 AWS S3 中。我在将其保存到 AWS S3 时遇到问题,因为保存在那里的文件没有打开。它说photo viewer doesn't support this file format
。知道怎么做吗?
import json
import base64
import boto3
#import scipy.io.wavfile as wav
#import scipy.signal as signal
import numpy as np
from matplotlib import pyplot as plt
from scipy import signal
import shutil
import wavio
import wave
import matplotlib.pylab as plt
from scipy.signal import butter, lfilter
from scipy.io import wavfile
import scipy.signal as sps
from io import BytesIO
def lambda_handler(event, context):
s3 = boto3.client("s3")
# retrieving data from event. Which is the wave audio file
get_file_content_from_postman = event["content"]
# decoding data. Here the wava file is converted back to binary form
decoded_file_name = base64.b64decode(get_file_content_from_postman)
new_rate = 2000
# Read file
sample_rate, clip = wavfile.read(BytesIO(decoded_file_name))
# Resample data
number_of_samples = round(len(clip) * float(new_rate) / sample_rate)
clip = sps.resample(clip, number_of_samples)
#butter_bandpass_filter is another fuction
a = butter_bandpass_filter(clip, 20, 400, 2000, order=4)
filtered = 2*((a-min(a))/(max(a)-min(a)))-1
fig = plt.figure(figsize=[1,1])
ax = fig.add_subplot(212)
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on(False)
powerSpectrum, freqenciesFound, time, imageAxis = plt.specgram(filtered, Fs=2000)
#filename is referring to the AWS Lambda /tmp directory
filename = '/tmp/' + 'image.png'
plt.savefig(filename, dpi=400, bbox_inches='tight',pad_inches=0)
s3_upload = s3.put_object( Bucket="aaa", Key="filename.png", Body=filename)
return {
'statusCode': 200,
'body': json.dumps("Executed successfully")
}
解决方案
您正在使用put_object这意味着 Body不是文件名:
- 正文(字节或可查找的类似文件的对象)——对象数据。
如果你想继续使用put_object
,那么它应该是:
with open(filename, 'rb') as file_obj:
s3_upload = s3.put_object( Bucket="aaa", Key="filename.png", Body=file_obj)
或者使用更直观的upload_file 。
推荐阅读
- swift - UICollectionViewFlowLayoutestimatedItemSize 不能在 iOS12 上正常工作,虽然它在 iOS 11 上工作正常。*
- tensorflow - 在具有 Nvidia GPU 节点的 Kubernetes 上运行示例 pod
- html - 使用 ckeditor、tinymce 或任何在线编辑器创建自定义模板
- python - 不透明时显示一次后无法设置 QWindow 的透明度
- java - 我想得到一个开始迈出一步的时间,然后时间停止,然后得到两者的差异。我该怎么做
- google-app-engine - 自定义子域上的 AppEngine“Google 管理的自动续订”SSL 证书错误地路由内容
- verilog - Verilog 在负指数的情况下如何表现?
- c - 为什么我的 C 结构必须添加一个奇怪的 int 并且它会影响指针?
- node.js - 如何从函数返回查询结果
- javascript - 无法在 mocha 测试中加载 Jquery