繁体   English   中英

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

[英]Tensorflow - Batch predict on multiple images

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

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

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

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

Output:

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() function 的输入需要作为 Z2EA9510C37F7F89E4941FF75F7F89E4941FF75F62F21CBZ 形状数组(N,224,输入图像 24 数量)给出。

To achieve this, we can stack the N individual numpy arrays of size ( 1, 224, 224, 3) into one array of size ( N, 224, 224, 3) and then pass it to model.predict() function.

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM