簡體   English   中英

TensorFlow 如何用邊緣值填充張量

[英]TensorFlow how to pad tensor with the edge values

如何使用邊緣值填充張量(尺寸為 WxHxC)?

例如:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

變成:

[1, 1, 2, 3, 3]
[1, 1, 2, 3, 3]
[4, 4, 5, 6, 6]
[7, 7, 8, 9, 9]
[7, 7, 8, 9, 9]

使用tf.pad()和模式“SYMMETRIC”——它會反映邊緣上的值,但如果你只做 1 個深度填充,它相當於重復邊緣值。 如果您需要更多填充,則必須重復該操作,但您可以按指數方式進行(首先是 1,然后是 2,然后是 4,等等)。 此代碼(已測試):

import tensorflow as tf

a = tf.reshape( tf.constant( range( 1, 10 ) ), ( 3, 3 ) )
b = tf.pad( a, [ [ 1, 1 ], [ 1, 1 ] ], "SYMMETRIC" )

with tf.Session() as sess:
    print( sess.run( b ) )

輸出:

[[1 1 2 3 3]
[1 1 2 3 3]
[4 4 5 6 6]
[7 7 8 9 9]
[7 7 8 9 9]]

如預期的。

作為補充,如果你想像opencv一樣用replication模式填充圖像,下面可以做到,dst_image是要填充的圖像。 而pad_h_up、pad_h_down、pad_w_left、pad_w_right,就​​是四個參數:

def pad_replica(image_pad, up,down, left, right):
    paddings_up = tf.constant([[1, 0],[0,0],[0,0]])
    paddings_down = tf.constant([[0, 1],[0,0],[0,0]])
    paddings_left = tf.constant([[0, 0],[1,0],[0,0]])
    paddings_right = tf.constant([[0, 0],[0, 1],[0 ,0]])
    i = tf.constant(0)
    c = lambda i,pad_len,pad_mode, image: tf.less(i, pad_len)
    def body(i,pad_len,pad_mode,image):
        i = i+1
        image = tf.pad(image, pad_mode,"SYMMETRIC")
        return [i, pad_len,pad_mode, image]
    [_, _, _, image_pad_up] = tf.while_loop(c, body, \
                                          [i, up, paddings_up, image_pad])
    i = tf.constant(0)
    [_, _, _, image_pad_down] = tf.while_loop(c, body, [i, down,paddings_down, image_pad_up])
    i = tf.constant(0)
    [_, _, _, image_pad_left] = tf.while_loop(c, body, [i, left, paddings_left, image_pad_down])
    i = tf.constant(0)
    [_, _, _, image_pad_right] = tf.while_loop(c, body, [i, right,paddings_right, image_pad_left])
    i = tf.constant(0)
    return image_pad_right
dst_image.set_shape([None, None, None])
dst_image = pad_replica(dst_image,\
             tf.cast(pad_h_up, tf.int32),\
            tf.cast(pad_h_down,tf.int32),\
            tf.cast(pad_w_left, tf.int32),\
            tf.cast(pad_w_right,tf.int32)
            )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM