python+numpy:矩阵array创建

#! usr/bin/env python
# coding: utf-8


import numpy as np
import cv2

# create array from python list and so on
a = [1,2,3]
print ('The type of \'a\' is ' + str(type(a)))
a = np.array(a)
print('The type of \'a\' is ' + str(type(a)))

b = np.array([[1,2]])
print(b)
print(type(b))
print(b.shape)
print(b[0][0])
print(b.dtype)
print(b.ndim)
print(b.size)

# create an array with zeros
zeroMatrix = np.zeros([2,3], dtype=np.int8)
print(zeroMatrix)
print(np.int8(zeroMatrix[0,0]+257))

# create an array with zeros_like
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix)
matrix_zeros_like = np.zeros_like(matrix)
print(matrix_zeros_like)

# create an array with ones
matrixOnes = np.ones((3,4), dtype=np.int16)
print(matrixOnes)

# create an array with ones_like
matrix = np.array([[1,2,3],[5,6,7]])
matrix_ones_like = np.ones_like(matrix)
print(matrix_ones_like)

# create an array with empty
emptyMatrix = np.empty([1,3])
emptyMatrix[0,1] = 1
emptyMatrix[0,2] = 2
print(emptyMatrix)

# create an array with empty_like
matrix = np.array([[1,0],[2,4],[0,5]])
matrix_empty_like = np.empty_like(matrix)
print(matrix_empty_like)

# create an array with arange
matrix = np.arange(1,10,1)
print(matrix)

# create an array with linspace
matrix = np.linspace(1,10,10)
print(matrix)

# create an array with numpy.random.rand
matrix = np.random.rand(2,3)
print(matrix)

# create an array with numpy.random.randn
matrix = np.random.randn(3,3)
print(matrix)
mean = np.mean(matrix)
std = np.std(matrix)
print(mean)
print(std)

# create an array with fromfunction
# please wait me to add

# create an array with fromfile
# we can get an array from a file, eg: .txt, .raw and so on.
# create a txt file at first
matrix = np.array([1,2,3,4,5,6], dtype=np.uint8)
matrix.tofile('matrix.txt')

result = np.fromfile('matrix.txt', dtype=np.uint8)
# please keep the dtype are same
print(result)

猜你喜欢

转载自blog.csdn.net/qq_27261889/article/details/81589642