主体识别
引导式阅读
Go
主体识别
作者
c***r
上架时间
2023-11-14 06:27:53

版本说明

本示例基于华为云SDK开发

功能介绍

用户传入图片通过后台算法判断图片主体,并返回主体坐标。

前置条件

申请服务

申请主体识别服务的具体操作步骤请参见《图像识别API参考》的“如何调用API > 申请服务”章节。

获取AK/SK

开发者在使用前需先获取账号的ak、sk、endpoint。

您需要拥有华为云账号以及该账号对应的 Access Key(AK)和 Secret Access Key(SK)。请在华为云控制台“我的凭证-访问密钥”页面上创建和查看您的 AK/SK。更多信息请查看访问密钥。 endpoint 华为云各服务应用区域和各服务的终端节点,详情请查看地区和终端节点。

运行环境

Python3 及其以上版本。

SDK获取和安装

pip install huaweicloudsdkimage

示例代码

主体识别示例代码只需将AK/SK信息替换为实际AK/SK,代码中可以使用ImageMainObjectDetectionReq中的withUrl或withImage方法配置图像信息(image和url参数二选一),示例中以url为例,配置完成后运行即可。

from huaweicloudsdkcore.auth.credentials import BasicCredentials from huaweicloudsdkcore.exceptions.exceptions import ConnectionException from huaweicloudsdkcore.exceptions.exceptions import RequestTimeoutException from huaweicloudsdkcore.exceptions.exceptions import ServiceResponseException from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkimage.v2.image_client import ImageClient from huaweicloudsdkimage.v2.model.image_main_object_detection_req import ImageMainObjectDetectionReq from huaweicloudsdkimage.v2.model.run_image_main_object_detection_request import RunImageMainObjectDetectionRequest from huaweicloudsdkimage.v2.region.image_region import ImageRegion import os class ImageMainObjectDetectionDemo: def __init__(self): pass @staticmethod def main(args): # 设置AK和SK # 认证用的ak和sk直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全; # 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 ak = os.environ["HUAWEICLOUD_SDK_AK"] sk = os.environ["HUAWEICLOUD_SDK_SK"] auth = BasicCredentials( ak=ak, sk=sk ) config = HttpConfig.get_default_config() config.ignore_ssl_verification = True config.proxy_protocol = "http" client = ImageClient.new_builder() \ .with_credentials(credentials=auth) \ .with_region(region=ImageRegion.value_of(region_id="cn-north-4")) \ .with_http_config(config=config) \ .build() request = RunImageMainObjectDetectionRequest() body = ImageMainObjectDetectionReq() # 替换示例中的图像地址 body.url = "图片url地址" request.body = body try: response = client.run_image_main_object_detection(request) print(response) except (ConnectionException, RequestTimeoutException) as e: print(e.err_message) except ServiceResponseException as e: print(e.status_code) print(e.error_code) print(e.error_msg)

参考

更多信息请参考主体识别API

修订记录

发布日期 文档版本 修订说明
2022-09-28 1.0 文档首次发布