但是很多情况下不需要使用,在进行矩阵加减运算的时候会自动复制(主要使用了broadcast)
>>> a
array([[1, 2],
[3, 4],
[5, 6]])
>>> b
array([1, 2])
>>> a-b
array([[0, 0],
[2, 2],
[4, 4]])
用repeat和tile扩充数组元素,例如
>>> import numpy as np
>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.repeat(5)
array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4,
4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9,
9, 9, 9, 9])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.tile(a,2)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
官方例子:
>>> from numpy import *
>>> a=array([10,20])
>>> tile(a,(3,2)) #构造3X2个copy
array([[10, 20, 10, 20],
[10, 20, 10, 20],
[10, 20, 10, 20]])
>>> tile(42.0,(3,2))
array([[ 42., 42.],
[ 42., 42.],
[ 42., 42.]])
>>> from numpy import *
>>> repeat(7.,4)
array([ 7., 7., 7., 7.])
>>> a=array([10,20])
>>> a.repeat([3,2])
array([10, 10, 10, 20, 20])
>>> repeat(a,[3,2])
array([10, 10, 10, 20, 20])
>>> a=array([[10,20],[30,40]])
>>> a.repeat([3,2],axis=0)
array([[10, 20],
[10, 20],
[10, 20],
[30, 40],
[30, 40]])
>>> a.repeat([3,2],axis=1)
array([[10, 10, 10, 20, 20],
[30, 30, 30, 40, 40]])
将gray图像变成3通道的RGB图像
import numpy as np
image_gray = np.random.randint(255, size=(5,7))
image_rgb= np.tile(image_gray , 3).reshape((mask.shape[0],3,mask.shape[1])).transpose((0,2,1))
或者
import numpy as np
image_gray = np.random.randint(255, size=(5,7))
image_rgb= np.tile(image_gray.reshape((5,7,1)), 3)