I am storing a matrix (a python list of lists, not a numpy matrix) containing numbers in the range of [0;255] - representable well as uint8s. However, I would like to build a matrix which packs these numbers into 32bit ones.
Is there an efficient/nice way of doing this in numpy? Currently I'm rebuilding the matrix row by row with numpy.frombuffer()
but it feels like there should be a more convenient way of achieving this.
Current code:
def convert_8to32bit_matrix(mat):
ret_mat = np.zeros(shape=(mat.shape[0], int(mat.shape[1]/4)))
for i, row in enumerate(mat):
ret_mat[i] = np.frombuffer(row, dtype=np.uint32)
return ret_mat
Use numpy.ndarray.astype
method:
mat8 = np.array([[1, 2], [3, 4]]).astype(np.uint8)
mat32 = mat8.astype(np.uint32)
print(mat32.dtype) #uint32
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.