j35t3r
j35t3r

Reputation: 1533

how to replace values in a tensor?

I have reading an image as a tensor object, which aims to be a mask.

Now, I want to replace values which are close to white (almost 1.0) with 0 and values which are gray to 1.

Then the mask would be correct for my machine learning task.

I have tried it with:

tf.where(imag >= 1.0) 

or the next function also returns me the indices

greater = tf.greater_equal(mask, 0.95)

but how to update/assign 0? scatter_nd_add does not work for me.

mask = tf.scatter_nd_add(mask, greater, 0)

Edit:

I tried it differently:

v_mask = tf.Variable(tf.shape(mask))
ind = tf.to_float(mask >= 0.0)
v_mask.assign(ind)

but if I run the session. It stops there and does not go on.

What I really wanna do: I have a gray image with the dimensions (mxnx1, tensor, float32) and the values are rescaled to from [0,255] to [0,1].

I want to replace all values which are white (1) with 0 and gray (0.45 - 0.55) with 1 and the rest should be undefined.

Upvotes: 0

Views: 1411

Answers (2)

pmaini
pmaini

Reputation: 1

One workaround I found is to use the numpy() bridge. Do the numpy operations on the numpy array and the same is reflected in the tensor values. This is because, the numpy array and the pytorch tensor use the same underlying memory locations.

Memory sharing is mentioned on the pytorch introductory tutorial here

Upvotes: 0

P-Gn
P-Gn

Reputation: 24661

To threshold your image, you can use:

thim = tf.tofloat(im >= 0.95) # or to whichever type you use

To reassign the result to im, assuming it is a variable:

im_update = im.assign(thim)

This gives you an update op that you need to call for the update to happen.

If im is not a variable, then you cannot reassign values to it. Generally though, cases where you really need to reassign values to a node are scarce.

Upvotes: 1

Related Questions