我有一個形狀爲(466,394,1)
的image
,我想分割成7x7塊。將圖像張量分割成小塊
image = tf.placeholder(dtype=tf.float32, shape=[1, 466, 394, 1])
使用
image_patches = tf.extract_image_patches(image, [1, 7, 7, 1], [1, 7, 7, 1], [1, 1, 1, 1], 'VALID')
# shape (1, 66, 56, 49)
image_patches_reshaped = tf.reshape(image_patches, [-1, 7, 7, 1])
# shape (3696, 7, 7, 1)
遺憾的是在實踐中行不通爲image_patches_reshaped
拌和像素順序(如果你查看images_patches_reshaped
你只會看到噪聲)。
所以我的新方法是使用tf.split
:
image_hsplits = tf.split(1, 4, image_resized)
# [<tf.Tensor 'split_255:0' shape=(462, 7, 1) dtype=float32>,...]
image_patches = []
for split in image_hsplits:
image_patches.extend(tf.split(0, 66, split))
image_patches
# [<tf.Tensor 'split_317:0' shape=(7, 7, 1) dtype=float32>, ...]
這的確保留圖像像素順序遺憾的是它創造了很多的OP這是不是很不錯的。
如何將圖像分割成更小的補丁並使用更少的OP?
UPDATE1:
我移植了answer of this question for numpy到tensorflow:
def image_to_patches(image, image_height, image_width, patch_height, patch_width):
height = math.ceil(image_height/patch_height)*patch_height
width = math.ceil(image_width/patch_width)*patch_width
image_resized = tf.squeeze(tf.image.resize_image_with_crop_or_pad(image, height, width))
image_reshaped = tf.reshape(image_resized, [height // patch_height, patch_height, -1, patch_width])
image_transposed = tf.transpose(image_reshaped, [0, 2, 1, 3])
return tf.reshape(image_transposed, [-1, patch_height, patch_width, 1])
,但我認爲還是有改進的餘地。
UPDATE2:
這將轉換補丁回到原始圖像。
def patches_to_image(patches, image_height, image_width, patch_height, patch_width):
height = math.ceil(image_height/patch_height)*patch_height
width = math.ceil(image_width/patch_width)*patch_width
image_reshaped = tf.reshape(tf.squeeze(patches), [height // patch_height, width // patch_width, patch_height, patch_width])
image_transposed = tf.transpose(image_reshaped, [0, 2, 1, 3])
image_resized = tf.reshape(image_transposed, [height, width, 1])
return tf.image.resize_image_with_crop_or_pad(image_resized, image_height, image_width)
這是一個有趣的觀點!我會稍後再研究。在我的模型中,我認爲在重塑步驟中必然存在腐敗,因爲當我檢查「修補程序」時,他們看起來不正確,但我無法保證。 – bodokaiser
嘿,你是對的。現在只用原始數據進行測試。不知道之前出了什麼問題.. – bodokaiser