tensorflow - 使用种子预处理层不会为图像和蒙版产生相同的数据增强

标签 tensorflow data-augmentation data-preprocessing image-masking

我正在尝试创建一个简单的预处理增强层,遵循这个 Tensorflow tutorial 。我创建了这个“简单”示例来显示我遇到的问题。

即使我使用种子初始化增强类,应用于图像的操作以及相应的蒙版并不总是相等。

我做错了什么?

注意:tf v2.10.0

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import skimage
import rasterio as rio

def normalize(array: np.ndarray):
    """ normalise image to give a meaningful output """
    array_min, array_max = array.min(), array.max()
    return (array - array_min) / (array_max - array_min)

# field
im = rio.open('penguins.tif')
fields = np.zeros((1,im.shape[0],im.shape[1],3))
fields[0,:,:,0] = normalize(im.read(1))
fields[0,:,:,1] = normalize(im.read(2))
fields[0,:,:,2] = normalize(im.read(3))

# mask is a simple contour
masks = skimage.color.rgb2gray(skimage.filters.sobel(fields[0]))
masks = np.expand_dims(masks, [0,3])

在这种情况下,数据集只有一张图像,我们可以使用此函数来可视化字段和掩模。

def show(field:np.ndarray, mask:np.ndarray): 
    """Show the field and corresponding mask."""
    fig = plt.figure(figsize=(8,6))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    ax1.imshow(field[:,:,:3])
    ax2.imshow(mask,cmap='binary')    
    plt.tight_layout()
    plt.show()

show(fields[0], masks[0])

image and field

好吧,现在我使用 tutorial 中的示例这将随机翻转(水平)图像和蒙版。

class Augment(tf.keras.layers.Layer):
    def __init__(self, seed=42):
        super().__init__()
        # both use the same seed, so they'll make the same random changes.
        self.augment_inputs = tf.keras.layers.RandomFlip(mode="horizontal", seed=seed)
        self.augment_labels = tf.keras.layers.RandomFlip(mode="horizontal", seed=seed)

    def call(self, inputs, labels):
        inputs = self.augment_inputs(inputs)
        labels = self.augment_labels(labels)
        return inputs, labels

现在,如果我多次运行以下命令,我最终会在字段和蒙版上得到相反的翻转。

# Create a tf.datasets
ds = tf.data.Dataset.from_tensor_slices((fields, masks))

ds2 = ds.map(Augment())

for f,m in ds2.take(1):
    show(f, m)

different processing to image and mask

我希望图像及其蒙版以相同的方式翻转,因为我按照 Tensorflow 教程中的建议在 Augment 类中设置了种子。

最佳答案

可以对沿着 channel 轴连接的imagemask进行增强以形成单个数组,然后恢复imagelabel返回,如下所示:

class Augment(tf.keras.layers.Layer):
    def __init__(self):
        super().__init__()
        # both use the same seed, so they'll make the same random changes.
        self.augment_inputs = tf.keras.layers.RandomRotation(0.3)


    def call(self, inputs, labels):
        
        output = self.augment_inputs(tf.concat([inputs, labels], -1) )
        
        inputs = output[:,:,0:4]
        labels = output[:,:,4:]

        return inputs, labels

关于tensorflow - 使用种子预处理层不会为图像和蒙版产生相同的数据增强,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74764831/

相关文章:

python - 从 Image Generator 绘制图像

machine-learning - 使用 mlr3pipeline 编码和缩放后无法通过 mlr3proba 训练数据集

python-3.x - 如何使用 Openpyxl 访问 Onedrive 上的 Excel 文件

python - 如何将所有 tf​​.data.Dataset 对象提取到特征和标签中并传递给 ImageDataGenerator 的 flow() 方法?

python - 如何用特征的中值填充极坐标数据框中存在的特征的空值?

dataframe - 神经网络摘要到数据框

python - tensorflow 稀疏算法

python - ImportError : Imageio Pillow requires Pillow, 不是 PIL!在 M1 Mac 上

python-3.x - 类型错误 : Fetch argument None has invalid type <class 'NoneType' > in Tensorflow

python - 如何用折痕,褶皱和皱纹来放大扫描的文档图像?