I have been looking for a solution for this for a while but I can't seem to find anything.
Some info about my env:
print(tf.__version__)
print(tf.executing_eagerly())
print(tf.config.list_physical_devices('GPU'))
Output:
2.7.0
True
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
I am using a tf.data.Dataset
created with
train_ds = tf.data.Dataset.list_files(str(train_dir/'*'), shuffle=False)
train_ds = train_ds.shuffle(train_count, reshuffle_each_iteration=False)
val_ds = tf.data.Dataset.list_files(str(val_dir/'*'), shuffle=False)
val_ds = val_ds.shuffle(val_count, reshuffle_each_iteration=False)
I then created some helper functions
def process_path(file_path):
img = tf.io.read_file(file_path)
img = decode_img(img)
return img
def bin_image(image, mask):
mask = mask.numpy()
bins = np.array([20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240])
new_mask = np.digitize(mask, bins)
new_mask_tensor = tf.convert_to_tensor(new_mask, np.float32)
return image, new_mask_tensor
def split_image(image):
cityscape = tf.image.crop_to_bounding_box(image, 0, 0, 256, 256)
mask = tf.image.crop_to_bounding_box(image, 0, 256, 256, 256)
return bin_image(cityscape, mask)
Using the helper functions
train_ds = train_ds.map(process_path, num_parallel_calls=AUTOTUNE)
val_ds = val_ds.map(process_path, num_parallel_calls=AUTOTUNE)
train_images = train_ds.map(split_image, num_parallel_calls=tf.data.AUTOTUNE)
val_images = val_ds.map(split_image, num_parallel_calls=tf.data.AUTOTUNE)
Printing the type of the mask
print(type(mask))
Outputs:
<class 'tensorflow.python.framework.ops.Tensor'>
I get the error at mask = mask.numpy()
. I believe that it is due to it being a different type of tensor not an EagerTensor
, which supports .numpy()
. The issue I have found is that most other ways of converting a tensor to a np.array
were removed in TF2.0. How would one go about converting a tensor to a np.array
given the scenario? Or should I just give up and attempt to find a different implementation?
Use tf.make_ndarray
to convert Tensorflow tensor to numpy.
Sample code
import tensorflow as tf
a = tf.constant([[1,2,3],[4,5,6]])
proto_tensor = tf.make_tensor_proto(a) # convert `tensor a` to a proto tensor
tf.make_ndarray(proto_tensor)
output
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)
In this case
mask = tf.make_ndarray(mask)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.