Pythonで、ValueError: need at least one array to concatenate とは何でしょうか??
下記サイトの、画像分類でkerasを使用して試そうとしたら、上記のエラーが出てきてしまいました。
AIに五等分の花嫁の正妻を判定させてみた
Traceback (most recent call last): File "/Users/Name/Desktop/*/split.py", line 39, in <module> X = np.r_[tuple(img_list)] File "/Users/Name/opt/anaconda3/lib/python3.9/site-packages/numpy/lib/index_tricks.py", line 407, in __getitem__ res = self.concatenate(tuple(objs), axis=axis) File "<__array_function__ internals>", line 5, in concatenate ValueError: need at least one array to concatenate
該当の失敗コードは、4. データの分類の
tuple化して結合
X = np.r_[tuple(img_list)]
なのですが、どこが問題なのでしょうか?
Pythonに詳しい方、どうか対策方法をいただけたら幸いです。
以下、全文コードです。
split.py
1import numpy as np 2import glob 3import cv2 4from keras.utils.np_utils import to_categorical 5# from tensorflow.keras.utils import to_categorical 6# from tensorflow.keras.utils import np_utils 7import pandas as pd 8import matplotlib.pyplot as plt 9 10names = ['hitori', 'kita', 'nizika', 'ryo'] 11img_list = [] 12label_list = [] 13 14# append index 15for index, name in enumerate(names): 16 face_img = glob.glob('data/'+name+'/*.png') 17 for face in face_img: 18 # imread RGB 19 a = cv2.imread(face, 1) 20 b = np.expand_dims(a, axis=0) 21 img_list.append(b) 22 label_list.append(index) 23 24# convert pandas 25X_pd = pd.Series(img_list, dtype='float64') 26y_pd = pd.Series(label_list, dtype='float64') 27 28# merge 29Xy_pd = pd.concat([X_pd, y_pd], axis=1) 30# shuffle 31sf_Xy = Xy_pd.sample(frac=1) 32# shuffle後にlistとして再取得 33img_list = sf_Xy[0].values 34label_list = sf_Xy[1].values 35# tuple化して結合 36X = np.r_[tuple(img_list)] 37# convert binary 38Y = to_categorical(label_list) 39 40train_rate = 0.8 41 42train_n = int(len(X) * train_rate) 43train_X = X[:train_n] 44test_X = X[train_n:] 45train_y = Y[:train_n][:] 46test_y = Y[train_n:][:]
当方のmacのpythonで、質問のコードの画像ファイルのパスと、画像ファイルのファイル名の拡張子を変えて(png→jpg)、他はそのままで実行したら、質問の
> X = np.r_[tuple(img_list)]
より前の
> X_pd = pd.Series(img_list, dtype='float64')
でエラーが出ます
質問者さんの環境では、エラーは出ないのでしょうか?
画像ファイルのサイズが統一されてない場合は、下記のエラーが出ます
「ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions.」
そこで、「a = cv2.imread(face, 1)」のすぐ下に
a = cv2.resize(a, (100, 100))
を追加して画像ファイルのサイズを統一したら、下記のエラーが出ます
「ValueError: Wrong number of dimensions. values.ndim > ndim [5 > 1]」
環境
Python 3.7.16 (anaconda)
pandas 1.3.5 (python 3.7なので、少々古いです)
質問者さん
> 画像はちゃんと読み込めていますか?
コードの「label_list.append(index)」のすぐ下に、(インデントを合わせて)下記を追加して実行したら、画像ファイルがちゃんと読み込めてるか分かります
print("face: " + face)
print("b.shape: " + str(b.shape))

あなたの回答
tips
プレビュー