Skip to main content
 首页 » 编程设计

python之谷歌云视觉 api 检测到不同数量的标签

2025年05月04日24落叶无声

根据 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 个标签。

为什么这些方法各不相同?我在这里缺少什么?

请您参考如下方法:

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

detect_labels() 的文档

Help on method detect_labels in module google.cloud.vision.image:

detect_labels(self, limit=10) method of google.cloud.vision.image.Image instance

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