首页 > 解决方案 > TensorFlow:如何在不包括零的张量中找到分割的最小/最大坐标?

问题描述

image_pred对于联合交集 (IoU) 的计算,我想在由 float32 3D 张量表示的分割图像中找到最小值和最大值(边界像素)的坐标。特别是,我的目标是找到图像中对象的左上角和右下角坐标。图像完全由黑色像素(值 0.0)组成,除了对象所在的位置,我有彩色像素(0.0 < 值 < 1.0)。这是这样一个边界框的示例(在我的例子中,对象是交通标志,环境被涂黑):

在此处输入图像描述

到目前为止,我的方法是tf.boolean_mask将每个像素设置为 False,除了颜色像素:

zeros = tf.zeros_like(image_pred)
mask = tf.greater(image_pred, zeros)
boolean_mask_pred = tf.boolean_mask(image_pred, mask)

然后用于tf.where查找蒙版图像的坐标。为了确定矩形左上角和右下角的水平和垂直坐标值tf.recude_max,我考虑过使用and tf.reduce_min,但是由于如果我提供 an ,它们不会返回单个值axis,我不确定这是否是正确的函数采用。根据文档,如果我不指定axis,该函数将减少所有维度,这也不是我想要的。执行此操作的正确功能是什么?最后的 IoU 是单个 1D 浮点值。

coordinates_pred = tf.where(boolean_mask_pred)
x21 = tf.reduce_min(coordinates_pred, axis=1)
y21 = tf.reduce_min(coordinates_pred, axis=0)
x22 = tf.reduce_max(coordinates_pred, axis=1)
y22 = tf.reduce_max(coordinates_pred, axis=0)

标签: tensorflowcomputer-visionimage-segmentation

解决方案


您需要做的就是不使用tf.boolean_mask. 首先,我定制了一张类似的图片。

import numpy as np
from matplotlib import pyplot as plt

image = np.zeros(shape=(256,256))
np.random.seed(0)
image[12:76,78:142] = np.random.random_sample(size=(64,64))
plt.imshow(image)
plt.show()

在此处输入图像描述

然后通过tensorflow得到它的最大值和最小值的坐标。

import tensorflow as tf

image_pred = tf.placeholder(shape=(256,256),dtype=tf.float32)
zeros = tf.zeros_like(image_pred)
mask = tf.greater(image_pred, zeros)

coordinates_pred = tf.where(mask)
xy_min = tf.reduce_min(coordinates_pred, axis=0)
xy_max = tf.reduce_max(coordinates_pred, axis=0)

with tf.Session() as sess:
    print(sess.run(xy_min,feed_dict={image_pred:image}))
    print(sess.run(xy_max,feed_dict={image_pred:image}))

[12 78]
[ 75 141]

推荐阅读