[英]Extract patches from list of images using tensorflow
这是列表中两个图像的示例。 为每个图像提取图像块,最终结果是每个图像有 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.