将多页 tiff 文件转换为 hdf5

问题描述 投票:0回答:2

我想询问有关将多页 tiff 转换为 h5 文件的问题。 我可以从图像中获取 2-d 数据数组,但我有 21GB 多页 tiff 容器,因此我需要将图像转换为 3-d 数据形状。然后,我想将这些数据放入 hdf 数据集。

下面是我的代码。请帮助我成功完成此操作。

import numpy as np
import numpy as np
import h5py
import tifffile
with tifffile.TiffFile('tomo.tif') as tif:
    num_frames = len(tif.pages)
    for n in range(num_frames):
        im = tif.pages[n].asarray()
        frame_shape = tif.pages[n].asarray().shape
        dtype = tif.pages[n].asarray().dtype
    with h5py.File('test.h5', 'w') as f:
        f.create_dataset('temp', data=im, shape=(n, *frame_shape))
    
print("array is of type:", type(im))
print("No. of dimensions", im.ndim)
print("Shape of array:", im.shape)
print("Size of array", im.size)
print("array stores elements of type", im.dtype)
print(im)
 -----------console message----------------
array is of type: <class 'numpy.ndarray'>
No. of dimensions 2
Shape of array: (2160, 2560)
Size of array 5529600
array stores elements of type uint16
[[1330 1380 1361 ... 1476 1606 1598]
 [1389 1440 1416 ... 1535 1549 1606]
 [1248 1367 1401 ... 1691 1525 1318]
 ...
 [1320 1379 1420 ... 1364 1585 1683]
 [1437 1387 1376 ... 1577 1563 1566]
 [1215 1326 1492 ... 1549 1626 1514]]

raise ValueError("Shape tuple is incompatible with data")
ValueError: Shape tuple is incompatible with data
python numpy shapes hdf5 tiff
2个回答
0
投票

假设 TIFF 文件中的所有页面都包含相同形状和数据类型的图像,创建一个空的 HDF5 数据集并将所有图像从 TIFF 复制到该数据集:

import h5py
import tifffile

with tifffile.TiffFile('tomo.tif') as tif:
    with h5py.File('test.h5', 'w') as f:
        dset = f.create_dataset(
            'temp', (len(tif.pages), *tif.pages[0].shape), tif.pages[0].dtype
        )
        for i, page in enumerate(tif.pages):
            dset[i] = page.asarray()

0
投票

我使用了下面的代码......它有效,但出现了一个问题。图像文件是2000帧21602560数据形状。然而,生成的数据集是 2560 帧,20002160 数据形状。我尝试了很多方法来纠正这个问题,例如转置函数或其他函数,但它不起作用。有没有办法获得正确的数据集?

import h5py
import tifffile

with tifffile.TiffFile('tomo.tif') as tif:
    with h5py.File('test.h5', 'w') as f:
        num_pages = len(tif.pages)
        height, width = tif.pages[0].shape
        dset = f.create_dataset(
            'temp', shape=(num_pages, height, width), dtype=tif.pages[0].dtype
            )
    for i, page in enumerate(tif.pages):
        dset[i] = page.asarray()
© www.soinside.com 2019 - 2024. All rights reserved.