我有一個大小為 55 x 10 x 10 的 numpy 陣列,它代表 55 個 10 x 10 灰度影像。我試圖通過將 10 x 10 影像復制 3 次來使它們成為 RGB。
據我所知,我首先需要添加一個新維度來容納重復的資料。我已經這樣做了:
array_4d = np.expand_dims(array_3d, 1),
所以我現在有一個 55 x 1 x 10 x 10 的陣列。我現在如何復制 10 x 10 影像并將它們添加回此陣列?
快速編輯:最后我想要一個 55 x 3 x 10 x 10 的陣列
uj5u.com熱心網友回復:
讓我們首先創建一個大小為 55x10x10 的 3d 陣列
from matplotlib import pyplot as plt
import numpy as np
original_array = np.random.randint(10,255, (55,10,10))
print(original_array.shape)
>>>(55, 10, 10)
陣列中第一張影像的視覺效果:
first_img = original_array[0,:,:]
print(first_img.shape)
plt.imshow(first_img, cmap='gray')
>>>(10, 10)

現在,您只需一步即可獲得所需的陣列。
stacked_img = np.stack(3*(original_array,), axis=1)
print(stacked_img.shape)
>>>(55, 3, 10, 10)
axis=-1如果您希望頻道最后使用,請使用
現在讓我們通過從該陣列中提取第一張影像并取 3 個通道的平均值來驗證該值是否正確:
new_img = stacked_img[0,:,:,:]
print(new_img.shape)
>>> (3, 10, 10)
new_img_mean = new_img.mean(axis=0)
print(new_img_mean.shape)
>>> (10, 10)
np.allclose(new_img_mean, first_img) # If this is True then the two arrays are same
>>> True
對于視覺驗證,您必須將通道移到最后,因為這是matplotlib需要的。這是一個 3 通道影像,所以我們沒有cmap='gray'在這里使用
print(np.moveaxis(new_img, 0, -1).shape)
plt.imshow(np.moveaxis(new_img, 0, -1))
>>> (10, 10, 3)

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361256.html
上一篇:為什么我可以在一種情況下為陣列賦值,而在另一種情況下不能?
下一篇:帶有大串列的更快搜索協議(c )
