简体   繁体   English

如果图像是 tif float32,如何将图块读入张量?

[英]How to read the tiles into the tensor if the images are tif float32?

I am trying to run a CNN where the input images have three channels (rgb) and the label (target) images are grayscale images (1 channel).我正在尝试运行一个 CNN,其中输入图像具有三个通道(rgb),并且 label(目标)图像是灰度图像(1 个通道)。 The input and label images are in float32 and tif format.输入和 label 图像采用 float32 和 tif 格式。

I got the list of image and label tile pairs as below:我得到了图像和 label 瓦片对的列表,如下所示:

def get_train_test_lists(imdir, lbldir):
    imgs = glob.glob(imdir+"/*.tif")
    dset_list = []
    for img in imgs:
        filename_split = os.path.splitext(img) 
        filename_zero, fileext = filename_split 
        basename = os.path.basename(filename_zero) 
        dset_list.append(basename)
    
    x_filenames = []
    y_filenames = []
    for img_id in dset_list:
        x_filenames.append(os.path.join(imdir, "{}.tif".format(img_id)))
        y_filenames.append(os.path.join(lbldir, "{}.tif".format(img_id)))
    
    print("number of images: ", len(dset_list))
    return dset_list, x_filenames, y_filenames

train_list, x_train_filenames, y_train_filenames = get_train_test_lists(img_dir, label_dir)
test_list, x_test_filenames, y_test_filenames = get_train_test_lists(test_img_dir, test_label_dir)

from sklearn.model_selection import train_test_split
x_train_filenames, x_val_filenames, y_train_filenames, y_val_filenames = 
train_test_split(x_train_filenames, y_train_filenames, test_size=0.1, random_state=42)

num_train_examples = len(x_train_filenames)
num_val_examples = len(x_val_filenames)
num_test_examples = len(x_test_filenames)

In order to read the tiles into tensor, firstly I defined the image dimensions and batch size:为了将瓦片读入张量,首先我定义了图像尺寸和批量大小:

img_shape = (128, 128, 3)
batch_size = 2

I noticed that there is no decoder in tensorflow for tif image based on this link .我注意到基于 此链接的 tif 图像在 tensorflow 中没有解码器。 tfio.experimental.image.decode_tiff can be used but it decodes to unit8 tensor . tfio.experimental.image.decode_tiff可以使用,但它会解码为 unit8 张量

here is a sample code for png images :这是png 图像的示例代码:

def _process_pathnames(fname, label_path):
  # We map this function onto each pathname pair  
  img_str = tf.io.read_file(fname)
  img = tf.image.decode_png(img_str, channels=3)

  label_img_str = tf.io.read_file(label_path)

  # These are png images so they return as (num_frames, h, w, c)
  label_img = tf.image.decode_png(label_img_str, channels=1)
  # The label image should have any values between 0 and 9, indicating pixel wise
  # cropt type class or background (0). We take the first channel only. 
  label_img = label_img[:, :, 0]
  label_img = tf.expand_dims(label_img, axis=-1)
  return img, label_img

Is it possible to modify this code by tf.convert_to_tensor or any other option to get float32 tensor from tif images?是否可以通过tf.convert_to_tensor或任何其他选项修改此代码以从 tif 图像中获取 float32 张量? (I asked this question before, but I don't know how to integrate tf.convert_to_tensor with the mentioned codes) (我之前问过这个问题,但我不知道如何将tf.convert_to_tensor与上述代码集成)

You can read almost any image format and convert it to a numpy array with the Pillow image package:您可以读取几乎任何图像格式并将其转换为带有枕头图像 package 的 numpy 数组:

from PIL import Image
import numpy as np

img = Image.open("image.tiff")
img = np.array(img)

print(img.shape, img.dtype)
# (986, 1853, 4) uint8

You can integrate this function into your code and then convert the numpy array to a tensorflow tensor as well as doing the appropriated image conversions.您可以将此 function 集成到您的代码中,然后将 numpy 数组转换为 tensorflow 张量以及进行适当的图像转换。


Side note: you can simplify a lot your get_train_test_lists function using the pathlib package (which is integrated to Python3 like os but much simpler to use).旁注:您可以使用pathlib package (它像os一样集成到 Python3,但使用起来更简单)简化了很多get_train_test_lists function。

def get_train_test_lists(imdir, lbldir):
    x_filenames = list(Path(imdir).glob("*.tif"))
    y_filenames = [Path(lbldir) / f.name for f in x_filenames]
    dset_list = [f.stem for f in x_filenames]
    return dset_list, x_filenames, y_filenames

Note that x_filenames and y_filenames are now absolute paths but this shouldn't be an issue in your code.请注意, x_filenamesy_filenames现在是绝对路径,但这在您的代码中应该不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在tensoflow中将float32 tif图像解码为float32张量? - How to decode float32 tif images to float32 tensor in tensoflow? 如何将int32张量转换为float32 - How to cast int32 tensor to float32 如何对 float32 类型的张量应用“或”运算? - how to apply “or” operation to tensor with float32 type? Tensorflow将uint8张量视为float32张量 - Tensorflow viewing a uint8 tensor as a float32 tensor TensorFlow:将float64张量强制转换为float32 - TensorFlow: cast a float64 tensor to float32 TF 2.0:如何将 Tensor("mul_1:0", shape=(1000, 64), dtype=float32) 转换为 Numpy 数组 - TF 2.0: How to convert Tensor("mul_1:0", shape=(1000, 64), dtype=float32) to Numpy array ValueError: Tensor("ExponentialDecay_4:0", shape=(), dtype=float32) - ValueError: Tensor("ExponentialDecay_4:0", shape=(), dtype=float32) ValueError:张量转换为具有 dtype float32 的张量请求 dtype float32_ref - ValueError: Tensor conversion requested dtype float32_ref for Tensor with dtype float32 如何将 dtype= complex64 的 3D 张量转换为 tensorflow 中 dtype = float32 的 3D 张量 - How to convert a 3D tensor of dtype= complex64 to 3D tensor of dtype = float32 in tensorflow 如何强制 Pandas read_csv 对所有浮点列使用 float32? - How to force pandas read_csv to use float32 for all float columns?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM