Python的3.8 skimage imread提供错误"int"对象没有属性"read" [英] Python's 3.8 skimage imread gives error 'int' object has no attribute 'read'
问题描述
我必须通过API网关使用AWS Lambda函数在python中读取图像,并将该图像提供给AWS SageMaker进行预测.现在,当我使用API网关获取图像时,它实际上是base64字符串,我必须将其转换回文件.当我使用 scikit-image的
skimage
imread
读取图像文件时,出现以下错误.
I have to read an image in python using AWS Lambda function via API Gateway and serve that image to AWS SageMaker for prediction. Now when I get the image using API Gateway it's actually a base64 string which I have to convert back to a file. When I read the image file using scikit-image's
skimage
imread
it gives the following error.
> "errorMessage": "'int' object has no attribute 'read'",
> "errorType": "AttributeError",
> "stackTrace": [
> " File \"/var/task/lambda_function.py\", line 51, in lambda_handler\n data = np.array([resize(imread(new_file_obj),
> (137, 310, 3))])\n",
> " File \"/var/task/lib/skimage/io/_io.py\", line 48, in imread\n img = call_plugin('imread', fname, plugin=plugin,
> **plugin_args)\n",
> " File \"/var/task/lib/skimage/io/manage_plugins.py\", line 207, in call_plugin\n return func(*args, **kwargs)\n",
> " File \"/var/task/lib/skimage/io/_plugins/pil_plugin.py\", line 51, in imread\n im = Image.open(fname)\n",
> " File \"/var/task/lib/PIL/Image.py\", line 2897, in open\n fp = io.BytesIO(fp.read())\n"
知道我在这里缺少什么吗?我的代码如下.
Any idea what I am missing here? My code is given below.
import os
import sys
CWD = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CWD, "lib"))
import json
import base64
import boto3
import numpy as np
from scipy import signal
from scipy.signal import butter, lfilter
from scipy.io import wavfile
import scipy.signal as sps
from io import BytesIO
import matplotlib.pylab as plt
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
from datetime import datetime
from skimage.io import imread
from skimage.transform import resize
ENDPOINT_NAME = ''
runtime= boto3.client('runtime.sagemaker')
def lambda_handler(event, context):
s3 = boto3.client("s3")
# retrieving data from event.
get_file_content_from_postman = event["content"]
# decoding data.
decoded_file_name = base64.b64decode(get_file_content_from_postman)
filename = '/tmp/' + 'test.png'
file_obj = open(filename, 'wb')
new_file_obj = file_obj.write(decoded_file_name)
data = np.array([resize(imread(new_file_obj), (137, 310, 3))])
response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME, ContentType='text/csv', Body=data)
result = json.loads(response['Body'].read().decode())
return result
推荐答案
You are getting the error because write:
返回写入的字节的数量.
因此,您的 new_file_obj
将只是写入的字节数,而不是新的文件对象.因此,您可以尝试以下操作:
So your new_file_obj
will be just number of bytes written, not a new file object. Thus you can try the following:
file_obj.write(decoded_file_name)
data = np.array([resize(imread(file_obj), (137, 310, 3))])
这篇关于Python的3.8 skimage imread提供错误"int"对象没有属性"read"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!