使用MTCNN时TensorFlow中的警告

问题描述

我正在一个项目上进行人脸识别,并且正在使用以下代码

# demonstrate face detection on 5 Celebrity Faces Dataset
from os import listdir
from PIL import Image
from numpy import asarray
from matplotlib import pyplot
from mtcnn.mtcnn import MTCNN

# extract a single face from a given photograph
def extract_face(filename,required_size=(160,160)):
    # load image from file
    image = Image.open(filename)
    # convert to RGB,if needed
    image = image.convert('RGB')
    # convert to array
    pixels = asarray(image)
    # create the detector,using default weights
    detector = MTCNN()
    # detect faces in the image
    results = detector.detect_faces(pixels)
    # extract the bounding Box from the first face
    x1,y1,width,height = results[0]['Box']
    # bug fix
    x1,y1 = abs(x1),abs(y1)
    x2,y2 = x1 + width,y1 + height
    # extract the face
    face = pixels[y1:y2,x1:x2]
    # resize pixels to the model size
    image = Image.fromarray(face)
    image = image.resize(required_size)
    face_array = asarray(image)
    return face_array

# specify folder to plot
#folder = '5-celebrity-faces-dataset/train/ben_afflek/'
folder = '/content/drive/My Drive/ufc-project/5-celebrity-faces-dataset/train/ben_afflek'
i = 1
# enumerate files
for filename in listdir(folder):
    # path
    path = folder + '/' + filename
    # get face
    face = extract_face(path)
    print(i,face.shape)
    # plot
    pyplot.subplot(2,7,i)
    pyplot.axis('off')
    pyplot.imshow(face)
    i += 1
pyplot.show()

我从本教程中获得了以下代码https://machinelearningmastery.com/how-to-develop-a-face-recognition-system-using-facenet-in-keras-and-an-svm-classifier/?unapproved=549711&moderation-hash=6b355b586de2f2ff191df14529849990#comment-549711

它正在工作,但是我收到以下警告:

WARNING:tensorflow:6 out of the last 11 calls to <function Model.make_predict_function..predict_function at 0x7f0016e2eae8> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings Could be due to (1) creating @tf.function repeatedly in a loop,(2) passing tensors with different shapes,(3) passing Python objects instead of tensors. For (1),please define your @tf.function outside of the loop. For (2),@tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3),please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details.

有人知道如何解决吗?

解决方法

每次调用提取面部时,您都在创建检测器。将面部检测器的创建从循环中移出,并将其作为参数传递给函数。 将行检测器= MTCNN()移到extract_face之外,特别是在循环之前。