gpt4 book ai didi

python-3.x - 如何使用 Python 3 从 S3 获得的 OpenCV 读取图像?

转载 作者:行者123 更新时间:2023-12-02 16:16:15 25 4
gpt4 key购买 nike

我的 S3 存储桶文件夹中有一堆图像。

我有来自 S3 ( img_list ) 的 key 列表,我可以读取和显示图像:

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 读取图像,但出现错误:
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

请建议如何以正确的方式阅读它?

最佳答案

对不起,我在评论中弄错了。此代码在内存缓冲区中设置一个 PNG 文件来模拟您从 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.x - 如何使用 Python 3 从 S3 获得的 OpenCV 读取图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61461753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com