我正在使用Google Cloud Vision检测图像中的面部。今天早些时候,我的代码运行良好。该代码应创建一个JSON字符串,以解释图像是否带有面部,如何确定Google视觉以及是否存在异常。但是,现在它给了我一条错误消息,提示我很难调试。该代码如下所示:
import io
import os
import json
# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types
class Face_Detector:
# Constructor for Face Detector
def __init__(self, im):
self.im_file = im
# Creates String in Json format given whether a face was detected
# the confidence if yes, and the name of an exception if one was triggered
# (f_d is false if an exception is triggered)
# (con is None if f_d is false)
# (ex is None if an exception is not triggered)
def formatJson(self, f_d, con, ex):
# Generates json String
dic = {
"face_detected" : f_d,
"confidence" : con,
"exception" : ex
}
jsonA = json.dumps(dic);
return jsonA
# Checks image to see if a face exists
def detect_face(self):
# vairbles to be used in Json
# is face detected
f_d = False
# with what ertainty
con = None
# if there is an exception, displays which one
ex = None
try:
# Creates an environment variable
credential_path = "C:\\Users\\Nick\\Desktop\\Proj1-7f68a23c3dd0.json"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
# Uses object field to define local variable
im_file = self.im_file
# Checks for valid file type
if(not (im_file[-4:] == ".jpg" or im_file[-4:] == ".png" or im_file[-5:] == ".jpeg")):
ex = "Invalid file type."
return Face_Detector.formatJson(self, f_d, con, ex)
# Checks for images that are too large or too small
im_size = os.stat(im_file).st_size
if(im_size == 0):
ex = "Image file size of 0."
return Face_Detector.formatJson(self, f_d, con, ex)
elif(im_size > 10485760):
ex = "Exceeds image file size limit of 10MB."
return Face_Detector.formatJson(self, f_d, con, ex)
# Instantiates a client
client = vision.ImageAnnotatorClient()
# Concatenates the service key address and the image file address
file_name = os.path.join(
os.path.dirname("C:\\Users\\Nick\\Desktop\\<ProjectName>"),
im_file)
# Loads the image into RAM
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
# Makes data type compatable with the Google Cloud API
image = types.Image(content=content)
# Performs face detection
response = client.face_detection(image=image)
faces = response.face_annotations
# Checks for the existance of face and confidence
for face in faces:
f_d = True
con = face.detection_confidence
return Face_Detector.formatJson(self, f_d, con, ex)
except FileNotFoundError:
ex = "File Not Found."
return Face_Detector.formatJson(self, f_d, con, ex)
im = r"C:\\Users\\Nick\\Desktop\\Images\\Face2.jpg"
i = Face_Detector(im)
print(i.detect_face())
截至目前,似乎正在产生此错误:
Traceback (most recent call last):
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\google\api_core\grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\grpc\_channel.py", line 549, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\grpc\_channel.py", line 466, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.', '{\n "error": "invalid_grant",\n "error_description": "Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems."\n}')"
debug_error_string = "{"created":"@1553027287.140000000","description":"Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.', '{\n "error": "invalid_grant",\n "error_description": "Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems."\n}')","file":"src/core/lib/security/credentials/plugin/plugin_credentials.cc","file_line":79,"grpc_status":14}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Nick\Desktop\Python Stuff\Face_Detector.py", line 97, in <module>
print(i.detect_face())
File "C:\Users\Nick\Desktop\Python Stuff\Face_Detector.py", line 81, in detect_face
response = client.face_detection(image=image)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\google\cloud\vision_helpers\decorators.py", line 101, in inner
response = self.annotate_image(request, retry=retry, timeout=timeout)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\google\cloud\vision_helpers\__init__.py", line 72, in annotate_image
r = self.batch_annotate_images([request], retry=retry, timeout=timeout)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\google\cloud\vision_v1\gapic\image_annotator_client.py", line 234, in batch_annotate_images
request, retry=retry, timeout=timeout, metadata=metadata
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\google\api_core\gapic_v1\method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python36\lib\site-packages\google\api_core\grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.ServiceUnavailable: 503 Getting metadata from plugin failed with error: ('invalid_grant: Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems.', '{\n "error": "invalid_grant",\n "error_description": "Invalid JWT: Token must be a short-lived token (60 minutes) and in a reasonable timeframe. Check your iat and exp values and use a clock with skew to account for clock differences between systems."\n}')
[Finished in 1.6s]
有人可以帮我解决这个问题吗?这是我第一次使用Google Cloud Vision。