IIUC, you should be able to simply use tf.reshape to reconstruct the original images from batches of patches:
import tensorflow as tf
samples = 5
images = tf.random.normal((samples, 256, 256, 3))
@tf.function
def grid(images):
img_shape = tf.shape(images)
batch_size, height, width, n_filters = img_shape[0], img_shape[1], img_shape[2], img_shape[3]
patches = tf.image.extract_patches(images=images,
sizes=[1, 32, 32, 1],
strides=[1, 32, 32, 1],
rates=[1, 1, 1, 1],
padding='VALID')
return tf.reshape(tf.nn.softmax(patches), (batch_size, height, width, n_filters))
patches = grid(images)
print(patches.shape)
# (5, 256, 256, 3)
Update 1:
If you want to reconstruct the images in the correct order, you can calculate the gradients of tf.image.extract_patches as shown in this code snippet. Here is an example:
import tensorflow as tf
import matplotlib.pyplot as plt
import pathlib
@tf.function
def grid(images):
img_shape = tf.shape(images)
patches = tf.image.extract_patches(images=images,
sizes=[1, 64, 64, 1],
strides=[1, 64, 64, 1],
rates=[1, 1, 1, 1],
padding='VALID')
return patches
@tf.function
def extract_patches_inverse(shape, patches):
_x = tf.zeros(shape)
_y = grid(_x)
grad = tf.gradients(_y, _x)[0]
return tf.gradients(_y, _x, grad_ys=patches)[0] / grad
dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
data_dir,
seed=123,
image_size=(512, 512),
batch_size = batch_size,
shuffle= False)
images, _ = next(iter(train_ds.skip(1).take(2)))
patches = grid(images)
shape = (batch_size, 512, 512, 3)
images_reconstructed = extract_patches_inverse(shape, patches)
plt.figure()
f, axarr = plt.subplots(1,2)
axarr[0].imshow(images[0]/ 255)
axarr[1].imshow(images_reconstructed[0] / 255)
