python - Tensorflow - 对多个图像进行批量预测

标签 python tensorflow keras

我有一个 faces 列表,其中列表的每个元素都是一个形状为 ( 1, 224, 224, 3) 的 numpy 数组,即一张人脸图像。我有一个模型,其输入形状为 (None, 224, 224, 3),输出形状为 (None, 2)

现在我想对 faces 列表中的所有图像进行预测。当然,我可以遍历列表并一个一个地获得预测,但我想批量处理所有图像,只使用一次调用 model.predict() 来更快地获得结果。

如果我像现在这样直接传递人脸列表(完整代码在最后),我只会得到第一张图像的预测。

print(f"{len(faces)} faces found")
print(faces[0].shape)
maskPreds = model.predict(faces)
print(maskPreds)

输出:

3 faces found
(1, 224, 224, 3)
[[0.9421933  0.05780665]]

但是 3 张图像的 maskPreds 应该是这样的:

[[0.9421933  0.05780665], 
 [0.01584494 0.98415506], 
 [0.09914105 0.9008589 ]] 

完整代码:

from tensorflow.keras.models import load_model
from cvlib import detect_face
import cv2
import numpy as np

def detectAllFaces(frame):
    dets = detect_face(frame)
    boxes = dets[0]
    confidences = dets[1]
    faces = []

    for box, confidence in zip(boxes, confidences):
        startX, startY, endX, endY = box
        cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 0), 1)
        face = frame[startY:endY, startX:endX]
        face = cv2.resize(face, (224, 224))
        face = np.expand_dims(face, axis=0) # convert (224,224,3) to (1,224,224,3)
        faces.append(face)

    return faces, frame

model = load_model("mask_detector.model")
vs = cv2.VideoCapture(0)
model.summary()

while True:
    ret, frame = vs.read()
    if not ret:
        break            
    faces, frame = detectAllFaces(frame)

    if len(faces):
        print(f"{len(faces)} faces found")
        maskPreds = model.predict(faces) # <==========
        print(maskPreds) 

    cv2.imshow("Window", frame)
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyWindow("Window")
vs.release()

注意:如果我不将每个图像从 (224, 224, 3) 转换为 ( 1, 224, 224, 3),tensorflow 会抛出错误,指出输入尺寸不匹配。

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (224, 224, 3)

如何实现批量预测?

最佳答案

在这种情况下,model.predict() 函数的输入需要作为形状为 (N, 224, 224, 3) 的 numpy 数组给出,其中 N是输入图像的数量。

为此,我们可以堆叠 N 个大小为( 1, 224, 224, 3) 的numpy 数组 到一个数组中大小为 ( N, 224, 224, 3),然后将其传递给 model.predict() 函数。

maskPreds = model.predict(np.vstack(faces))

关于python - Tensorflow - 对多个图像进行批量预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61746477/

相关文章:

python - 将 url 链接解析为列表

python - 如何在 Python 中发送带有 pdf 附件的电子邮件?

python - 在 MAC OS X 10.9 上安装 NLTK 真的很困难

TensorFlow:tf.contrib.data API 中的 "Cannot capture a stateful node by value"

python - 为什么在 Keras 子类化 API 中,永远不会调用 call 方法,而是通过调用此类的对象来传递输入?

python - tensorflow2.0还有参数 'trainable'吗?

python - Keras 模型评估()与预测类()给出不同的精度结果

python - Keras:显示多标签回归中每个标签的损失

keras - 如果我们需要更改 input_shape,为什么我们需要 include_top=False?

Python 单元测试调用困惑