[英]reshape a numpy 1D array to a 3D array
我在將 numpy 數組從 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
您的images
數組可能是 (400,) 形狀,因為原始列表不包含所有相同的形狀。 假設您的圖片/視頻在 5D 中具有正確的表示形式,如果所有附加項目的大小相同,它就會轉換為一個numpy
數組。 但它沒有。 嘗試:
for i in images:
print(np.array(i.shape))
當您運行此行時,您可能會發現為什么您的列表被轉換為列表數組:
images = np.array(images)
reshape
函數只重新排列當前數組。 想象一個總共有 8 個單位的2x2x2立方體。 一個陣列只能使用這 8 個單位進行重塑。
正如我所說,如果您發現並非所有圖片陣列都是相同的形狀,您將無法將它們重塑為相同的形狀。 您需要裁剪或調整大小。 你可以用PIL
和它的Image
模塊來做到這一點。
from PIL import Image
pic = Image.fromarray(pic).resize((128, 128, 3))
您可以使用以下方法將單通道圖像轉換為三通道圖像
image3Channel=np.stack((image1Channel,)*3, -1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.