如何修正Python代码从Google Cloud Vision API获取最高占比主色调
修复Google Cloud Vision API主色调提取代码,确保获取像素占比最高的颜色
Google Cloud Vision API返回的dominant_colors.colors列表默认是按像素占比从高到低排序的,GCP界面属性标签里最左侧的颜色就是这个列表的第一个元素。你的现有代码通过循环找最大值的逻辑冗余,还可能因变量初始化或遍历逻辑出现偶发错误,直接取第一个元素就能精准匹配界面显示的结果。
修改后的代码
def dominant_color(image): response = client.image_properties(image=image) props = response.image_properties_annotation # 检查是否返回了主色调数据 if not props.dominant_colors or not props.dominant_colors.colors: raise ValueError("未检测到图片的主色调数据") # 直接取占比最高的第一个颜色(和GCP界面最左侧一致) top_color = props.dominant_colors.colors[0] red = int(top_color.color.red) green = int(top_color.color.green) blue = int(top_color.color.blue) if response.error.message: raise Exception( f'{response.error.message}\n' 'For more info on error messages, check: ' 'https://cloud.google.com/apis/design/errors' ) return red, green, blue creds = service_account.Credentials.from_service_account_file(r'xxxx.json') #credentials client = vision.ImageAnnotatorClient(credentials=creds,)
说明
- 去掉冗余的最大值遍历逻辑,直接调用排序后的第一个元素,和GCP界面显示完全对齐
- 增加空值检查,避免因图片无有效主色调数据导致的索引错误
- 变量命名更清晰,提升代码可读性
示例输出
Image_name Red Green Blue k1.jpg 240 125 16
内容的提问来源于stack exchange,提问作者Sasi
相关产品推荐
相关产品推荐

