create 3D binary image
<p>I have a 2D array, <code>a</code>, comprising a set of 100 x,y,z coordinates: </p>

<pre><code>[[ 0.81  0.23  0.52]
 [ 0.63  0.45  0.13]
 ...
 [ 0.51  0.41  0.65]]
</code></pre>

<p>I would like to create a 3D binary image, <code>b</code>,  with 101 pixels in each of the x,y,z dimensions, of coordinates ranging between 0.00 and 1.00. 
Pixels at locations defined by <code>a</code> should take on a value of 1, all other pixels should have a value of 0.</p>

<p>I can create an array of zeros of the right shape with <code>b = np.zeros((101,101,101))</code>, but how do I assign coordinate and slice into it to create the ones using <code>a</code>?</p>

<p>First, start off by safely rounding your floats to ints. In context, see <a href="http://stackoverflow.com/q/3387655/525169">this</a> question.</p>

<pre><code>a_indices = np.rint(a * 100).astype(int)
</code></pre>

<p>Next, assign those indices in <code>b</code> to 1. But be careful to use an ordinary <code>list</code> instead of the array, or else you'll trigger the usage of <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays" rel="nofollow">index arrays</a>. It seems as though performance of this method is comparable to that of alternatives (Thanks @Divakar! :-)</p>

<pre><code>b[list(a_indices.T)] = 1
</code></pre>

<p>I created a small example with size 10 instead of 100, and 2 dimensions instead of 3, to illustrate:</p>

<pre><code>&gt;&gt;&gt; a = np.array([[0.8, 0.2], [0.6, 0.4], [0.5, 0.6]])
&gt;&gt;&gt; a_indices = np.rint(a * 10).astype(int)
&gt;&gt;&gt; b = np.zeros((10, 10))
&gt;&gt;&gt; b[list(a_indices.T)] = 1
&gt;&gt;&gt; print(b) 
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
</code></pre>

python numpy indexing binary ndimage