keras 当TensorFlow模型名称!= x时接收输出文本

yzuktlbb  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(123)

我做了一个模型,可以检测一个人的脸是朝右、朝左还是朝中间,我用下面的代码做了一个预测:

from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np

# Disable scientific notation for clarity
np.set_printoptions(suppress=True)

# Load the model
model = load_model('models//keras_Model.h5', compile=False)

# Load the labels
class_names = open('models//labels.txt', 'r').readlines()

# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)

# Replace this with the path to your image
image = Image.open('IMG.png').convert('RGB')

# resize the image to a 224x224 with the same strategy as in TM2:
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)

# turn the image into a numpy array
image_array = np.asarray(image)

# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1

# Load the image into the array
data[0] = normalized_image_array

# run the inference

prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]

print('Class:', class_name, end='')
print('Confidence score:', confidence_score)

这段代码给出了正确的预测,下面是labels.txt文件:

0 Left_Side_Face
1 Middle_Face
2 Right_Side_Face

我现在想做的是说,例如,人已经把他们的头转向右侧,我想打印的消息'面对电脑',但当我尝试这样做,我失败了。
下面是我尝试的代码:

if class_name == "2 Right_Side_Face":
    print('face the computer')
if class_name == "0 Left_Side_Face":
    print('face the computer')
else:
    print('Invalid class name')
    print('exiting.....')

问题是,每当我运行上面的代码时,它都会转到else并打印"Invalid class name",当我删除else时,代码中没有错误,它只是跳过if语句。

    • 问题:**

当TensorFlow模型检测到特定类时,如何执行操作(打印消息、警报等)?
编辑:下面是我给模型输入右侧脸图像时脚本的输出:

Class: 2 Right_Side_Face
Confidence score: 0.84736574
Invalid class name
exiting....
j13ufse2

j13ufse21#

我认为这是因为class_name不是一个完整的字符串,而是一个int + a string:也许用:if str(class_name) == "2 Right_Side_Face":代替if class_name == "2 Right_Side_Face":,以确保在比较之前它是一个完整的字符串,或者只使用索引:if index == 2: print('face the computer')

相关问题