numpy 我正在做一个简单的图像分类模型来检测图像中是否有猫

2skhul33  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(79)

这是代码的一部分,我得到的问题,

# Load the image using PIL
image_path = '/content/drive/MyDrive/_b3169321-61c1-4116-be9f-b1a4878318b5.jpg'
image = Image.open(image_path)

# Convert the image to a NumPy array
new_image = np.array(image)

# Preprocess the new image
new_image = new_image.reshape(-1, 224, 224, 3) / 255.0

这是错误消息

----> 9 new_image = new_image.reshape(-1, 224, 224, 3) / 255.0

ValueError: cannot reshape array of size 3145728 into shape (224,224,3)

我该怎么弥补?

3j86kqsm

3j86kqsm1#

您正在处理的图像的像素数超过模型输入(224 x 224 x 3)
当您使用PIL时,可以使用PIL.Image.resize将图像大小调整为该分辨率
image = Image.open(image_path).resize((224,224))
这个图像现在可以被转换成一个形状为(224, 224, 3)的numpy数组,但是如果原始图像的长宽比不同于1:1,那么图像将被拉伸到该长宽比。

mbzjlibv

mbzjlibv2#

解决方案:

# Load the image using PIL
image_path = '/content/drive/MyDrive/_b3169321-61c1-4116-be9f-b1a4878318b5.jpg'
image = Image.open(image_path)
image = image.resize((224,224)) #new line 
# Convert the image to a NumPy array
new_image = np.array(image)

# Preprocess the new image
new_image = new_image.reshape(-1, 224, 224, 3) / 255.0

说明:

好吧,问题是你加载的图像不是一个224 × 224的图像,请注意,在错误中它说,

  • ValueError:无法将大小为3145728的数组整形为(224,224,3)*

数组的大小是其形状中所有数字的乘积,因此如果图像的形状是(224,224,3),则其大小将是224x224x3,即150528,而不是3145728。这意味着jpg图像大于(224,224,3),我做了计算,要获得3145728的大小,你的图像形状必须是(1024,1024,3),所以,基本上你不能将(1024,1024,3)图像调整为(224,224,3),这意味着,扔掉一些像素和numpy不会为你做这件事,所以也许可以找到已经是224,224,3的图像,或者将图像重塑为224,224,3。所以我在你的代码中添加了一个“resize”。
如果成功了就告诉我

相关问题