I have a numpy array of images with the shape of (5879,). Inside every index of the numpy array, I have the Pixels of the image with a shape of (640,640,3).
I want to reshape the complete array in such a way that the shape of the numpy array becomes (5879,640,640,3).
please check, whether below code works for you or not
import numpy as np
b = np.array([5879])
b.shape
output (1,)
a = np.array([[640],[640],[3]])
a = a.reshape((a.shape[0], 1))
a.shape
output (3, 1)
c = np.concatenate((a,b[:,None]),axis=0)
c.shape
Output:
(4, 1)
np.concatenate((a,b[:,None]),axis=0)
output
array([[ 640],
[ 640],
[ 3],
[5879]])
You want to stack your images along the first axis, into a 4D array. However, your images are all 3D.
So, first you need to add a leading singleton dimension to all images, and then to concatenate them along this axis:
imgs = [i_[None, ...] for i_ in orig_images] # add singleton dim to all images
x = np.concatenate(imgs, axis=0) # stack along the first axis
Edit:
Based on Mad Phyiscist's comment, it seems like using np.stack is more appropriate here: np.stack takes care of adding the leading singleton dimension for you:
x = np.stack(orig_images, axis=0)
Related
I have the following code which gets the color palette from series of images and try to reshape the output using numpy reshape. but when I try reshaping the output I get the error can't reshape array of size 27 into shape (3,3).
The output of Colours array print out is like this
[(256,256,265),(256,256,265),(256,256,265),(256,256,265),(256,256,265),(256,256,265),(256,256,265),(256,256,265),(256,256,265)]
Which are 9 tuples containing the colour palette which supposedly can be reshaped into 3 * 3
But numpy.reshape keeps saying it is 27 items and can't be reshaped into 3*3 array,
My question is how can I reshape this output into 3 * 3 array
So The colour array I need after reshaping should look something like this:
colours=[
[(256,256,265),(256,256,265),(256,256,265)],
[(256,256,265),(256,256,265),(256,256,265)],
[(256,256,265),(256,256,265),(256,256,265)]
]
from PIL import Image
import numpy as np
array=[]
for row in range(1,4):
for column in range(1,4):
filename = '/storage/emulated/0/python/banana/banana_0'+str(row)+'_0'+str(column)+'.png'
img = Image.open(filename)
img.show()
colors = img.getpixel((10,10))
array.append(colors)
array=np.array(array)
box_array=array.reshape(3,3)
You need to reshape using the full destination shape. Your array contains 27 elements in total
When you do:
array = np.array(array)
you obtain a (9, 3) shaped array, so you can't reshape it in (3, 3), but in (3, 3, 3).
you can proceed like:
box_array = array.reshape(3, 3, 3)
Depending on what dimension is subject to change in your array later, you can let numpy figure it out.
If for instance your 2nd and 3rd dimensions will always be (3, 3), then you can reshape your array as follows and numpy will detect automatically the 1st dimension:
box_array = array.reshape(-1, 3, 3)
And inversely if your 1st and 2nd dimensions will always be (3, 3), then you can reshape your array as follows and numpy will detect automatically the 3rd dimension:
box_array = array.reshape(3, 3, -1)
I have a 3D numpy array A representing a batch of images:
A.shape -> (batch_size, height, width)
I want to access this array using two other arrays Hs,Ws, of size batch_size.
They contain the x index and y index of each image that I want to access.
Example 2 images of size 3x3:
A.shape(2,3,3)
A = [[[1,2,3],[5,6,7],[8,9,10]], [[10,20,30],[50,60,70],[80,90,100]]]
Hs = [0,2]
Ws = [1,2]
I want to acces A so that I get:
A[:, Hs,Ws] = [2,100]
Doing it like this (A[:, Hs,Ws]) unfortunately results in a 2x2 array (batch_size x batch_size)
Executed with a for loop this would look like this:
Result = np.zeros(batch_size)
for b in range(0,batch_size):
Result[b] = A[b,Hs[b],Ws[b]]
Is it possible to do this without a for loop by accessing A directly in a vectorized manner?
Do you mean this:
In [6]: A = np.array(A); Hs=np.array(Hs); Ws=np.array(Ws)
In [7]: A.shape
Out[7]: (2, 3, 3)
In [8]: A[np.arange(2), Hs, Ws]
Out[8]: array([ 2, 100])
When using indexing arrays, they 'broadcast' against each other. Here with (2,),(2,),(2,) the broadcasting is eash.
import numpy as np
a = np.array([1,2,3,4])
print a.shape[0]
Why it will output 4?
The array [1,2,3,4], it's rows should be 1, I think , so who can explain the reason for me?
because
print(a.shape) # -> (4,)
what you think (or want?) to have is
a = np.array([[1],[2],[3],[4]])
print(a.shape) # -> (4, 1)
or rather (?)
a = np.array([[1, 2 , 3 , 4]])
print(a.shape) # -> (1, 4)
If you'll print a.ndim you'll get 1. That means that a is a one-dimensional array (has rank 1 in numpy terminology), with axis length = 4. It's different from 2D matrix with a single row or column (rank 2).
More on ranks
Related questions:
numpy: 1D array with various shape
Python: Differentiating between row and column vectors
The shape attribute for numpy arrays returns the dimensions of the array. If a has n rows and m columns, then a.shape is (n,m). So a.shape[0] is n and a.shape[1] is m.
numpy arrays returns the dimensions of the array. So, when you create an array using,
a = np.array([1,2,3,4])
you get an array with 4 dimensions. You can check it by printing the shape,
print(a.shape) #(4,)
So, what you get is NOT a 1x4 matrix. If you want that do,
a = numpy.array([1,2,3,4]).reshape((1,4))
print(a.shape)
Or even better,
a = numpy.array([[1,2,3,4]])
a = np.array([1, 2, 3, 4])
by doing this, you get a a as a ndarray, and it is a one-dimension array. Here, the shape (4,) means the array is indexed by a single index which runs from 0 to 3. You can access the elements by the index 0~3. It is different from multi-dimensional arrays.
You can refer to more help from this link Difference between numpy.array shape (R, 1) and (R,).
I'm using python / Numpy to store small images into ndarray.
I'm stuck when I'm trying to transform an ndarray from 32,32,1 shape to 1,32,32,1. Any help ? Thanks
You need to expand the dimensions of the numpy array. Use np.expand_dims.
arr = np.expand_dims(arr, axis=0)
arr[np.newaxis, :, :, :] will work
Instead of explicitly adding an axis you could also explicitly reshape it to add the axis:
>>> import numpy as np
>>> arr = np.ones((32, 32, 1)) # just ones for demonstration purposes
>>> reshaped = arr.reshape(1, *arr.shape)
>>> reshaped.shape
(1, 32, 32, 1)
If I create an array X = np.random.rand(D, 1) it has shape (3,1):
[[ 0.31215124]
[ 0.84270715]
[ 0.41846041]]
If I create my own array A = np.array([0,1,2]) then it has shape (1,3) and looks like
[0 1 2]
How can I force the shape (3, 1) on my array A?
You can assign a shape tuple directly to numpy.ndarray.shape.
A.shape = (3,1)
As of 2022, the docs state:
Setting arr.shape is discouraged and may be deprecated in the future.
Using ndarray.reshape is the preferred approach.
The current best solution would be
A = np.reshape(A, (3,1))
A=np.array([0,1,2])
A.shape=(3,1)
or
A=np.array([0,1,2]).reshape((3,1)) #reshape takes the tuple shape as input
The numpy module has a reshape function and the ndarray has a reshape method, either of these should work to create an array with the shape you want:
import numpy as np
A = np.reshape([1, 2, 3, 4], (4, 1))
# Now change the shape to (2, 2)
A = A.reshape(2, 2)
Numpy will check that the size of the array does not change, ie prod(old_shape) == prod(new_shape). Because of this relation, you're allowed to replace one of the values in shape with -1 and numpy will figure it out for you:
A = A.reshape([1, 2, 3, 4], (-1, 1))
You can set the shape directy i.e.
A.shape = (3L, 1L)
or you can use the resize function:
A.resize((3L, 1L))
or during creation with reshape
A = np.array([0,1,2]).reshape((3L, 1L))
Your 1-D array has the shape (3,):
>>>A = np.array([0,1,2]) # create 1-D array
>>>print(A.shape) # print array shape
(3,)
If you create an array with shape (1,3), you can use the numpy.reshape mentioned in other answers or numpy.swapaxes:
>>>A = np.array([[0,1,2]]) # create 2-D array
>>>print(A.shape) # print array shape
>>>A = np.swapaxes(A,0,1) # swap 0th and 1st axes
>>>A # display array with swapped axes
(1, 3)
array([[0],
[1],
[2]])