当使用Google的API时,可能会遇到Annotate()在响应中返回重复项的问题。这通常是因为Annotate()在对每个图像进行注解时,会返回多个不同的面部检测位置。解决此问题的方法是使用Python中的集合(set)来删除重复项。以下是一个示例代码:
from google.cloud import vision
# 客户端连接服务端
client = vision.ImageAnnotatorClient()
# 读取图像
with open('image.jpg', 'rb') as image_file:
content = image_file.read()
# 创建图像实例
image = vision.Image(content=content)
# 获取面部注解
response = client.face_detection(image=image)
faces = response.face_annotations
# 使用集合(set)来去重
unique_faces = set(faces)
# 输出注解结果
for face in unique_faces:
print(face)
在上述代码中,我们使用了Python中的set()函数来创建一个集合,以存储面部注解结果并去重。然后我们循环输出每个注解结果。这样就可以确保我们不会重复记录相同的面部检测位置。