Jan Rüegg
Jan Rüegg

Reputation: 10075

Best way to create a three channel image with a fixed color?

I want to create a numpy three channel image with dimensions 10x5 and a fixed color of [0, 1, 2]. I'm currently doing it using the following code:

x = np.array([0, 1, 2])
x = np.array((x,) * 10)
x = np.array((x,) * 5)

This works, but is not very elegant. What is the best / most efficient way to achieve the same with less code?

Upvotes: 1

Views: 167

Answers (3)

taras
taras

Reputation: 6915

Alternatively, you can use np.full:

np.full((10, 5, 3), [0, 1, 2])

It creates an array of given shape (10, 5, 3) and fills it with a constant value [0, 1, 2].

Upvotes: 2

Divakar
Divakar

Reputation: 221684

Use np.broadcast_to to get a view into the input 1D array -

np.broadcast_to([0, 1, 2],(5,10,3))

If you need a copy that has its own data, simply append .copy() -

np.broadcast_to([0, 1, 2],(5,10,3)).copy()

Or use np.tile -

np.tile([0,1,2],(5,10,1))

The benefit with having a view is that there's no extra memory overhead and virtually free. -

In [17]: x0 = np.arange(3)

In [18]: %timeit np.broadcast_to(x0,(5,10,len(x0)))
100000 loops, best of 3: 3.16 µs per loop

In [19]: x0 = np.arange(3000)

In [20]: %timeit np.broadcast_to(x0,(5,10,len(x0)))
100000 loops, best of 3: 3.08 µs per loop

Upvotes: 1

Dschoni
Dschoni

Reputation: 3872

What about slice notation?

a = np.empty((10,5,3))
a[:,:,0]=0
a[:,:,1]=1
a[:,:,2]=2

Upvotes: 1

Related Questions