将numpy 1D阵列重塑为3D阵列

2024-06-02 04:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将np数组从1D改为3D时遇到问题

我在看一个视频文件, 然后,我从x个帧中提取人脸,并将其存储在带有标签的numpy数组中。你知道吗

谢谢你的帮助。你知道吗

fps = 3
time_of_video = 10
x = 0
face_size = 128

images = []
labels = []

for original_name, filename, label in tqdm(zip(train_sample_metadata['original'], train_sample_metadata['filename'], train_sample_metadata['label'])):

...

        video_1 = read_video(f'{base_path}/{filename}', fps*time_of_video)
        video_2 = read_video(f'{base_path}/{original_name}', fps*time_of_video)
        face_annotations = get_annotations(real_video)
        faces_1 = crop_faces(video_1, face_annotations, face_size)
        faces_2 = crop_faces(video_2, face_annotations, face_size)

        x = faces_1

        for ff, rf in zip(faces_1, faces_2):
            if np.array_equal(ff, rf):
                y.append(0)
            else:
                y.append(1)

        y = to_categorical(np.array(y), 2)

    images.append(x)
    labels.append(y)


images = np.array(images)
labels = np.array(labels)

images.shape, labels.shape
((400,), (400,))

images = images.reshape((images.shape[0] * images.shape[1], 128, 128, 3))
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-38-af9e927f8a1c> in <module>
----> 1 images = images.reshape((images.shape[0] * images.shape[1], 299, 299, 3))

IndexError: tuple index out of range

Tags: ofsizelabelstimevideonparrayface
2条回答

可以使用将单通道图像转换为三通道图像

image3Channel=np.stack((image1Channel,)*3, -1)

您的images数组的形状可能是(400,),因为原始列表不包含所有相同的形状。假设您的图片/视频在5D中的表示是正确的,那么如果所有附加项的大小相同,它将转换为numpy数组。但没有。试试看:

for i in images:
    print(np.array(i.shape))

当您运行此行时,您可能会发现您的列表被转换为列表数组的原因:

images = np.array(images)

reshape函数只重新排列当前数组。想象一个总共有8个单位的立方体。一个数组只能用这8个单位来重塑。你知道吗

正如我所说的,如果你发现不是所有的图片数组都是相同的形状,你将无法将它们重塑为相同的形状。您需要裁剪或调整大小。您可以使用PIL及其Image模块来实现这一点。你知道吗

from PIL import Image

pic = Image.fromarray(pic).resize((128, 128, 3))

相关问题 更多 >