使用Google Cloud Vision API生成图像标注报错:无enums属性
解决Google Cloud Vision API的AttributeError: module 'google.cloud.vision' has no attribute 'enums'错误
这个错误是因为新版Google Cloud Vision Python客户端库(v1版本)调整了枚举类型的结构,enums不再挂载在google.cloud.vision模块下。可以通过以下两种方式修复:
方法1:使用google.cloud.vision_v1中的枚举类
修改导入和feature类型的引用:
from google.cloud import vision from google.cloud.vision_v1 import types, Feature client = vision.ImageAnnotatorClient.from_service_account_json('service_account_key.json') file_name = 'Images/man.jpg' with open(file_name, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.annotate_image({ 'image': image, 'features': [{'type': Feature.Type.LABEL_DETECTION}] }) captions = [] for annotation in response.label_annotations: captions.append(annotation.description) print("Generated captions for the image:") for caption in captions: print(caption)
方法2:直接使用字符串常量
Vision API的features.type字段支持直接传入字符串值,这是更简洁的写法:
from google.cloud import vision from google.cloud.vision_v1 import types client = vision.ImageAnnotatorClient.from_service_account_json('service_account_key.json') file_name = 'Images/man.jpg' with open(file_name, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) response = client.annotate_image({ 'image': image, 'features': [{'type': 'LABEL_DETECTION'}] }) captions = [] for annotation in response.label_annotations: captions.append(annotation.description) print("Generated captions for the image:") for caption in captions: print(caption)
两种方法都可以解决错误,推荐第二种,代码更简洁且避免枚举类的导入问题。
内容的提问来源于stack exchange,提问作者Touseef Ahmed
相关产品推荐
相关产品推荐

