axes don't match array in convert 2D images to 3D image

43 views Asked by At

In converting 2D images to 3D, why do I convert images to array in numpy

for object_images_array = object_images_array.transpose(1, 0, 2) # Change dimensions to (cube_depth, cube_height, cube_width)

Am I getting this error?

ValueError: axes don't match array

Here is part of my code:

import os
import cv2
import numpy as np
from mayavi import mlab
output_folder = 'output_img-test-2'
cube_height, cube_width = 200, 340  
 num_frames = 6
object_images = []
while frame_number < num_frames:
    cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number * frame_skip)
    ret, frame = cap.read()
    if not ret:
        break 
    # Resize 
    frame = cv2.resize(frame, (cube_width, cube_height))
    output_image_path = os.path.join(output_folder, f'output_{frame_number:04d}.png')
    cv2.imwrite(output_image_path, frame)
    frame_number += 1
cap.release()
cube_depth = len(object_images)   
x, y = np.meshgrid(np.arange(cube_width), np.arange(cube_height))
z = np.zeros_like(x)
object_images_array = np.array(object_images)
object_images_array = object_images_array.transpose(2, 0, 1)

For the project of converting 2D photos to 3D, I have the problem of converting images to an array in numpy: error

ValueError: axes don't match array"

1

There are 1 answers

0
hpaulj On

I can get your error by trying to move 3 axes of a 2d array

In [108]: np.ones((2,3)).transpose([1,0])
Out[108]: 
array([[1., 1.],
       [1., 1.],
       [1., 1.]])

In [109]: np.ones((2,3)).transpose([1,0,2])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[109], line 1
----> 1 np.ones((2,3)).transpose([1,0,2])

ValueError: axes don't match array

transpose moves existing axes; it does not add new dimensions. This is most frequently an issue when people think in terms of 'row vector' vs 'column vector', without taking seriously the shape of 1d numpy arrays.

In [110]: np.arange(4).T
Out[110]: array([0, 1, 2, 3])

transpose of a 1d array does not change the shape at all. This is clearly documented for the np.transpose.

To add a dimension you have to use reshape, or the None/newaxis indexing idiom

In [112]: np.ones((2,3)).reshape(2,1,3)
Out[112]: 
array([[[1., 1., 1.]],

       [[1., 1., 1.]]])

In [113]: np.ones((2,3))[:,None,:]
Out[113]: 
array([[[1., 1., 1.]],

       [[1., 1., 1.]]])