人脸识别_人脸识别_准确率99.99%_免费试用-百度AI开放平台https://ai.baidu.com/tech/face
1、导入依赖
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.8.0</version>
</dependency>
2、Propeties属性类
@Data
@ConfigurationProperties("aip")// 指定yml文件全路径,获取属性
public class AipFaceProperties {
private String appId;
private String apiKey;
private String secretKey;
}
3、定义模板类
public class AipFaceTemplate {
private AipFaceProperties properties;
public AipFaceTemplate(AipFaceProperties properties) {
this.properties = properties;
}
/**
* 根据上传的图片,校验是否包含人脸
* @param body 图片字节数组
* @return true 人脸; false 非人脸
*/
public boolean detect(byte[] body) {
AipFace client = new AipFace(properties.getAppId(), properties.getApiKey(), properties.getSecretKey());
// 传入可选参数调用接口
HashMap<String, String> options = new HashMap<String, String>();
options.put("face_field", "age");
options.put("max_face_num", "2");
options.put("face_type", "LIVE");
options.put("liveness_control", "LOW");
String imageType = "BASE64";
String image = Base64Util.encode(body);
// 人脸检测
JSONObject res = client.detect(image, imageType, options);
int code = res.getInt("error_code");
return code == 0;
}
}
4、自动配置类
@Configuration
//自动的读取yml中配置信息,并赋值到AipFaceProperties对象中,将此对象存入容器
@EnableConfigurationProperties({
AipFaceProperties.class
})
public class TanhuaAutoConfiguration {
@Bean
public AipFaceTemplate aipFaceTemplate(AipFaceProperties properties) {
return new AipFaceTemplate(properties);
}
}
5、application.yml配置
#阿里云信息配置
aip:
appId:
apiKey:
secretKey:
测试:
/**
* 测试人脸检测测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class AipFaceTest {
@Autowired
private AipFaceTemplate template;
@Test
public void testAip() throws IOException {
String fileName = "D:\\123.jpg";// 图片路径
File file = new File(fileName);
boolean detect = template.detect(Files.readAllBytes(file.toPath()));
System.out.println("是否人脸 = " + detect);
}
}