简体   繁体   中英

concatenate two arrays into additional dimension python

I have 2 arrays shape of each (50,50,3) when I do concatenation .... I need the new dimension to be :

(2 , 50 , 50,3)

where 2 is for 2 images I tried:

np.concatenate((cat01 , cat02 ) , axis = 0)

outputs (100 , 50 , 3)

And

np.concatenate((cat01 , cat02 ) , axis = 1)

outputs (50 , 100 , 3)

So How Could I add Another dimension to the array ?

You want this:

np.stack((cat01, cat02))

Then the shape is (2, 50, 50, 3) .

cat01G = cat01[np.newaxis , :,:,:]

只需添加np.newaxis这将解决您的问题

While stack is convenient, it is a good idea to understand how to use concatenate directly:

np.concatenate((cat01[None,...] , cat02[None,...] ) , axis = 0)

In other words - adjust the dimensions of each of the input arrays. Using None or np.newaxis should become something you use routinely in numpy . Also learn to do the same thing with reshape .

Also try:

np.expand_dims(cat01, axis=0)

Or:

np.array((cat01, cat02))

a bit simpler than

np.concatenate((cat01[None], cat02[None), 0)

and roughly as fast.

>>> cat01 = np.ones((50, 50, 3))
>>> cat02 = np.zeros((50, 50, 3))
>>> 
>>> from timeit import timeit
>>> kwds = dict(globals=globals(), number=100000)
>>> 
>>> timeit("np.concatenate((cat01[None], cat02[None]), 0)", **kwds)
0.7162981643341482
>>> timeit("np.array((cat01, cat02))", **kwds)
0.7192633128724992
>>> timeit("np.stack((cat01, cat02))", **kwds)
1.1847702045924962

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM