我有许多 tiff 文件,我想使用 python 将它们合并到一个 z-stack 中。各个文件都有我想保存的元数据(在我的例子中是 OME),特别是关于它是哪个 z 切片的信息。或者,我想在 z-stack 的元数据中的某处插入它是一个 z-stack(而不是例如延时。我需要它来使用 ImageJ 中的 Bioformats 正确打开堆栈)。
我可以使用例如tifffile.py ,像这个简单的例子一样读取单个文件:
img1 = tifffile.imread(path_to_img1)
img2 = tifffile.imread(path_to_img2)
zstack = np.zeros((2, img1.shape[0], img1.shape[1]))
zstack[0] = img1
zstack[1] = img2
tifffile.imsave(path, zstack)
我还可以使用 tifffile.TiffFile
读取各个元数据信息。
但是,我看不到如何为每个切片附加元数据。 Tifffile 有一个选项可以添加额外的标签(包括标签 ID 270,图像描述),但我不明白如何将其应用于每个单独的切片。另一方面,tifffile.TiffFile 对象没有写入方法。
我不限于tifffile,也尝试过使用PIL,但没有成功。
最佳答案
试试这个:
import numpy as np
import bioformats.omexml as ome
import tifffile
import sys
def writeplanes(pixel, SizeT=1, SizeZ=1, SizeC=1, order='TZCYX', verbose=False):
if order == 'TZCYX':
p.DimensionOrder = ome.DO_XYCZT
counter = 0
for t in range(SizeT):
for z in range(SizeZ):
for c in range(SizeC):
if verbose:
print('Write PlaneTable: ', t, z, c),
sys.stdout.flush()
pixel.Plane(counter).TheT = t
pixel.Plane(counter).TheZ = z
pixel.Plane(counter).TheC = c
counter = counter + 1
return pixel
# Dimension TZCXY
SizeT = 1
SizeZ = n_zs
SizeC = n_chs
SizeX = 2048
SizeY = 2048
Series = 0
scalex = 0.1
scaley = scalex
scalez = 0.5
pixeltype = 'uint16'
dimorder = 'TZCYX'
output_file = os.path.join(out_dir, 'R{}'.format(i), file)
# create numpy array with correct order
img5d = np.random.randn(SizeT, SizeZ, SizeC, SizeY, SizeX).astype(np.uint16)
# Getting metadata info
omexml = ome.OMEXML()
omexml.image(Series).Name = output_file
p = omexml.image(Series).Pixels
#p.ID = 0
p.SizeX = SizeX
p.SizeY = SizeY
p.SizeC = SizeC
p.SizeT = SizeT
p.SizeZ = SizeZ
p.PhysicalSizeX = np.float(scalex)
p.PhysicalSizeY = np.float(scaley)
p.PhysicalSizeZ = np.float(scalez)
p.PixelType = pixeltype
p.channel_count = SizeC
p.plane_count = SizeZ * SizeT * SizeC
p = writeplanes(p, SizeT=SizeT, SizeZ=SizeZ, SizeC=SizeC, order=dimorder)
for c in range(SizeC):
if pixeltype == 'unit8':
p.Channel(c).SamplesPerPixel = 1
if pixeltype == 'unit16':
p.Channel(c).SamplesPerPixel = 2
omexml.structured_annotations.add_original_metadata(ome.OM_SAMPLES_PER_PIXEL, str(SizeC))
# Converting to omexml
xml = omexml.to_xml()
# write file and save OME-XML as description
tifffile.imwrite(output_file, img5d, metadata={'axes': dimorder}, description=xml)
关于python - 如何使 tiff z-stack 保存或添加元数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978698/