0

I have converted an image into a 2-dim Array to make some analysis:

im=imageio.imread(file)
im2D=im[:,:,0]

Now I need an efficient way to turn over this step. For the moment I'm doing this with 2 for-loops but I think this is really inefficient:

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)

Example: imageio gives me something like this:

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

and im[:,:,0] gives me something like this:

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

2 Answers2

0

Assuming that I understand your question correctly and your goal is to add a dimension (an additional axis) to your existing array in which you repeat the existing data three times. Then you could use one of the following ways:

# 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
0

I think I have already found a solution to avoid the for-loops: D3->D2:

im=imageio.imread(file)
im2D=im[:,:,0]

2D->D3:

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