Reputation: 2168
Let say, I have a interpolation function.
def mymap():
x = np.arange(256)
y = np.random.rand(x.size)*255.0
return interp1d(x, y)
This guy maps a number in [0,255] to a number following the profile given by x
and y
(now y
is random, though). When I do following, each value in image gets mapped nicely.
x = imread('...')
x_ = mymap()(x)
However, how can I do this in Tensorflow? I want to do something like
img = tf.placeholder(tf.float32, [64, 64, 1], name="img")
distorted_image = tf.map_fn(mymap(), img)
But it results in an error saying
ValueError: setting an array element with a sequence.
For information, I checked if a function map is simple as below, it works well
mymap2 = lambda x: x+10
distorted_image = tf.map_fn(mymap2, img)
How can I map each number in a tensor? Could anyone help?
Upvotes: 0
Views: 633
Reputation: 28198
The function input of tf.map_fn
needs to be a function written with Tensorflow ops. For instance, this one will work:
def this_will_work(x):
return tf.square(x)
img = tf.placeholder(tf.float32, [64, 64, 1])
res = tf.map_fn(this_will_work, img)
This one will not work:
def this_will_not_work(x):
return np.sinh(x)
img = tf.placeholder(tf.float32, [64, 64, 1])
res = tf.map_fn(this_will_not_work, img)
Because np.sinh
cannot be applied to a TensorFlow tensor (np.sinh(tf.constant(1))
returns an error).
You can write your interpolation function in TensorFlow, and maybe ask for help in another StackOverflow question.
If you absolutely want to use scipy.interpolate.interp1d
, you will need to keep the code encapsulated in python. For that, you can use tf.py_func
, and use your scipy
function inside.
Upvotes: 1