根据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个标签。
为什么这些方法都有所不同?我在这里缺少什么?
答案 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