我收到此错误Error when checking input: expected conv2d_11_input to have 4 dimensions, but got array with shape (300, 300, 3)
如何将RGB图像传递到CNN?如何枚举样本以创建4D图像?
答案 0 :(得分:3)
卷积函数需要一批图像,即使您有一个单一的图像,也应该将图像传递为:
# assume img is your RGB image
# add 4th batch dimension
img = np.expand_dims(img, axis=0))
# now you can pass it to CNN
答案 1 :(得分:0)
通常,要向numpy矩阵添加新维度,可以使用np.newaxis
或np.expand_dims
(或仅使用reshape
)
import numpy as np
nh, nw = 300, 300
x = np.random.rand(nh, nw, 3)
y = x[np.newaxis, ...]
z = np.expand_dims(x, axis=0)
>>> x.shape
(300, 300, 3)
>>> y.shape
(1, 300, 300, 3)
>>> z.shape
(1, 300, 300, 3)
但是,如果您想将RGB
馈入CNN模型,也许您还需要一步:交换频道并转换为float32:
import cv2
import numpy as np
fpath = "test.png"
nh, nw = 300, 300
img = cv2.imread(fpath)
img = cv2.cvtColor(cv2.resize(img, (nw, nh)), cv2.COLOR_BGR2RGB)
ximg = np.float32(img) / 255.0
ximg = ximg[np.newaxis, ...]
>>> (ximg.shape, ximg.dtype)
((1, 300, 300, 3), dtype('float32'))