张量流中的张量切片

时间:2021-02-17 17:47:09

标签: tensorflow keras tensor

我想做如下相同的numpy操作来制作自定义图层

img=cv2.imread('img.jpg') # img.shape =>(600,600,3)

mask=np.random.randint(0,2,size=img.shape[:2],dtype='bool')

img2=np.expand_dims(img,axis=0) #img.shape => (1,600,600,3)

img2[:,mask,:].shape # =>  (1, 204030, 3)

这是我第一次尝试,但我失败了。我不能对张量流张量做同样的操作

class Sampling_layer(keras.layers.Layer):

    def __init__(self,sampling_matrix):
        super(Sampling_layer,self).__init__()
        self.sampling_matrix=sampling_matrix

    def call(self,input_img):
        return input_img[:,self.sampling_matrix,:]        

更多解释:

我想定义一个 keras 层,以便给定一批图像,它使用一个采样矩阵,并为我提供一批图像的采样向量。采样矩阵是一个与图像大小相同的随机布尔矩阵。我使用的切片操作对于 numpy 数组来说是直接的,并且工作得很好。但我无法用张量流中的张量完成它。我尝试使用循环来手动执行我想要的操作,但我失败了。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作。

import numpy as np
import tensorflow as tf

# Batch of images
img=np.random.normal(size=[2,600,600,3]) # img.shape =>(600,600,3)

# You'll need to match the first 3 dimensions of mask with the img
# for that we'll repeat the first axis twice
mask=np.random.randint(0,2,size=img.shape[1:3],dtype='bool')
mask = np.repeat(np.expand_dims(mask, axis=0), 2, axis=0)

# Defining input layers
inp1 = tf.keras.layers.Input(shape=(600,600,3))
mask_inp = tf.keras.layers.Input(shape=(600,600))

# The layer you're looking for
out = tf.keras.layers.Lambda(lambda x: tf.boolean_mask(x[0], x[1]) )([inp1, mask])

model = tf.keras.models.Model([inp1, mask_inp], out)

# Predict on sample data
toy_out = model.predict([img, mask])

请注意,您的图像和蒙版都需要具有相同的批次大小。如果不重复批处理轴上的掩码以匹配图像的批处理大小,我就找不到解决方案来完成这项工作。这是我想到的唯一可能的解决方案(假设您的掩码因每批数据而变化)。