TL;DR - image.detect_labels 采用可选的 limit 参数,其默认值为 10,因此您在第二个版本中仅获得 10 标签。如果您将限制增加到高于18 的值,您将获得与您在 Cloud Vision 演示页面上观察到的结果相同的结果。
detect_labels() 的文档
模块google.cloud.vision.image中方法detect_labels的帮助:
detect_labels(self, limit=10)方法
google.cloud.vision.image.Image实例
Detect labels that describe objects in an image.
:type limit: int
:param limit: The maximum number of labels to try and detect.
:rtype: list
:returns: List of :class:`~google.cloud.vision.entity.EntityAnnotation`
使用Image.detect_labels() 的工作示例
试试这个:
from google.cloud import vision
IMAGE_URL = 'https://farm9.staticflickr.com/8215/8267748261_ea142faf5e.jpg'
vision_client = vision.Client()
image = vision_client.image(source_uri=IMAGE_URL)
labels = image.detect_labels(limit=100)
print('Label Count: {0}'.format(len(labels))) # Result is 18
print('Labels:')
for label in labels:
print(label.description)
使用ImageAnnotatorClient.annotate_image() 的工作示例
您也可以在使用ImageAnnotatorClient 时设置最大结果数(此处默认为5),尽管请求会有点冗长:
from google.cloud import vision
IMAGE_URL = 'https://farm9.staticflickr.com/8215/8267748261_ea142faf5e.jpg'
annot_client = vision.ImageAnnotatorClient()
request_image = {'source': {'image_uri': IMAGE_URL}}
label_detection_feature = {
'type': vision.enums.Feature.Type.LABEL_DETECTION, 'max_results': 100}
request_features = [label_detection_feature]
response = annot_client.annotate_image(
{'image': request_image, 'features': request_features})
print('Label Count: {0}'.format(len(response.label_annotations))) # Result is 18
使用ImageAnnotatorClient.label_detection() 的示例
如果你直接使用ImageAnnotatorClient.label_detection(),它总是默认最多5结果,似乎没有办法配置这个限制。
from google.cloud import vision
IMAGE_URL = 'https://farm9.staticflickr.com/8215/8267748261_ea142faf5e.jpg'
annot_client = vision.ImageAnnotatorClient()
response = annot_client.label_detection(image={'source': {'image_uri': IMAGE_URL}})
print('Label Count: {0}'.format(len(response.label_annotations))) # Result is 5