使用张量流从图像列表中提取补丁

Extract patches from list of images using tensorflow

如果我们有图像列表,我们如何提取补丁。

示例:

def get_train_images():
    image_list = glob(FLAGS.train_path + '/*.jpg')
    #extract_patch

想做这样的事情: 例如,我只对 1 张图像执行此操作,但我想对 100 张图像执行相同的任务。

示例图片:

示例图像的输出图像:

我有一个图像列表,想从图像中提取补丁并将它们保存在另一个列表中。该列表可以被覆盖。

这是列表中两个图像的示例。为每个图像提取图像块,最终结果是每个图像有 4 个块的数组,因此 patched_images 的形状 (2, 4, 4, 3),其中 2 是样本数,4 是样本数每个图像的补丁,(4, 4, 3) 是每个补丁图像的形状。

import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

images = [tf.random.normal((16, 16, 3)), tf.random.normal((16, 16, 3))]

patched_images = []
for img in images:
  image = tf.expand_dims(np.array(img), 0)
  patches = tf.image.extract_patches(images=image,
                          sizes=[1, 4, 4, 1],
                          strides=[1, 4, 4, 1],
                          rates=[1, 1, 1, 1],
                          padding='VALID')
  patches = [tf.reshape(patches[0, i, i], (4, 4, 3)) for i in range(4)]
  patched_images.append(np.asarray(patches))

patched_images = np.asarray(patched_images)
print(patched_images.shape)

axes=[]
fig=plt.figure()
patched_image = patched_images[0] # plot patches of first image
for i in range(4):
    axes.append( fig.add_subplot(2, 2, i + 1) )
    subplot_title=("Patch "+str(i + 1))
    axes[-1].set_title(subplot_title)  
    plt.imshow(patched_image[i, :, :, :])
fig.tight_layout()    
plt.show()
(2, 4, 4, 4, 3)

如果您有不同的图像尺寸并且仍然想提取 4x4 的补丁而不考虑图像的尺寸,试试这个:

import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

images = [tf.random.normal((16, 16, 3)), tf.random.normal((24, 24, 3)), tf.random.normal((180, 180, 3))]

patched_images = []
for img in images:
  image = tf.expand_dims(np.array(img), 0)
  patches = tf.image.extract_patches(images=image,
                          sizes=[1, 4, 4, 1],
                          strides=[1, 4, 4, 1],
                          rates=[1, 1, 1, 1],
                          padding='VALID')
  patches = [tf.reshape(patches[0, i, i], (4, 4, 3)) for i in range(4)]
  patched_images.append(np.asarray(patches))