Finding centre of mass of tensor (tensorflow)

会有一股神秘感。 提交于 2019-12-13 14:24:56

问题


Is there an efficient way to find the centre of mass of a tensor? I'm working with N stacked volumes (Nx64x64x64) and would like to obtain an Nx3 tensor with the x,y,z position of the centre of mass of each 64x64x64 volume


回答1:


Following the formula, you should just need to multiply each coordinate by the corresponding mass, sum everything and divide by the total mass:

import tensorflow as tf

# Input volumes
volumes = tf.placeholder(tf.float32, [None, 64, 64, 64])
# Make array of coordinates (each row contains three coordinates)
ii, jj, kk = tf.meshgrid(tf.range(64), tf.range(64), tf.range(64), indexing='ij')
coords = tf.stack([tf.reshape(ii, (-1,)), tf.reshape(jj, (-1,)), tf.reshape(kk, (-1,))], axis=-1)
coords = tf.cast(coords, tf.float32)
# Rearrange input into one vector per volume
volumes_flat = tf.reshape(volumes, [-1, 64 * 64 * 64, 1])
# Compute total mass for each volume
total_mass = tf.reduce_sum(volumes_flat, axis=1)
# Compute centre of mass
centre_of_mass = tf.reduce_sum(volumes_flat * coords, axis=1) / total_mass



回答2:


This is a perfect use case for numpy.apply_over_axes:

my_tensor = np.apply_over_axes( np.mean, my_tensor, (1,2,3))

This will return an array of shape (N,1,1,1) with the average along each axis.



来源:https://stackoverflow.com/questions/51724450/finding-centre-of-mass-of-tensor-tensorflow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!