user19676560
user19676560

Reputation:

How to stack tensors (from images) to train a CNN?

I have converted images to tensors. How should I stack them to train for a Convolutional Neural Network in keras.

mask_tensor = tf.Variable([])
for img in mask_img:
    image = tf.io.read_file(img)
    tensor = tf.io.decode_jpeg(image, channels=3)
    tensor = tf.image.resize(tensor, [128,128])
    if mask_tensor.shape == 0:
        mask_tensor = tf.stack([tensor])
    else:
        tf.reshape(tensor, [1,128,128,3])
        mask_tensor = tf.stack([mask_tensor, tensor])



InvalidArgumentError: Input to reshape is a tensor with 49152 values, but the requested shape has 98304 [Op:Reshape]

Upvotes: 1

Views: 180

Answers (2)

user19676560
user19676560

Reputation:

Using tf.data.Dataset.from_tensor_slices as said in comment above

filenames = tf.constant(["img1.jpg", ...])
labels = tf.constant([1, ...])

dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))

def _parse_function(filename, label):
    image_string = tf.read_file(filename)
    tensor = tf.image.decode_jpeg(image_string, channels=3)
    tensor = tf.image.resize(tensor, [128,128])
    image = tf.cast(tensor, tf.float32)/255.
    return image, label

dataset = dataset.map(_parse_function).batch(32)

Upvotes: 0

AloneTogether
AloneTogether

Reputation: 26708

If your tensors are based on this, try :

mask_tensor = tf.TensorArray(dtype=tf.float32, size=0, dynamic_size=True)
for img in mask_img:
    image = tf.io.read_file(img)
    tensor = tf.io.decode_jpeg(image, channels=3)
    tensor = tf.image.resize(tensor, [128,128])
    mask_tensor = mask_tensor.write(mask_tensor.size(), tensor)
images = mask_tensor.stack()
images.shape

Upvotes: 0

Related Questions