阿里云图像识别Java调用示例参考

简介: 图像识别服务(Image Recognition)基于大数据和深度学习实现,可精准识别图像中的视觉内容,包括上千种物体标签、数十种常见场景等,包含场景分类、图像打标、鉴黄等在线API服务模块,应用于智能相册管理、图片分类和检索、图片安全监控等场景。

概述

图像识别服务(Image Recognition)基于大数据和深度学习实现,可精准识别图像中的视觉内容,包括上千种物体标签、数十种常见场景等,包含场景分类、图像打标、鉴黄等在线API服务模块,应用于智能相册管理、图片分类和检索、图片安全监控等场景。下面给出使用Java语言分别使用网络图片和本地图片调用场景识别API的示例。


控制台测试

与人脸识别类似,可以参考:阿里云人脸识别使用流程简介

Java Code Sample

使用网络图片测试

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;

//@SuppressWarnings("restriction")
public class ComputerDemo1 {
    /*
     * 计算MD5+BASE64
     */
    public static String MD5Base64(String s) {
        if (s == null)
            return null;
        String encodeStr = "";
        byte[] utfBytes = s.getBytes();
        MessageDigest mdTemp;
        try {
            mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(utfBytes);
            byte[] md5Bytes = mdTemp.digest();
            BASE64Encoder b64Encoder = new BASE64Encoder();
            encodeStr = b64Encoder.encode(md5Bytes);
        } catch (Exception e) {
            throw new Error("Failed to generate MD5 : " + e.getMessage());
        }
        return encodeStr;
    }
    /*
     * 计算 HMAC-SHA1
     */
    public static String HMACSha1(String data, String key) {
        String result;
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = (new BASE64Encoder()).encode(rawHmac);
        } catch (Exception e) {
            throw new Error("Failed to generate HMAC : " + e.getMessage());
        }
        return result;
    }
    /*
     * 等同于javaScript中的 new Date().toUTCString();
     */
    public static String toGMTString(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }
    /*
     * 发送POST请求
     */
    public static String sendPost(String url, String body, String ak_id, String ak_secret) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        int statusCode = 200;
        try {
            URL realUrl = new URL(url);
            /*
             * http header 参数
             */
            String method = "POST";
            String accept = "application/json";
            String content_type = "application/json";
            String path = realUrl.getFile();
            String date = toGMTString(new Date());
            // 1.对body做MD5+BASE64加密
            String bodyMd5 = MD5Base64(body);
            String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
                    + path;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            // 3.得到 authorization header
            String authHeader = "Dataplus " + ak_id + ":" + signature;
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", accept);
            conn.setRequestProperty("content-type", content_type);
            conn.setRequestProperty("date", date);
            conn.setRequestProperty("Authorization", authHeader);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(body);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            statusCode = ((HttpURLConnection)conn).getResponseCode();
            if(statusCode != 200) {
                in = new BufferedReader(new InputStreamReader(((HttpURLConnection)conn).getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (statusCode != 200) {
            throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);
        }
        return result;
    }
    /*
     * GET请求
     */
    public static String sendGet(String url, String ak_id, String ak_secret) throws Exception {
        String result = "";
        BufferedReader in = null;
        int statusCode = 200;
        try {
            URL realUrl = new URL(url);
            /*
             * http header 参数
             */
            String method = "GET";
            String accept = "application/json";
            String content_type = "application/json";
            String path = realUrl.getFile();
            String date = toGMTString(new Date());
            // 1.对body做MD5+BASE64加密
            // String bodyMd5 = MD5Base64(body);
            String stringToSign = method + "\n" + accept + "\n" + "" + "\n" + content_type + "\n" + date + "\n" + path;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            // 3.得到 authorization header
            String authHeader = "Dataplus " + ak_id + ":" + signature;
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", accept);
            connection.setRequestProperty("content-type", content_type);
            connection.setRequestProperty("date", date);
            connection.setRequestProperty("Authorization", authHeader);
            connection.setRequestProperty("Connection", "keep-alive");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            statusCode = ((HttpURLConnection)connection).getResponseCode();
            if(statusCode != 200) {
                in = new BufferedReader(new InputStreamReader(((HttpURLConnection)connection).getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (statusCode != 200) {
            throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        // 发送POST请求示例
        String ak_id = "********"; //用户ak
        String ak_secret = "********"; // 用户ak_secret
        String url = "https://dtplus-cn-shanghai.data.aliyuncs.com/image/scene";
        String body = "{\"type\": \"0\", \"image_url\":\"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1544608444&di=54513735567736d0eaeba7a13aa0421c&src=http://img5q.duitang.com/uploads/item/201411/23/20141123205812_Bircn.jpeg\"}";
        System.out.println("response body:" + sendPost(url, body, ak_id, ak_secret));

    }
}

使用本地图片测试

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;

public class ComputerDemo2 {
    /*
     * 计算MD5+BASE64
     */
    public static String MD5Base64(String s) {
        if (s == null)
            return null;
        String encodeStr = "";
        byte[] utfBytes = s.getBytes();
        MessageDigest mdTemp;
        try {
            mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(utfBytes);
            byte[] md5Bytes = mdTemp.digest();
            BASE64Encoder b64Encoder = new BASE64Encoder();
            encodeStr = b64Encoder.encode(md5Bytes);
        } catch (Exception e) {
            throw new Error("Failed to generate MD5 : " + e.getMessage());
        }
        return encodeStr;
    }
    /*
     * 计算 HMAC-SHA1
     */
    public static String HMACSha1(String data, String key) {
        String result;
        try {
            SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = (new BASE64Encoder()).encode(rawHmac);
        } catch (Exception e) {
            throw new Error("Failed to generate HMAC : " + e.getMessage());
        }
        return result;
    }
    /*
     * 等同于javaScript中的 new Date().toUTCString();
     */
    public static String toGMTString(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
        return df.format(date);
    }
    /*
     * 发送POST请求
     */
    public static String sendPost(String url, String body, String ak_id, String ak_secret) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        int statusCode = 200;
        try {
            URL realUrl = new URL(url);
            /*
             * http header 参数
             */
            String method = "POST";
            String accept = "application/json";
            String content_type = "application/json";
            String path = realUrl.getFile();
            String date = toGMTString(new Date());
            // 1.对body做MD5+BASE64加密
            String bodyMd5 = MD5Base64(body);
            String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date + "\n"
                    + path;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            // 3.得到 authorization header
            String authHeader = "Dataplus " + ak_id + ":" + signature;
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", accept);
            conn.setRequestProperty("content-type", content_type);
            conn.setRequestProperty("date", date);
            conn.setRequestProperty("Authorization", authHeader);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(body);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            statusCode = ((HttpURLConnection)conn).getResponseCode();
            if(statusCode != 200) {
                in = new BufferedReader(new InputStreamReader(((HttpURLConnection)conn).getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (statusCode != 200) {
            throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);
        }
        return result;
    }
    /*
     * GET请求
     */
    public static String sendGet(String url, String ak_id, String ak_secret) throws Exception {
        String result = "";
        BufferedReader in = null;
        int statusCode = 200;
        try {
            URL realUrl = new URL(url);
            /*
             * http header 参数
             */
            String method = "GET";
            String accept = "application/json";
            String content_type = "application/json";
            String path = realUrl.getFile();
            String date = toGMTString(new Date());
            // 1.对body做MD5+BASE64加密
            // String bodyMd5 = MD5Base64(body);
            String stringToSign = method + "\n" + accept + "\n" + "" + "\n" + content_type + "\n" + date + "\n" + path;
            // 2.计算 HMAC-SHA1
            String signature = HMACSha1(stringToSign, ak_secret);
            // 3.得到 authorization header
            String authHeader = "Dataplus " + ak_id + ":" + signature;
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", accept);
            connection.setRequestProperty("content-type", content_type);
            connection.setRequestProperty("date", date);
            connection.setRequestProperty("Authorization", authHeader);
            connection.setRequestProperty("Connection", "keep-alive");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            statusCode = ((HttpURLConnection)connection).getResponseCode();
            if(statusCode != 200) {
                in = new BufferedReader(new InputStreamReader(((HttpURLConnection)connection).getErrorStream()));
            } else {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (statusCode != 200) {
            throw new IOException("\nHttp StatusCode: "+ statusCode + "\nErrorMessage: " + result);
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        // 发送POST请求示例
        String ak_id = "********"; //用户ak
        String ak_secret = "********"; // 用户ak_secret
        String url = "https://dtplus-cn-shanghai.data.aliyuncs.com/image/scene";
        //上传本地图片
        // Request body
        String pic_path = "C:\\Users\\taro.yt\\Desktop\\timg.jpg";

        File picBase64 = new File(pic_path);
        String pic = encodeImageToBase64(picBase64);

        //提出base64编码的换行符问题
        String data = pic.replaceAll("[\\s*\t\n\r]", "");
        data = "'" + data + "'";

        String body = "{\"type\": \"1\", \"content\":"+data+"}";

        System.out.println("response body:" + sendPost(url, body, ak_id, ak_secret));
    }


    /**
     * 将本地图片编码为base64
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String encodeImageToBase64(File file) throws Exception {
        //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
//        loggerger.info("图片的路径为:" + file.getAbsolutePath());
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("图片上传失败,请联系客服!");
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(data);
        return base64;//返回Base64编码过的字节数组字符串
    }
}
测试结果
response body:{"tags":[{"value":"人物","confidence":97.0},{"value":"演出","confidence":12.0},{"value":"其他","confidence":12.0},{"value":"室内","confidence":11.0}],"errno":0,"request_id":"b31aebed-305a-4377-a843-ac4e9d3d30c1"}

参考链接

场景识别API调用说明

相关实践学习
基于函数计算实现AI推理
本场景基于函数计算建立一个TensorFlow Serverless AI推理平台。
相关文章
|
自然语言处理 Java API
阿里云自然语言处理--文本相似度(电商)Java SDK 调用示例
自然语言处理(Natural Language Processing,简称NLP),是为各类企业及开发者提供的用于文本分析及挖掘的核心工具,旨在帮助用户高效的处理文本,已经广泛应用在电商、文娱、司法、公安、金融、医疗、电力等行业客户的多项业务中,取得了良好的效果。文本相似度可以提供不同文本之间相似度的计算,并输出一个介于0到1之间的分数,分数越大则文本之间的相似度越高。可广泛应用于信息检索,新闻推荐、智能客服等场景。使用该服务建议分数不要用于直接判断,可以作为特征,并按照范围进行分桶。本文将使用Java Common SDK 演示文本相似度(电商)服务的快速调用以供参考。
649 0
阿里云自然语言处理--文本相似度(电商)Java SDK 调用示例
|
达摩院 Java 开发工具
Python、Java SDK两种方式调用阿里云人脸检测与五官定位
阿里云视觉智能开放平台基于达摩院自研的人脸人体分析技术,提供人脸检测与五官定位、人脸属性识别、人脸比对、人脸搜索、人体检测、人体属性、行为分析等多种功能,为开发者和企业用户提供高性能高可用的人脸人体识别服务。广泛应用于数字门店、楼宇门禁、身份识别、互动娱乐、IPC摄像头、内容广告等领域。此篇文章简单介绍人脸人体与五官定位python,java两种方式调用。
558 0
Python、Java SDK两种方式调用阿里云人脸检测与五官定位
|
Java API 计算机视觉
阿里云新版人脸识别Java使用示例教程
之前阿里云人脸识别只提供人脸检测,人脸属性及人脸对比三个API接口,关于这方面的介绍及使用细节,可以参考阿里云人脸识别使用流程简介,之前使用的服务地址为:dtplus-cn-shanghai.data.aliyuncs.com。目前新版本加入了1:N人脸查找的功能,新版本还处于公测阶段,服务地址:face.cn-shanghai.aliyuncs.com。下面主要介绍如何使用新版本的地址调用之前的三个API的功能。
2401 0
|
10月前
|
自然语言处理 安全 机器人
Java快速接入Chatgpt简单案例
ChatGPT是一种由OpenAI训练的大型语言模型。它的原理是基于Transformer架构,通过预训练大量文本数据来学习如何生成人类可读的文本,然后通过接受输入并生成输出来实现对话。 ChatGPT的用途非常广泛,可以用于自然语言处理(NLP)任务,如对话生成、问答系统、文本生成等。 如果你想使用ChatGPT,你可以用它来构建对话机器人,回答问题,生成文本等。它的应用非常广泛,可以用于各种场景,如客服、帮助提供者、教育机构等。
260 0
|
自然语言处理 Java 机器人
自然语言处理预训练模型商品评价解析服务-本地生活领域 Java SDK示例
自然语言处理(Natural Language Processing,简称NLP),是为各类企业及开发者提供的用于文本分析及挖掘的核心工具,旨在帮助用户高效的处理文本,已经广泛应用在电商、文娱、司法、公安、金融、医疗、电力等行业客户的多项业务中,取得了良好的效果。可用于搭建内容搜索、内容推荐、舆情识别及分析、文本结构化、对话机器人等智能产品。NLP自学习平台提供了一些预训练的特定领域模型服务。例如:商品评价解析服务、新闻层次分类服务、中文简历抽取、英文简历抽取等,且无需自主标注训练,直接调用API即可使用。本文将使用Java SDK演示商品评价解析服务-本地生活领域的快速调用以供参考。
196 0
|
自然语言处理 Java API
阿里云自然语言处理--文本摘要(电商)Java SDK 调用示例
自然语言处理(Natural Language Processing,简称NLP),是为各类企业及开发者提供的用于文本分析及挖掘的核心工具,旨在帮助用户高效的处理文本,已经广泛应用在电商、文娱、司法、公安、金融、医疗、电力等行业客户的多项业务中,取得了良好的效果。文本摘要服务可以在保证能够反映原文档的重要内容的情况下,尽可能地保持简明扼要,自动抽取输入文本中的关键信息并生成短文本摘要。能让用户在当今世界海量的互联网数据中找到有效的信息,有效缩短检索的时间,提高用户体验。本文将使用Java Common SDK 演示文本摘要(电商)服务的快速调用以供参考。
498 0
阿里云自然语言处理--文本摘要(电商)Java SDK 调用示例
|
自然语言处理 Java API
阿里云自然语言处理--中心词提取(中文)Java SDK 调用示例
自然语言处理(Natural Language Processing,简称NLP),是为各类企业及开发者提供的用于文本分析及挖掘的核心工具,旨在帮助用户高效的处理文本,已经广泛应用在电商、文娱、司法、公安、金融、医疗、电力等行业客户的多项业务中,取得了良好的效果。NLP基础服务中心词提取是基于海量数据,使用电商标题中心词以及类目进行训练,通过给每个词计算一个相关性分数来衡量每个词与句子的相关性程度,进而识别并提取出句子的中心词。适用于提取电商搜索query、标题及其他类似短文本(一般小于25个词)的中心词。本文将使用Java CommonSDK演示中心词提取(中文)服务的快速调用以供参考。
628 0
阿里云自然语言处理--中心词提取(中文)Java SDK 调用示例
|
自然语言处理 Java API
阿里云自然语言处理--词性标注(电商)Java SDK 调用示例
自然语言处理(Natural Language Processing,简称NLP),是为各类企业及开发者提供的用于文本分析及挖掘的核心工具,旨在帮助用户高效的处理文本,已经广泛应用在电商、文娱、司法、公安、金融、医疗、电力等行业客户的多项业务中,取得了良好的效果。通过词性标注服务,用户可以快速的为每一个词附上对应的词性,结合分词服务,可以快速进行更深层次的文本挖掘处理,无需担心新词发现、歧义消除等问题。本文将使用Java CommonSDK演示词性标注(电商)服务的快速调用以供参考。
316 0
阿里云自然语言处理--词性标注(电商)Java SDK 调用示例
|
自然语言处理 Java 开发工具
阿里云机器翻译产品机器批量翻译服务 Java SDK 调用指南
阿里云机器翻译产品下的机器批量翻译服务,支持同时对多段文本进行翻译。本文介绍如何使用机器批量翻译提供的JavaSDK,包括SDK的安装方法及SDK代码示例。
289 0
|
文字识别 Java
java 百度手写文字识别接口配置
java 百度手写文字识别接口配置
128 0