【问题标题】:Average of multiple stacks多个堆栈的平均值
【发布时间】:2020-06-30 22:38:12
【问题描述】:
如何一次平均多个堆栈?理想情况下使用 ImageJ 之类的 GUI 工具?我想在大约 10-20 个堆栈的集合上执行此操作:1500x1500 像素,500 个切片,每个堆栈中有 1 个通道。一次加载所有这些将推动我的 RAM 的极限。
作为输出,我想要一个堆栈(1500x1500 像素,500 个切片,1 个通道),其强度平均分布在不同堆栈中。
ImageJ 似乎仅限于一次平均 2 个堆栈。
我希望所有堆栈的最终平均权重相同。
【问题讨论】:
标签:
image-processing
imagej
【解决方案1】:
最好使用像 imageJ 这样的 GUI 工具?
关于 ImageJ 的使用且与任何代码段无关的问题在 stackoverflow.com 上是题外话,最好在 ImageJ forum 上提问。
如何一次平均多个堆栈?
在 ImageJ 中,您可以从堆栈构建 hyperstack(例如,使用 Image > Stacks > Tools > Concatenate... 然后 Image > Hyperstacks > Stack to Hyperstack...)并随后创建平均投影(Image > Stacks > Z Project...)。
为了完成您的任务,您应该将每个堆栈的 500 个切片分配给 t 维度,并且要平均的维度应该是 z。
希望对您有所帮助。
【解决方案2】:
我有太多堆栈,无法将它们全部组合成一个大型超堆栈。我的内存快用完了。
我最终改用 python:
import tkFileDialog
import os
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import glob
from tifffile import imsave
#select a directory containing tif-stacks to process
#tif-stacks must have equal dimensions
sd=tkFileDialog.askdirectory()
#list of files to process
fl= glob.glob(os.path.join(sd,'*.tif'))
#number of files to process
n_files=np.shape(fl)[0]
im = Image.open(fl[0])
#get number of frames in first file by seeking all frames until error occurs
#this seems clunky but is very fast
#assuming same number of frames for all files
n = 0
while True:
n += 1
try:
im.seek(n)
except:
break
n_frames=n
#loop through all images,
#read each frame and accumulate frame-wise sum over all stacks
w, h = im.size
temp = np.zeros( (h,w,n_frames), dtype=np.int32 )
for i in range(n_files):
print 'processing file: ', i
im = Image.open(fl[i])
for n in range (n_frames):
curframe = np.array(im.getdata()).reshape(h,w)
temp[:,:,n] += curframe
im.seek(n)
print ['frame: ', n]," \r",
avgStack=temp/n_files
【解决方案3】:
我稍微修改了上面的 jlarsch 的代码,因为它没有在 python3 中运行。这是我的解决方案:
from tkinter import filedialog
import os
from PIL import Image
import numpy as np
import glob
from tifffile import imwrite, imread
#select a directory containing tif-stacks to process
#tif-stacks must have equal dimensions
sd=filedialog.askdirectory()
fl = glob.glob(os.path.join(sd, '*.tif'))
#list of files to process
fl= glob.glob(os.path.join(sd,'*.tif'))
#number of files to process
n_files=np.shape(fl)[0]
#get number of frames in first file by seeking all frames until error occurs
#this seems clunky but is very fast
#assuming same number of frames for all files
with Image.open(fl[0]) as im:
h,w=im.size
n = 0
while True:
n += 1
try:
im.seek(n)
except:
break
n_frames = n
#loop through all images,
#read each stack and append to a 4-dimensional numpy array
w, h = im.size
temp = np.empty((0,n_frames,h,w), dtype=np.int32)
for i in range(n_files):
stack = imread(fl[i])
temp = np.append(temp, stack[np.newaxis, :], axis=0)
#average over all stacks
average=np.mean(temp,axis=0)
imwrite('average.tif', average)