簡體   English   中英

如何將形狀 (h,w,c) 的 ndarray 轉換為類似文件的對象

[英]How to convert ndarray of shape (h,w,c) to file-like object

我正在嘗試將形狀(h,w,c)ndarray轉換為具有讀取操作的類文件對象。

這個想法是將文件保存在內存中並將其作為參數發送到 AWS S3 存儲桶。

下面是代碼示例:

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 示例:

[[[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]]]

有什么建議?

編輯(通過更改保存/加載功能使其與 ndarrays 一起使用):

Numpy 有一個內置函數來保存加載以保存.npy文件。 以下對我有用:

>>> import numpy as np
>>> a = np.random.rand(2, 2, 2)
>>> np.save("test", a)
>>> g = np.load("test.npy")

再次編輯:

>>> 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)

想通了,這就是我所做的:

img = Image.fromarray(ndarray)
img_obj = io.BytesIO()
img.save(img_obj, format="jpeg")
img_obj.seek(0)

這會在內存中創建img_obj ,可以將其傳遞給 S3 Bucket。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM