[英]How to create a new ndarray after performing a calculation on a slice
我有一個4d的numpy數組,我想對它的幾個切片執行計算,然后創建一個包含所有值的新數組。主要問題是我對3個維度有固定的切片,但是對第四軸有幾個范圍,請按第4軸的范圍進行切片
盡管我認為這里已經有幾個類似的問題( numpy 4d slice
結果為38),但這是我嘗試以直觀的方式對此進行解釋。 首先,我從Giphy下載了.gif
文件,並將其轉換為示例的多維np.array()
; 它的尺寸為200x200px,具有3個顏色通道,6個幀,因此形狀為(6, 200, 200, 3)
6,200,200,3 (6, 200, 200, 3)
。
在圖的第一行中,我分別顯示每個顏色通道以及索引為1
的幀的總和(請注意,此處忽略了cmap
關鍵字)。
接下來,我創建綠色通道的特定切片(顏色索引1
),其在y方向上從50-150px,在x方向上從100-120px,如下所示: my_slice= frames[frame_index,50:150,100:120,1]
-它的形狀為(100, 20)
。 我將其乘以0.1,然后將結果插入原始位置。
現在第二個圖像行顯示了我如何減少該區域的綠色通道,從而在整個圖像中產生了總體粉紅色調。
現在,如果您想在例如幀[0,4,5]
上執行此操作,則for frame_index in [0,4,5]:
循環中的for frame_index in [0,4,5]:
來說很簡單。 希望這可以幫助。
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageSequence
## downloaded from here:
# https://media.giphy.com/media/uQCxA7u9CEdIA/200w_d.gif
img = Image.open("/path/to/Downloads/brainscan.gif")
frames = np.array([np.array(frame.copy().convert('RGB').getdata(),dtype=np.uint8).reshape(frame.size[1],frame.size[0],3) for frame in ImageSequence.Iterator(img)])
print(np.shape(frames))
frame_index=1
fig,axes=plt.subplots(2,4,figsize=(10,4))
axes[0,0].imshow(frames[frame_index,:,:,0],cmap="Reds_r")
axes[0,1].imshow(frames[frame_index,:,:,1],cmap="Greens_r")
axes[0,2].imshow(frames[frame_index,:,:,2],cmap="Blues_r")
axes[0,3].imshow(frames[frame_index,:,:,:],cmap="viridis")
my_slice= frames[frame_index,50:150,100:120,1]
print(np.shape(my_slice[:]))
frames[frame_index,50:150,100:120,1]=0.1*my_slice
axes[1,0].imshow(frames[frame_index,:,:,0],cmap="Reds_r")
axes[1,1].imshow(frames[frame_index,:,:,1],cmap="Greens_r")
axes[1,2].imshow(frames[frame_index,:,:,2],cmap="Blues_r")
axes[1,3].imshow(frames[frame_index,:,:,:],cmap="viridis")
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.