ValueError: could not broadcast input array from shape (256,340,3) into shape (256,340,30)

ValueError: could not broadcast input array from shape (256,340,3) into shape (256,340,30)

我试图在 python 中保存一叠 10 张 rgb 图像,但出现以下错误:

rgb[:,:,:, i] = img
ValueError: could not broadcast input array from shape (256,340,3) into shape (256,340,30) 

我试过了:

img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
rgb[:,:,:, i] = img

我也试过:

chunks = 10
step = int(math.floor((duration - chunks + 1)/(num_samples)))
dims = (256, 340, chunks * 3, num_samples)
rgb = np.zeros(shape=dims, dtype=np.float64)
   for i in range(num_samples):
    for j in range(chunks):
         img_file = os.path.join(vid_name, 'image_{0:04d}.jpg'.format(i*step+j+1 + start_frame))
         img = cv2.imread(img_file, cv2.IMREAD_UNCHANGED)
         img = cv2.resize(img, dims[1::-1])
         rgb[:,:,(j+1)*3, i] = img

img_file 保留图像的路径,使其正确。我用

测试过
print("%r") % img_file

我想要实现的是 10 个堆叠的 rgb 图像。

感谢任何帮助。 谢谢!

方法 #1: 为了让事情更简单,我建议初始化一个 5D 数组,而不是将倒数第二个轴分成两个轴,保持 chunks3 像这样 -

dims = (256, 340, chunks , 3, num_samples)

为了补偿这个编辑,我们需要将图像的分配部分放入嵌套循环内的输出数组中,就像这样 -

rgb[:,:,j, :, i] = img

执行所有这些操作后,最后如果需要,只需重新整形为 4D 数组 -

rgb.shape = (256, 340, chunks* 3, num_samples)

因此,所有三个编辑都需要。


方法 #2: 保持循环代码不受问题影响,我们可以这样做 -

rgb[:,:,j*3:(j+1)*3, i] = img