numpy 在将2D图像转换为3D图像时,轴与阵列不匹配

c0vxltue  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(155)

将2D图像转换为3D中,为什么我在numpy中将图像转换为数组

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

我得到这个错误吗?
ValueError:axes do not match array
下面是我的部分代码:

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)

对于将2D照片转换为3D的项目,我遇到了将图像转换为numpy中的数组的问题:误差
ValueError:axes do not match array”

7qhs6swi

7qhs6swi1#

我可以通过尝试移动2D数组的3个轴来获得您的错误

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移动现有轴;它不会增加新的维度。当人们考虑“行向量”与“列向量”时,这是最常见的问题,而没有认真考虑1d numpy数组的形状。

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

1D数组的转置根本不改变形状。这在np.transpose中有明确的记录。
要添加维度,必须使用reshape,或None/newaxis索引习惯用法

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.]]])

相关问题