簡體   English   中英

在 python 中重新排列 3D 陣列

[英]Rearrange 3D array in python

我有大的二進制 3D 數據,我想重新排列數據,例如它是一個值序列,以便通過將原始數據解析為大小(4x4x4)的子數組來實現。

例如,如果數據是 2D 並且我想重新排列 2x2 子數組示例圖像中的數據

我為此使用了簡單的循環,但只是迭代循環需要更多時間,我正在嘗試使用一些 numpy 函數來這樣做,但我是 SciPy 的新手 我的代碼看起來像這樣

x,y,z = 1200,800,400
data = np.fromfile(file_name, dtype=np.float32)
data.shape = (z,y,x)
new_data = np.empty(shape=x*y*z, dtype = np.float32)
index = 0
for zz in range(0,z,4):
    for yy in range(0,y,4):
        for xx in range(0,x,4):
            for zShift in range(4):
                for yShift in range(4):
                    for xShift in range(4):
                        new_data[index] = data[zz+zShift][yy+yShift][xx+xShift]
                        index+=1
new_data.tofile(output)

但是,這需要很多時間,有更好的實現思路嗎? 正如我所說,代碼按預期工作,但是,我需要一種更智能、pythonic 的方式來實現我的 output

謝謝!

x,y,z = 1200,800,400
data = np.empty([x,y,z])

# numpy calculates the shape of -1
out = data.reshape(-1, 4, 4, 4)
out.shape
>>> (6000000, 4, 4, 4)

對於較小的數據和塊大小,請執行以下測試:

x, y, z = 4, 4, 4    # Dimensions
stp = 2              # Block size (in each dimension)

# Create the test array
arr = np.arange(x * y * z).reshape((x, y, z))

並創建一個“塊”列表,運行:

new_data = []
for xx in range(0, x, stp):
    for yy in range(0, y, stp):
        for zz in range(0, z, stp):
            print('Index:', xx, yy, zz)
            obj = arr[xx:xx+stp, yy:yy+stp, zz:zz+stp].copy()
            print(obj)
            new_data.append(obj)

在代碼的目標版本中:

  • 恢復xyz的原始值,
  • 從您的源中讀取數組,
  • stp改回4
  • 跌落測試打印輸出。

另請注意,您的代碼將單個元素添加到new_data ,僅迭代大小為4 * 4 * 4的塊,而您寫道,您想要一系列較小的 arrays (即切片),大小為4 * 4 * 4 ,我的代碼做了什么.

因此,如果您需要切片列表(較小的數組),而不是單個4-D數組,請使用我的代碼。

暫無
暫無

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

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