[英]How to save image in AWS Lambda function which is generated by python matplotlib?
I have the below python code.我有下面的python代码。 It takes
.wav
file as an input via postman.它通过邮递员将
.wav
文件作为输入。 It is received here as a base64 string which is then decoded back from base64.它在这里作为 base64 字符串接收,然后从 base64 解码回来。 The code further processes the
.wav
file and generates the .png
image.该代码进一步处理
.wav
文件并生成.png
图像。 I have to save that in AWS S3.我必须将其保存在 AWS S3 中。 I am facing problems in saving it to AWS S3 because the file that is saved there does not open.
我在将其保存到 AWS S3 时遇到问题,因为保存在那里的文件没有打开。 It says
photo viewer doesn't support this file format
.它说
photo viewer doesn't support this file format
。 Any idea how to do this?知道如何做到这一点吗?
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")
}
You are using put_object which means that Body is not a file name :您正在使用put_object这意味着 Body不是文件名:
If you want to keep using put_object
, then it should be:如果你想继续使用
put_object
,那么它应该是:
with open(filename, 'rb') as file_obj:
s3_upload = s3.put_object( Bucket="aaa", Key="filename.png", Body=file_obj)
Or use upload_file which is more intuitive.或者使用更直观的upload_file 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.