0

when I try to run the following code:

def pixel_drop(image, drop_rate=0.5):
    img_h, img_w, _ = image.shape
    pixel_count = img_h * img_w
    drop_num = pixel_count * drop_rate

    for drop in range(int(drop_num)):
        rand_x = random.randint(0, img_h - 1)
        rand_y = random.randint(0, img_w - 1)
        image[rand_x, rand_y,:] = 0

    return image

I seem to get the following error:

TypeError: 'Tensor' object does not support item assignment

It looks like I can't assign things to a tensor. How should I go about implementing this?

1
  • Is image[rand_x, rand_y,:] = 0 the cause of the error ? Which line ? Commented May 20, 2022 at 6:01

1 Answer 1

1

This notebook has the details about how to assign values to different variables and constants.

This example assigns zeros of the appropriate shape to the tensor. But you may have a different type of variable in your code.

import tensorflow as tf
import numpy as np

def pixel_drop(image, drop_rate=0.5):
    img_h, img_w, _ = image.shape
    pixel_count = img_h * img_w
    drop_num = pixel_count * drop_rate

    for drop in range(int(drop_num)):
        rand_x = np.random.randint(0, img_h - 1)
        rand_y = np.random.randint(0, img_w - 1)
        image[rand_x, rand_y,:].assign(tf.zeros(shape=(3,)))

    return image

img_data = tf.Variable(tf.random.uniform((100, 100, 3)))
print(pixel_drop(img_data))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! The notebook is really helpful. This pretty much solves it for me :)
So you may 'upvote' the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.