Google Cloud vision api会检测到不同数量的标签

时间:2017-07-22 20:40:13

标签: python google-cloud-vision

根据this page,以下代码段会返回5个标签:

from google.cloud import vision
url = 'https://farm9.staticflickr.com/8215/8267748261_ea142faf5e.jpg'

client = vision.ImageAnnotatorClient()
client.label_detection({'source': {'image_uri': url}}) # yields 5

当我按照here所述进行操作时,我会得到10个标签:

client = vision.Client()
image = client.image(source_uri=url)
labels = image.detect_labels() # yields 10

当我使用Cloud Vision demo page时,我会为同一张图片获得18个标签。

为什么这些方法都有所不同?我在这里缺少什么?

1 个答案:

答案 0 :(得分:5)

TL; DR - image.detect_labels采用可选的limit参数,其默认值为10,因此您只能获得10个标签在你的第二个版本。如果您将限制增加到高于18的值,您将获得与您在Cloud Vision演示页面上观察到的结果相同的结果。

detect_labels()

的文档
  

模块detect_labels中方法google.cloud.vision.image的帮助:

     

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()

的工作示例

使用5时,您可以设置最大结果数(此处默认为ImageAnnotatorClient),尽管请求稍微冗长:

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