[英]ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
[英]ValueError: could not broadcast input array from shape (224,224,4) into shape (224,224,3) , error while testing with GRAYSCALE IMAGES
以下代码适用于 RGB 图像,但不适用于灰度图像,另外我需要知道为什么灰度图像的形状为 (224,224,4),据我所知它应该是 (224,224,1)。
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)
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
为了社区的利益,在这里提供解决方案
Grayscale
图像有1
通道,RGB
图像有3
,RGBA
有4
个通道,最后一个通道代表alpha 。 你可以试试image = Image.open(img_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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.