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>You could do something like this -</p>

<pre><code># Get the XYZ indices
idx = np.round(100 * a).astype(int)

# Initialize o/p array
b = np.zeros((101,101,101))

# Assign into o/p array based on linear index equivalents from indices array
np.put(b,np.ravel_multi_index(idx.T,b.shape),1)
</code></pre>

<hr>

<p>Runtime on the assignment part -</p>

<p>Let's use a bigger grid for timing purposes.</p>

<pre><code>In [82]: # Setup input and get indices array
    ...: a = np.random.randint(0,401,(100000,3))/400.0
    ...: idx = np.round(400 * a).astype(int)
    ...: 

In [83]: b = np.zeros((401,401,401))

In [84]: %timeit b[list(idx.T)] = 1 #@Praveen soln
The slowest run took 42.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 6.28 ms per loop

In [85]: b = np.zeros((401,401,401))

In [86]: %timeit np.put(b,np.ravel_multi_index(idx.T,b.shape),1) # From this post
The slowest run took 45.34 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 5.71 ms per loop

In [87]: b = np.zeros((401,401,401))

In [88]: %timeit b[idx[:,0],idx[:,1],idx[:,2]] = 1 #Subscripted indexing
The slowest run took 40.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 6.38 ms per loop
</code></pre>

python numpy indexing binary ndimage