Omid Erfanmanesh
Omid Erfanmanesh

Reputation: 617

reshape 4D numpy Array of the image is changing the images figures

I want to change the 4d array of images from (50, 100, 100, 128) to (50,128, 100, 100) but when I plot the image after reshaping it the image was changed. All the images are CT Scan image from 50 patients and I want to use them for 3d Resnet Convolution Neural Network. in addition, each patient has 128 slices of 100*100 pixels image.

original shape:

data.shape

(50, 100, 100, 128)

the image from data

imgplot = plt.imshow(data[0,:,:,1])
plt.show()

orginal image

after reshaping

rd = data.reshape(-1,128,100,100)
rd.shape

(50, 128, 100, 100)
imgplot = plt.imshow(rd [0,1,:,:])
plt.show()

reshapingimage

Also, I tried the transpose but nothing changed

r2data = np.transpose(data)
r2data.shape

(128, 100, 100, 50)

Upvotes: 3

Views: 1545

Answers (1)

kmario23
kmario23

Reputation: 61315

Use array.transpose() with the desired order of axes:

# original 4D array
In [98]: data = np.random.random_sample((50, 100, 100, 128))

# move last axis to second position; reshapes data but would still be a `view`
In [99]: reshaped_data = data.transpose((0, -1, 1, 2))

In [100]: reshaped_data.shape
Out[100]: (50, 128, 100, 100)

If you really want a copy of the data after transposing, then you can force it to do so:

In [106]: reshaped_data = data.transpose((0, -1, 1, 2)).copy()

In [107]: reshaped_data.flags
Out[107]: 
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

Upvotes: 6

Related Questions