更新时间:2023-11-21 GMT+08:00

搜索图片示例

本章节对搜索图片AK/SK方式使用SDK进行示例说明。

搜图图片示例代码只需将AK/SK信息替换为实际AK/SK,代码中可以使用SearchPictureReq类的setPath设置图像的URL,配置完成后运行即可。

  1. 搜索图片调用示例代码如下:
    import com.alibaba.fastjson.JSON;
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.imagesearch.v1.*;
    import com.huaweicloud.sdk.imagesearch.v1.model.*;
    import com.huaweicloud.sdk.imagesearch.v1.region.ImageSearchRegion;
     
    /**
     * 从图片索引库中搜索相似图片
     */
    public class RunSearchPictureSolution {
        
    public static void main(String[] args) {
           // 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全
           // 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK
            String ak = System.getenv("HUAWEICLOUD_SDK_AK");
            String sk = System.getenv("HUAWEICLOUD_SDK_SK");
            
            ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);
           
            ImageSearchClient client = ImageSearchClient.newBuilder()
                .withCredential(auth)
                //设置region, 示例中region为北京四
                .withRegion(ImageSearchRegion.valueOf("cn-north-4"))
                .build();
            RunSearchPictureRequest request = new RunSearchPictureRequest();
            //设置实例名称
            request.setInstanceName("instance-name");
            SearchPictureReq body = new SearchPictureReq();
            //设置图像URL路径
            body.setPath("https://bucketname.obs.cn-north-4.myhuaweicloud.com/search-test.jpg");
            request.setBody(body);
            try {
                RunSearchPictureResponse response = client.runSearchPicture(request);
                System.out.println(JSON.toJSONString(response));
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
  2. 执行示例代码文件,控制台输出搜索图片结果即表示程序执行成功。搜索图片结果输出到控制台。
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    {"count":1,"httpStatusCode":200,"result":[{"path":"https://bucketName.obs.cn-north-4.myhuaweicloud.com/search-test.jpg","sim":1.0,"tags":{}}]}
     
    Process finished with exit code 0