提取图像像素数据存入数组时遇ValueError错误求助
解决图像像素提取时的ValueError错误
问题场景
需要从图像列表中提取64x64x3尺寸的像素数据,将所有值存入数组X,要求每张图像以单独一列的形式表示,原代码运行时触发ValueError。
原代码
Y = np.zeros((1,m)) X = np.zeros((ROWS*COLS*CHANNELS, m)) for i,image_file in enumerate(train_images): if 'cat' in image_file.lower(): Y[0,i] = 1 else: Y[0,i] = 0 img = cv2.imread(image_file, cv2.IMREAD_COLOR) img_resized = cv2.resize(img, (ROWS, COLS),interpolation=cv2.INTER_CUBIC) X[0, i] = np.squeeze(img_resized.reshape((ROWS*COLS*CHANNELS,1)))
报错信息
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: only size-1 arrays can be converted to Python scalars The above exception was the direct cause of the following exception: ValueError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_17808\256590185.py in <module> 10 img = cv2.imread(image_file, cv2.IMREAD_COLOR) 11 img_resized = cv2.resize(img, (ROWS, COLS),interpolation=cv2.INTER_CUBIC) ---> 12 X[0, i] = np.squeeze(img_resized.reshape((ROWS*COLS*CHANNELS,1))) ValueError: setting an array element with a sequence.
错误原因
代码中X[0, i]试图对数组X的第0行第i列这个标量位置赋值,但img_resized.reshape(...)展开后是长度为64*64*3=12288的一维数组,二者维度不匹配,导致赋值失败。
修正方案
将赋值语句的索引从X[0, i]改为X[:, i],表示对X的第i列整体赋值,匹配展开后的图像像素数组维度:
Y = np.zeros((1,m)) X = np.zeros((ROWS*COLS*CHANNELS, m)) for i,image_file in enumerate(train_images): if 'cat' in image_file.lower(): Y[0,i] = 1 else: Y[0,i] = 0 img = cv2.imread(image_file, cv2.IMREAD_COLOR) img_resized = cv2.resize(img, (ROWS, COLS),interpolation=cv2.INTER_CUBIC) # 修正索引,用[:,i]选中整列,同时用flatten简化展开操作 X[:, i] = img_resized.flatten()
额外优化建议
- 用
img_resized.flatten()替代reshape(...) + np.squeeze(),代码更简洁高效; - 提前确认
ROWS=64、COLS=64、CHANNELS=3,避免因变量定义错误导致维度不匹配; - OpenCV默认以BGR格式读取图像,若需要RGB格式,可添加
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)转换。
内容的提问来源于stack exchange,提问作者Justin Wilker
相关产品推荐
相关产品推荐

