簡體   English   中英

我如何在Tensorflow中調整未知尺寸的圖像的大小(tf.shape(input)方法不起作用)

[英]How do I resize image with unknown size in Tensorflow(tf.shape(input) method doesn't work)

根據這篇文章 ,可以使用tf.shape()調整大小未知的圖像,如占位符。 但是該方法似乎不適用於我。 我有一些簡單的代碼,如下所示:

import tensorflow as tf
import numpy as np

def speed_tune(x, lower_bound=0.8, upper_bound=2.0):
    speed_rate = np.random.uniform(lower_bound, upper_bound)
    newshape = tf.shape(x)[1:] # get the tensor shape except for rank 0(None)
    newshape *= speed_rate # randomly stretch or compress the signal 
    return tf.resize(x, newshape)

sess = tf.InteractiveSession()
x = tf.placeholder(tf.int16, (None, 1000)) # x is a 1D audio signal
y = speed_tune(x)
data = np.random.randint(10, size=1000)
output = sess.run(y, feed_dict={x:data})

基本上,我的代碼執行以下操作:給定輸入1D數據x時,程序將嘗試通過某種隨機因素來拉伸或壓縮序列,並返回已調整的序列。 由於找不到任何直接執行此操作的Tensorflow函數,因此我將tf.resize視為1xD圖像,其中D是信號的長度。 但我得到一個錯誤:

Traceback (most recent call last):
  File "d:\SVNRepo\Python_codes\scratch.py", line 33, in <module>
    y = speed_tune(x)
  File "d:\SVNRepo\Python_codes\scratch.py", line 28, in speed_tune
    newshape *= speed_rate # randomly stretch or compress the signal 
TypeError: unsupported operand type(s) for *=: 'Tensor' and 'float'

所以看起來tf.shape(x)返回一個Tensor而不是指定張量形狀的整數值(由Tensorflow document驗證)。 我該如何解決?

不確定您要尋找的是什么,但這也許可以幫助tf.random.uniform避免張量/浮點運算

def speed_tune(x, lower_bound=1, upper_bound=2):
    speed_rate = tf.random.uniform([1,], lower_bound, upper_bound, dtype=tf.int32)
    newshape = tf.shape(x)[1:] # get the tensor shape except for rank 0(None)
    newshape = newshape * speed_rate # randomly stretch or compress the signal
    return tf.reshape(x, newshape)

使用過tf.reshape ,不確定您的意思是tf.resize

x = tf.placeholder(tf.int32, (None, 1000)) # x is a 1D audio signal
y = speed_tune(x)
data = np.random.rand(1, 1000)

with tf.Session() as sess:
    sess.run(y, feed_dict={x:data})

另一種方法是使用tf.pad :例如:

n = 10
tensor = tf.constant(np.random.rand(1, 10))
paddings = tf.constant([[0,1], [0,0]])

這種精確的填充設置意味着您在張量的末尾添加了n個零。 為了獲得初始尺寸,您需要對其進行重塑

padded = tf.pad(tensor, paddings)
output  = tf.reshape(padded, [1,n*2])

暫無
暫無

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

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