Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中向数组添加维度以创建图像_Python_Arrays_Image - Fatal编程技术网

如何在Python中向数组添加维度以创建图像

如何在Python中向数组添加维度以创建图像,python,arrays,image,Python,Arrays,Image,我已将图像转换为2维阵列,以进行一些分析: im=imageio.imread(file) im2D=im[:,:,0] 现在我需要一个有效的方法来完成这一步。目前,我正在使用2个For循环执行此操作,但我认为这是非常低效的: NewImage=np.zeros((len(im2D),len(im2D[0]),3,dtype=int) for x in range(len(im2D)): for y in range(len(im2D[0])): NewImage[x][y]=[i

我已将图像转换为2维阵列,以进行一些分析:

im=imageio.imread(file)
im2D=im[:,:,0]
现在我需要一个有效的方法来完成这一步。目前,我正在使用2个For循环执行此操作,但我认为这是非常低效的:

NewImage=np.zeros((len(im2D),len(im2D[0]),3,dtype=int)
for x in range(len(im2D)):
  for y in range(len(im2D[0])):
    NewImage[x][y]=[im2D[x][y],im2D[y][y],im2D[x][y]]
NewImage=NewImage.astype(np.uint8)
示例: imageio给了我这样的信息:

im=Array([[[255,255,255,255],
           ...
           [255,255,255,255]],
           
           [  0,  0,  0,  0],
           ...
           [255,255,255,255]]],dtype=uint8)
im2D=Array([[255,...,255],
           ...
            [  0,...,255]],dtype=uint8)
im[:,:,0]
给了我这样的信息:

im=Array([[[255,255,255,255],
           ...
           [255,255,255,255]],
           
           [  0,  0,  0,  0],
           ...
           [255,255,255,255]]],dtype=uint8)
im2D=Array([[255,...,255],
           ...
            [  0,...,255]],dtype=uint8)

假设我正确理解了您的问题,并且您的目标是向现有数组中添加一个维度(一个附加轴),在该数组中重复现有数据三次。 然后,您可以使用以下方法之一:

# the 2d array
arr = np.ones((5,5))

# a manually way to stack the array 3 times along a new axis
arr3d1 = np.array([arr for i in range(3)])

# even more manually (without stacked loops though)
# useful if you want to change the content eg:
arr3d2 = np.array([arr, 1/arr, 2*arr])

# use numpy's tile 
arr_h=arr[None,:,:] # first prepend a new singular axis
arr3d3 = np.tile(arr_h, (3,1,1)) # repeat 3 times along first axis and keep other axes

我想我已经找到了一个避免for循环的解决方案: D3->D2:

2D->D3:

NewImage=np.zeros((len(im2D),len(im2D[0]),3,dtype=int)
NewImage[:,:,0]=im2D
NewImage[:,:,1]=im2D
NewImage[:,:,2]=im2D
看看这里。。。