python - 调整引用另一个数组的numpy数组的大小

标签 python arrays numpy opencv

mypath='/Users/sachal/Desktop/data_raw/normal_1/images'
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = np.asarray(np.empty(len(onlyfiles), dtype=object))

for n in range(0, len(onlyfiles)):
  images[n] = cv2.imread( join(mypath,onlyfiles[n]) )
#--------------------------------------------------------------------------------
resized = np.asarray(np.empty(len(onlyfiles), dtype=object))
img_f = np.asarray(np.empty(len(onlyfiles), dtype=object))


for n in range(0, len(onlyfiles)):
  resized[n] = cv2.resize(images[n],(101,101))
  img_f[n] = cv2.cvtColor(resized[n], cv2.COLOR_BGR2YUV)

train_img =  np.asarray(img_f)
#--------------------------------------------------------------------------------

在上面的代码中,我首先使用 opencv 加载图像,然后在第二个 block 中调整大小并更改它们的颜色空间。

我的批量大小是 6408图像尺寸为 101*101*3当我做 train_img.shape我得到 (6408,)并根据 train_img[i].shape我得到 101*101*3因此我无法训练我的神经网络模型,我想要的尺寸是6408*101*101*3
我尝试用这个 train_img.resize(6408,101,101,3) reshape 我得到了这个ValueError: cannot resize an array that references or is referenced by another array in this way. Use the resize function
在拟合我的模型时出现此错误 Error when checking input: expected conv2d_3_input to have 4 dimensions, but got array with shape (6408, 1)
我想知道是否可以使用当前用于加载图像的方法更改输入的尺寸。

最佳答案

你不应该使用 dtype=object这里。 OpenCV 创建 ndarray无论如何图像。

这是您的代码的更正版本:

mypath='/Users/sachal/Desktop/data_raw/normal_1/images'
onlyfiles = [ f for f in os.listdir(mypath) if os.path.isfile(join(mypath,f)) ]
images = []

for file in onlyfiles:
   img = cv2.imread(os.path.join(mypath,file))
   resized_img = cv2.resize(img, (101, 101)) 
   yuv_img = cv2.cvtColor(resized_img, cv2.COLOR_BGR2YUV)
   images.append(yuv_img.reshape(1, 101, 101, 3))

train_img = np.concatenate(images, axis=0)
print(train_img.shape)

在循环中,您加载每个图像,调整其大小,将其转换为 YUV,然后将其放入列表中。在循环结束时,您的列表包含所有训练图像。您可以将其传递给 np.concatenate创建 ndarray .

关于python - 调整引用另一个数组的numpy数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858428/

相关文章:

Javascript 将数组索引简化为参数

Python numpy 从 bool 数组设置索引

python - 如何以干净有效的方式在pytorch中获得小批量?

python - 检查Python中的元素是否乱序

python - 新手 - 将 49 张 Excel 工作表读入数据框

python - celery :错误:无法识别的参数:worker -A test_tasks -l info -c 5

python - 如何使用 2D 蒙版过滤 3D 阵列

python - 调整什么参数才能使视差结果正确?在opencv中使用cv2.StereoBM

c++ - 如何正确传递这些值?

python - 如何在 python 中处理数据但添加到 MERN Stack 应用程序