[英]How to convert ndarray of shape (h,w,c) to file-like object
I am trying to convert a ndarray
of shape (h,w,c)
to a file-like object with read operation.我正在尝试将形状(h,w,c)
的ndarray
转换为具有读取操作的类文件对象。
The idea is to have the file in memory and send it as a parameter to a AWS S3 bucket.这个想法是将文件保存在内存中并将其作为参数发送到 AWS S3 存储桶。
Here's an example of the code:下面是代码示例:
def arr_to_file(ndarray, key, bucket):
img = Image.fromarray(ndarray)
s3.upload_fileobj(
img, # The problem is here. Image does not implement a read method
bucket,
key
)
ndarray sample: ndarray 示例:
[[[135 114 177]
[123 131 174]
[111 138 179]
...
[130 111 170]
[139 127 155]
[144 124 143]]
[[125 133 182]
[119 133 182]
[104 148 182]
...
[129 118 165]
[142 116 160]
[145 112 155]]
[[125 151 186]
[115 145 187]
[ 96 154 185]
...
[105 125 160]
[123 109 163]
[117 127 161]]
...
[[ 97 124 127]
[113 119 129]
[124 111 141]
...
[ 74 110 85]
[ 63 94 96]
[ 65 85 105]]
[[116 102 124]
[116 128 117]
[119 115 154]
...
[ 82 80 95]
[ 85 89 95]
[ 85 89 97]]
[[113 131 116]
[107 155 108]
[114 130 151]
...
[ 88 39 102]
[105 75 98]
[100 91 97]]]
Any suggestions?有什么建议?
Edit (got this to work with ndarrays by changing save/load functions):编辑(通过更改保存/加载功能使其与 ndarrays 一起使用):
Numpy has a built in function to save and load to save .npy
files. Numpy 有一个内置函数来保存和加载以保存.npy
文件。 The following worked for me:以下对我有用:
>>> import numpy as np
>>> a = np.random.rand(2, 2, 2)
>>> np.save("test", a)
>>> g = np.load("test.npy")
Edit again:再次编辑:
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> x = np.arange(10)
>>> np.save(outfile, x)
>> #send outfile to S3 somehow...
>>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> f = np.load(outfile)
Figured it out, here's what I did:想通了,这就是我所做的:
img = Image.fromarray(ndarray)
img_obj = io.BytesIO()
img.save(img_obj, format="jpeg")
img_obj.seek(0)
This creates the img_obj
in memory which can be passed to the S3 Bucket.这会在内存中创建img_obj
,可以将其传递给 S3 Bucket。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.