Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ValueError:无法将输入数组从形状(224,4)广播到形状(224,3),使用灰度图像测试时出错_Python_Tensorflow_Keras - Fatal编程技术网

Python ValueError:无法将输入数组从形状(224,4)广播到形状(224,3),使用灰度图像测试时出错

Python ValueError:无法将输入数组从形状(224,4)广播到形状(224,3),使用灰度图像测试时出错,python,tensorflow,keras,Python,Tensorflow,Keras,以下代码适用于RGB图像,但不适用于灰度图像,我还需要知道为什么灰度图像的形状为(224,4),据我所知应该是(224,1) 为了社区的利益,在这里提供解决方案 Grayscale图像具有1通道,RGB图像具有3,以及 RGBA有4个通道,最后一个通道代表alpha。您可以尝试image=image.open(img\u path).convert('RGB')(摘自Frightera) 工作代码如下所示 import silence_tensorflow.auto import tensorf

以下代码适用于RGB图像,但不适用于灰度图像,我还需要知道为什么灰度图像的形状为(224,4),据我所知应该是(224,1)


为了社区的利益,在这里提供解决方案

Grayscale
图像具有
1
通道,
RGB
图像具有
3
,以及
RGBA
4个通道,最后一个通道代表alpha。您可以尝试
image=image.open(img\u path).convert('RGB')
(摘自Frightera)

工作代码如下所示

import silence_tensorflow.auto
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np

np.set_printoptions(suppress=True)
model = tensorflow.keras.models.load_model('models/keras_model.h5')
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
size = (224, 224)


def classify(img_path):
    image = Image.open(img_path).convert('RGB')
    image = ImageOps.fit(image, size, Image.ANTIALIAS)
    image_array = np.asarray(image)
    print(image_array.shape)
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    data[0] = normalized_image_array
    prediction = model.predict(data)
    print(prediction)
    if prediction[0][-1] == 1:      
        return False
    else:
        return True

灰度图像有1个通道正确,RGB图像有3个通道,RGBA有4个通道最后一个通道代表alpha。因此,您可能希望在加载后检查图像的形状等。那么您对代码中可以做哪些更改有何建议@Frightera您可以尝试
Image.open(img\u路径)。convert('RGB')
@Frightera谢谢,伙计,它成功了。:)
import silence_tensorflow.auto
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np

np.set_printoptions(suppress=True)
model = tensorflow.keras.models.load_model('models/keras_model.h5')
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
size = (224, 224)


def classify(img_path):
    image = Image.open(img_path).convert('RGB')
    image = ImageOps.fit(image, size, Image.ANTIALIAS)
    image_array = np.asarray(image)
    print(image_array.shape)
    normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
    data[0] = normalized_image_array
    prediction = model.predict(data)
    print(prediction)
    if prediction[0][-1] == 1:      
        return False
    else:
        return True