如何处理 Python 中的 ServiceRequestError

How to handle ServiceRequestError in Python

我正在研究人脸检测,使用 Kairos API,同时使用以下代码编写此程序

def Test():
    image = cap.read()[1]
    cv2.imwrite("opencv_frame.png",image)
    recognized_faces = kairos_face.verify_face(file="filepath/opencv_frame.png", subject_id='David',gallery_name='Test')
    print(recognized_faces)
    if recognized_faces.get('images')[0].get('transaction').get('status') !='success':
        print('No')
    else:
        print('Hello', recognized_faces.get('images')[0].get('transaction').get('subject_id'))

如果我直视相机,效果很好,但如果我转过头,它就会中断并出现以下响应。

kairos_face.exceptions.ServiceRequestError: {'Errors': [{'Message': 'no faces found in the image', 'ErrCode': 5002}]}

如何处理异常错误,并强制测试函数保持 运行 直到检测到人脸。

你就不能捕捉异常然后重试吗?

def Test():
    captured = False
    while not captured:
        try:
            image = cap.read()[1]
            cv2.imwrite("opencv_frame.png",image)
            recognized_faces = kairos_face.verify_face(file="filepath/opencv_frame.png", subject_id='David',gallery_name='Test')
            captured = True
        except kairos_face.exceptions.ServiceRequestError:
            pass # optionally wait
    print(recognized_faces)
    if recognized_faces.get('images')[0].get('transaction').get('status') !='success':
        print('No')
    else:
        print('Hello', recognized_faces.get('images')[0].get('transaction').get('subject_id'))