我正在處理尺寸為(128x128x128)的 3D 影像(300)。我想提取影像區域(去除背景),進行一些轉換,然后將轉換后的部分插回原始影像上。我怎樣才能在python中做到這一點?
這是我嘗試過的:
我創建了一個具有形狀的面具(128, 128, 128)。然后我得到了np.sum那個掩碼 n_voxels_flattened = np.sum(mask)(洗掉了零體素,以便我可以對非零體素進行轉換),現在n_voxels_flattened=962517. 然后遍歷所有影像(300 張影像),得到一個形狀為 的陣列(962517, 300)。我對這個陣列做了一些調整,輸出與輸入具有相同的形狀:(962517, 300). 我現在想重塑這個陣列并放回我洗掉的零體素,使其具有形狀(128,128,128,300)。
這是我嘗試過的,但是在可視化時會導致看起來很奇怪的影像。
zero_array = np.zeros((128*128*128 * 300))
zero_array[:len(result.reshape(-1))]=result.reshape(-1)
有人可以幫我嗎?
uj5u.com熱心網友回復:
好的,如果我正確閱讀了您的問題,您想對f所有不是背景像素的體素 ( 0) 應用一些函式嗎?
在這種情況下,您可以使用 in 中的np.where函式來執行此操作numpy,但我將提供一個更長的示例,它也可以執行相同的操作。
np.where有兩種模式。當您指定可選的第二個和第三個引數時,它將第二個引數中的所有值插入到條件為 的新陣列中True,并將第三個引數中的值插入條件為 的新陣列中False。
使用示例np.where
import numpy as np
# I used 3 to test because your original array is quite large,
# but you can change this back to (128, 128, 128, 300).
# I would suggest you iterate over this instead of having such a large
# single array object.
shape = (128,128,128,3)
# Computing some random data to try and emulate your situation
voxels = np.random.randint(low=0, high=10, size=shape)
# I'm going to use np.power(x, 2) as my transformation function
# because I don't know what you're doing with the voxels
# so you can just replace this with your actual transformation function.
output_voxels = np.where(voxels != 0, np.power(voxels, 2), voxels)
print(output_voxels.shape)
# (128, 128, 128, 3)
這導致了一個新的陣列,其中所有沒有0被提升到 2 次方的體素,以及所有0填充了它們的原始值的體素0。
直接使用陣列掩碼的更長示例。
import numpy as np
shape = (128,128,128,3)
voxels = np.random.randint(low=0, high=10, size=shape)
# Index the array to find all the data which is not equal to 0.
# Here we are using an inverse (~) mask so it has to be in brackets,
# Alternatively you could use voxels[voxels != 0]
valid_voxels = voxels[~(voxels == 0)]
# Simple transformation function to emulate your situation.
transformed_valid_voxels = np.power(valid_voxels, 2)
# Define a new array in the same shape as the input data.
output_voxels = np.zeros(shape=shape)
# Assign the new pixels to the output where the mask is applied.
output_voxels[~(voxels == 0)] = transformed_valid_voxels
print(output_voxels.shape)
# (128, 128, 128, 3)
希望我正確閱讀了這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497816.html
