如何使用Python 3从S3获得的OpenCV读取图像? [英] How to read image using OpenCV got from S3 using Python 3?
本文介绍了如何使用Python 3从S3获得的OpenCV读取图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的S3存储桶文件夹中有一堆图像.
I have a bunch of images in my S3 bucket folder.
我有一个来自S3(img_list
)的按键列表,我可以读取和显示图像:
I have a list of keys from S3 (img_list
) and I can read and display the images:
key = img_list[0]
bucket = s3_resource.Bucket(bucket_name)
img = bucket.Object(key).get().get('Body').read()
我有一个功能:
def image_from_s3(bucket, key):
bucket = s3_resource.Bucket(bucket)
image = bucket.Object(key)
img_data = image.get().get('Body').read()
return Image.open(io.BytesIO(img_data))
现在我要使用OpenCV读取图像,但出现错误:
Now what I want is to read the image using OpenCV but I am getting an error:
key = img_list[0]
bucket = s3_resource.Bucket(bucket_name)
img = bucket.Object(key).get().get('Body').read()
cv2.imread(img)
SystemError Traceback (most recent call last)
<ipython-input-13-9561b5237a85> in <module>
2 bucket = s3_resource.Bucket(bucket_name)
3 img = bucket.Object(key).get().get('Body').read()
----> 4 cv2.imread(img)
SystemError: <built-in function imread> returned NULL without setting an error
请建议如何正确阅读它?
Please advise how to read it in the right way?
推荐答案
对不起,我在注释中弄错了.这段代码在内存缓冲区中设置了一个PNG文件,以模拟您从S3获得的内容:
Sorry, I got it wrong in the comments. This code sets up a PNG file in a memory buffer to simulate what you get from S3:
#!/usr/bin/env python3
from PIL import Image, ImageDraw
import cv2
# Create new solid red image and save to disk as PNG
im = Image.new('RGB', (640, 480), (255, 0, 0))
im.save('image.png')
# Slurp entire contents, raw and uninterpreted, from disk to memory
with open('image.png', 'rb') as f:
raw = f.read()
# "raw" should now be very similar to what you get from your S3 bucket
现在,我需要的是这个
nparray = cv2.imdecode(np.asarray(bytearray(raw)), cv2.IMREAD_COLOR)
因此,您需要:
bucket = s3_resource.Bucket(bucket_name)
img = bucket.Object(key).get().get('Body').read()
nparray = cv2.imdecode(np.asarray(bytearray(img)), cv2.IMREAD_COLOR)
这篇关于如何使用Python 3从S3获得的OpenCV读取图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文