Commit c2a54915 by 徐甲彬

增加百度图像识别接口

1 parent b62f49b0
package com.dookay.cihai.core;
import com.dookay.coral.common.core.CoralCommonCoreMarker;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
......@@ -11,7 +12,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
CoralCommonCoreMarker.class,
CiHaiCoreApplication.class
})
@MapperScan(basePackageClasses = CiHaiCoreApplication.class)
public class CiHaiCoreApplication {
public static void main(String[] args) {
......
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.imageclassify.AipImageClassify;
import com.baidu.aip.util.Base64Util;
import com.dookay.cihai.core.aip.config.AipProperties;
import com.dookay.cihai.core.aip.enums.ImageInputTypeEnum;
import com.dookay.cihai.core.aip.model.ImageResult;
import com.dookay.coral.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.plexus.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
/**
* 图片识别客户端
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Component
@Slf4j
public class AipImageClassifyClient {
//设置APPID/AK/SK
public static final String APP_ID = "10492760";
public static final String API_KEY = "TPo1FLFn3cIuEAyvsjG2jpC4";
public static final String SECRET_KEY = "YUGcqkGioxrceK4CgD3wB90vmmG7KzRf";
/**
* 获取动物图片识别结果列表,可能会有多个结果
* @param
* @author luxor
* @date 2017/12/7
*/
private List<ImageResult> getAnimalDetect(String image, ImageInputTypeEnum typeEnum) throws JSONException {
// 初始化一个AipImageClassifyClient
AipImageClassify client = new AipImageClassify(APP_ID, API_KEY, SECRET_KEY);
JSONObject res;
// 参数为本地图片路径
if(typeEnum == ImageInputTypeEnum.PATH){
res = client.animalDetect(image, new HashMap<String, String>());
}else{
byte[] file = Base64Utils.decodeFromString(image);
res = client.animalDetect(file, new HashMap<String, String>());
log.info(image);
}
// 调用接口
return parseResult(res);
}
/**
* 获取动物图片识别结果列表,可能会有多个结果
* @param
* @author luxor
* @date 2017/12/7
*/
private List<ImageResult> getPlantDetect(String image, ImageInputTypeEnum typeEnum) throws JSONException {
// 初始化一个AipImageClassifyClient
AipImageClassify client = new AipImageClassify("10492760", "TPo1FLFn3cIuEAyvsjG2jpC4", "YUGcqkGioxrceK4CgD3wB90vmmG7KzRf");
JSONObject res;
// 参数为本地图片路径
if(typeEnum == ImageInputTypeEnum.PATH){
res = client.plantDetect(image, new HashMap<String, String>());
}else{
byte[] file = Base64Utils.decodeFromString(image);
res = client.plantDetect(file, new HashMap<String, String>());
log.info(image);
}
// 调用接口
return parseResult(res);
}
/**
* 处理返回结果
* @param
* @author luxor
* @date 2017/12/7
*/
private List<ImageResult> parseResult(JSONObject res) throws JSONException {
if(res.has("error_code")){
log.info("图像识别错误:"+res.toString(2));
throw new ServiceException("图像识别错误:"+res.toString(2));
}else{
List<ImageResult> imageResultList = new ArrayList<>();
JSONArray jsonArray = res.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ImageResult imageResult = new ImageResult();
imageResult.setName(jsonObject.getString("name"));
imageResult.setScore(jsonObject.getDouble("score"));
imageResultList.add(imageResult);
}
return imageResultList;
}
}
/**
* 获取单个图片识别结果,根据置信度从高到底排序
* @param
* @author luxor
* @date 2017/12/7
*/
public ImageResult getImageResult(String imageBase64) throws JSONException {
if(StringUtils.isBlank(imageBase64)){
return new ImageResult();
}
String image = imageBase64.replace("data:image/png;base64,","")
.replace("data:image/jpg;base64,","")
.replace("data:image/jpeg;base64,","");
log.info("image:"+image);
List<ImageResult> imageResultList = this.getAnimalDetect(image,ImageInputTypeEnum.BASE64);
List<ImageResult> imageResultList2 = this.getPlantDetect(image,ImageInputTypeEnum.BASE64);
imageResultList.addAll(imageResultList2);
log.info(JSON.toJSONString(imageResultList));
return imageResultList.stream().filter(x->x.getScore()<0.99).sorted(Comparator.comparing(ImageResult::getScore).reversed()).findFirst().orElse(new ImageResult());
}
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip.enums;
import com.dookay.coral.common.core.enums.IEnum;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
public enum ImageInputTypeEnum implements IEnum {
PATH(1, "本地路径"),
BASE64(2,"base64图像数据");
private int value;
private String description;
ImageInputTypeEnum(int value, String description) {
this.value = value;
this.description = description;
}
@Override
public int getValue() {
return value;
}
@Override
public String getDescription() {
return description;
}
public static ImageInputTypeEnum valueOf(Integer value) {
ImageInputTypeEnum[] values = ImageInputTypeEnum.values();
for (ImageInputTypeEnum item : values) {
if (item.value == value) {
return item;
}
}
return null;
}
}
/*****************************************
* *
* @dookay.com Internet make it happen *
* ----------- ----------------------- *
* dddd ddddd Internet make it happen *
* o o o Internet make it happen *
* k k k Internet make it happen *
* a a a Internet make it happen *
* yyyy yyyyy Internet make it happen *
* ----------- ----------------------- *
* Code is far away from bug with the *
* animal protecting *
* 神兽保佑,代码无bug  *
* *
****************************************/
package com.dookay.cihai.core.aip.model;
import lombok.Data;
/**
* 图片识别结果
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Data
public class ImageResult {
private String name;
private Double score;
}
package com.dookay.cihai.core.aip;
import com.alibaba.fastjson.JSON;
import com.dookay.cihai.core.CihaiCoreApplicationTests;
import com.dookay.cihai.core.aip.model.ImageResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import static org.junit.Assert.*;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/12/7
*/
@Slf4j
public class AipImageClassifyClientTest extends CihaiCoreApplicationTests {
@Autowired
private AipImageClassifyClient aipImageClassifyClient;
@Test
public void getImageResult() throws Exception {
File file = ResourceUtils.getFile("classpath:daxiang.txt");
System.out.println(txt2String(file));
String image = txt2String(file);
log.info(image);
ImageResult imageResult = aipImageClassifyClient.getImageResult(image);
Boolean flag = imageResult.getScore()<0.99;
log.info(JSON.toJSONString(imageResult));
}
/**
* 读取txt文件的内容
* @param file 想要读取的文件对象
* @return 返回文件内容
*/
public static String txt2String(File file){
StringBuilder result = new StringBuilder();
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result.append(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result.toString();
}
}
\ No newline at end of file
This diff could not be displayed because it is too large.
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!