python - Tensorflow 2:对掩码应用一种热编码以进行语义分割
问题描述
我正在尝试处理我的地面实况图像以创建一个热编码张量:
def one_hot(img, nclasses):
result = np.zeros((img.shape[0], img.shape[1], nclasses))
img_unique = img.reshape(512*512, img.shape[2])
unique = np.unique(img_unique, axis=0)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
for k, unique_val in enumerate(unique):
if (np.array_equal(img[i,j], unique_val)):
result[i,j,k] = 1
break
return result
这是从 WxHx3 图像创建 WxHxN 张量。我真的不喜欢这种方法,因为它的性能。你能建议更有效的方法吗?
我尝试使用 tf.one_hot 但它将图像转换为 WxHx3xN 张量。
解决方案
对于纯粹的 TF2.x 方法,您还可以执行以下操作
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import tensorflow as tf
@tf.function # Remove this to see the tf.print array values
def get_one_hot():
label_ids = [0,5,10]
mask_orig = tf.constant([[0,10], [0,10]], dtype=tf.float32) # [2,2]
mask_onehot = tf.concat([tf.expand_dims(tf.math.equal(mask_orig, label_id),axis=-1) for label_id in label_ids], axis=-1) # [2,2,2]
mask_label_present = tf.reduce_any(mask_onehot, axis=[0,1]) # [2]
tf.print('\n - label_ids:{}'.format(label_ids))
tf.print('\n - mask_orig:\n{}\n'.format(mask_orig))
for id_, label_id in enumerate(label_ids):
tf.print(' - mask_onehot:{}\n{}'.format(label_id, mask_onehot[:,:,id_]))
tf.print('\n - mask_label_present:\n ', mask_label_present)
get_one_hot()
推荐阅读
- android - 从 BottomSheetDialogFragment 打开片段 - Android Studio Java
- android - 当我向用户发送图像时,Firebase 数据库没有显示任何内容。reference.child("聊天").push().setValue(hashMap);
- c# - AWS Lambda 上的 .net core .XLSX 流式传输
- node.js - 数据库“neo4j”不可用。无法重置 neo4j 数据库
- javascript - 如何在此场景中触发 keyup 事件
- c# - 如何将字符串转换为 Microsoft.WindowsAzure.Storage.Table.ITableEntity?
- cmake - cmake configure_package_config_file 未正确添加 PATH_VARS
- java - 当我将 SpringBoot 应用程序部署到 AWS Elastic Beanstalk 并且无法从本地 SpringBoot 连接到 RDS 时出现 502 bad gateway
- c# - 是否有一种通用方法可以在现有列表上创建“视图”,允许仅在调用提交方法后才进行更改?
- c++ - 为什么我无法在下面的代码中为浮点变量添加值?