xxxxxxxxxx
np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2
array([[1, 2],
[3, 4],
[5, 6]])
xxxxxxxxxx
import numpy as np
# 2d array
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
# print 2d array shape
print(arr.shape)
# output (2, 4)
# 4 dimension array
arr = np.array([1, 2, 3, 4], ndmin=4)
print(arr)
print('shape of array :', arr.shape)
# reshape array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
arr = arr.reshape(4, 3)
print(arr)
# output
# [[ 1 2 3]
# [ 4 5 6]
# [ 7 8 9]
# [10 11 12]]
# reshape uneven array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
arr = arr.reshape(4, 3)
print(arr)
# output ValueError: cannot reshape array of size 11 into shape (4,3)
xxxxxxxxxx
import numpy as np
# 2 X 3 matrix = 6 items
arr = np.array([[1, 2, 3], [4, 5, 6]])
# reshaping a matrix with -1 will let the function know that this dimension is not currently know
# x X 1 = 6 => x = 6
# therefore, by the end of this function, the new output will be 6 X 1 matrix
arr.reshape(-1, 1)
xxxxxxxxxx
np.reshape(a, (2, 3)) # C-like index ordering
array([[0, 1, 2],
[3, 4, 5]])
np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
array([[0, 1, 2],
[3, 4, 5]])
np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
array([[0, 4, 3],
[2, 1, 5]])
np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
array([[0, 4, 3],
[2, 1, 5]])
xxxxxxxxxx
>>> np.reshape(a, (2, 3)) # C-like index ordering
array([[0, 1, 2],
[3, 4, 5]])
>>> np.reshape(np.ravel(a), (2, 3)) # equivalent to C ravel then C reshape
array([[0, 1, 2],
[3, 4, 5]])
>>> np.reshape(a, (2, 3), order='F') # Fortran-like index ordering
array([[0, 4, 3],
[2, 1, 5]])
>>> np.reshape(np.ravel(a, order='F'), (2, 3), order='F')
array([[0, 4, 3],
[2, 1, 5]])
xxxxxxxxxx
a.reshape(3, -1)
array([[3., 7., 3., 4.],
[1., 4., 2., 2.],
[7., 2., 4., 9.]])
# if -1 is given then numpy will calculate the shape of the other dimensions
xxxxxxxxxx
import cv2
image = cv2.imread("image.png")
new_width, new_height = 50, 50
# resizes the loaded image to size (50,50)
resized_image = cv2.resize(image, (new_width, new_height))
xxxxxxxxxx
>>> a = np.arange(6).reshape((3, 2))
>>> a
array([[0, 1],
[2, 3],
[4, 5]])
xxxxxxxxxx
z.reshape(-1,1)
array([[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11],
[12]])