旷视人脸识别代码

Posted uninan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了旷视人脸识别代码相关的知识,希望对你有一定的参考价值。

servlet

package com.sxr;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

public class HTTPUtil 
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception 
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) 
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\\r\\n");
            obos.writeBytes("Content-Disposition: form-data; name=\\"" + key
                    + "\\"\\r\\n");
            obos.writeBytes("\\r\\n");
            obos.writeBytes(value + "\\r\\n");
        
        if (fileMap != null && fileMap.size() > 0) 
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) 
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\\r\\n");
                obos.writeBytes("Content-Disposition: form-data; name=\\"" + fileEntry.getKey()
                        + "\\"; filename=\\"" + encode(" ") + "\\"\\r\\n");
                obos.writeBytes("\\r\\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\\r\\n");
            
        
        obos.writeBytes("--" + boundaryString + "--" + "\\r\\n");
        obos.writeBytes("\\r\\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try 
            if (code == 200) 
                ins = conne.getInputStream();
             else 
                ins = conne.getErrorStream();
            
         catch (SSLException e) 
            e.printStackTrace();
            return new byte[0];
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) 
            baos.write(buff, 0, len);
        
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    

    private static String getBoundary() 
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) 
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        
        return sb.toString();
    

    private static String encode(String value) throws Exception 
        return URLEncoder.encode(value, "UTF-8");
    

    public static byte[] getBytesFromFile(File f) 
        if (f == null) 
            return null;
        
        try 
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
         catch (IOException e) 
        
        return null;
    

FaceUtil

package com.sxr;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

public class FaceUtil 


    private static HashMap<String, String> map = new HashMap<>();

    static 
        //读取配置文件当中的内容
        Properties pro = new Properties();
        InputStream in = FaceUtil.class.getResourceAsStream("/api.properties");
        try 
            pro.load(in);
            map.put("api_key", pro.getProperty("API_KEY"));
            map.put("api_secret", pro.getProperty("API_SECRET"));
            map.put("display_name", pro.getProperty("DISPLAY_NAME"));
            map.put("outer_id", pro.getProperty("OUTER_ID"));

         catch (IOException e) 
            System.out.println("配置文件读取错误");
            throw new RuntimeException(e);

        
    

    /**
     * 查询指定的人脸是否在人脸集合faceset中存在
     *
     * @param
     * @return
     * @throws Exception
     */


    public static boolean getDetail() throws Exception 
        String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/getdetail";
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) 
            return false;


        
        return true;
    


    public static boolean createFaceset() throws Exception 
        String url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create";
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) 
            return false;
        
        return true;
    


    public static boolean addFace(String faceToken) throws Exception 
        boolean res = getDetail();//先查询是否有知道的人脸集合
        if (!res) //如果没有就创建
            res = createFaceset();
            if (res) 
                return false;
            

        
        String url = " https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";
        map.put("face_tokens", faceToken);
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) 
            return false;
        
        return true;
    


    /**
     * 查询指定的人脸是否在人脸集合faceset中存在
     *
     * @param faceToken
     * @return
     * @throws Exception
     */
    public static boolean search(String faceToken) throws Exception 
        String url = "https://api-cn.faceplusplus.com/facepp/v3/search";
        map.put("face_token", faceToken);
        byte[] bacd = HTTPUtil.post(url, map, null);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) 
            return false;
        
        //转换为json对象
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONObject thresholdsObject = (JSONObject) jsonObject.get("thresholds");
        double le5 = thresholdsObject.getDoubleValue("le-5");
        //十万分之一的误信率阈值
        JSONArray resArr = (JSONArray) jsonObject.get("results");
        if (resArr != null && resArr.size() >= 1) 
            JSONObject res = (JSONObject) resArr.get(0);
            //取出数组中第一个对象
            double confidence = res.getDoubleValue("confidence");
            if (confidence > le5) 
                return true;
            
        
        return false;
    

    /**
     * 根据传入的图片进行人脸检测
     *
     * @param file 传入人脸图片
     * @return 返回人脸照片,如果为空,说明图片有问题
     */

    public static String detect(File file) throws Exception 
        byte[] buff = HTTPUtil.getBytesFromFile(file);
        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";

        HashMap<String, byte[]> byteMap = new HashMap<>();

//        map.put("return_landmark", "1");
//        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_file", buff);
        byte[] bacd = HTTPUtil.post(url, map, byteMap);
        //符合json格式的字符串
        String str = new String(bacd);
        //转换为json对象
        System.out.println(str);
        if (str.indexOf("error_message") != -1) 
            System.out.println("请求发生错误");
            return null;
        
        JSONObject jsonObject = JSONObject.parseObject(str);
        int num = jsonObject.getIntValue("face_num");
        if (num == 1) 
            JSONArray array = (JSONArray) jsonObject.get("faces");
            JSONObject face = (JSONObject) array.get(0);
            String faceToken = face.getString("face_token");
            return faceToken;
        

        return null;
    

HTTPUtil

package com.sxr;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

public class HTTPUtil 
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();

    public static byte[] post(String url, HashMap<String, String> map, HashMap<String, byte[]> fileMap) throws Exception 
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) 
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\\r\\n");
            obos.writeBytes("Content-Disposition: form-data; name=\\"" + key
                    + "\\"\\r\\n");
            obos.writeBytes("\\r\\n");
            obos.writeBytes(value + "\\r\\n");
        
        if (fileMap != null && fileMap.size() > 0) 
            Iterator fileIter = fileMap.entrySet().iterator();
            while (fileIter.hasNext()) 
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\\r\\n");
                obos.writeBytes("Content-Disposition: form-data; name=\\"" + fileEntry.getKey()
                        + "\\"; filename=\\"" + encode(" ") + "\\"\\r\\n");
                obos.writeBytes("\\r\\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\\r\\n");
            
        
        obos.writeBytes("--" + boundaryString + "--" + "\\r\\n");
        obos.writeBytes("\\r\\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try 
            if (code == 200) 
                ins = conne.getInputStream();
             else 
                ins = conne.getErrorStream();
            
         catch (SSLException e) 
            e.printStackTrace();
            return new byte[0];
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while ((len = ins.read(buff)) != -1) 
            baos.write(buff, 0, len);
        
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    

    private static String getBoundary() 
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; ++i) 
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        
        return sb.toString();
    

    private static String encode(String value) throws Exception 
        return URLEncoder.encode(value, "UTF-8");
    

    public static byte[] getBytesFromFile(File f) 
        if (f == null) 
            return null;
        
        try 
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1)
                out.write(b, 0, n);
            stream.close();
            out.close();
            return out.toByteArray();
         catch (IOException e) 
        
        return null;
    

TestMain

package com.sxr;

import java.io.*;

public class TestMain


public static void main(String[] args)

// File file = new File("C:\\\\Users\\\\双休日\\\\Desktop\\\\image_file\\\\a22.jpg");
// try
// String faceToken = FaceUtil.detect(file);
// System.out.println(faceToken);
// boolean res = FaceUtil.search(faceToken);
// System.out.println("查找结果:" + res);
// FaceUtil.addFace(faceToken);
// res = FaceUtil.search(faceToken);
// System.out.println("查找结果:" + res);
//// boolean res = FaceUtil.getDetail();
//// System.out.println("查找结果:" + res);
//// if (res == false)
//// res = FaceUtil.createFaceset();
//// System.out.println("创建的faceset--outer_id:test"+res);
////
//// res = FaceUtil.getDetail();
//// System.out.println("查找结果:" + res);
//
// catch (Exception e)
// throw new RuntimeException(e);
//
//

File file = new File("C:\\\\Users\\\\双休日\\\\Desktop\\\\image_file\\\\a1.jpg");
try
String str = FaceUtil.detect(file);//人脸检测
System.out.println("face_token:" + str);
//添加一个人脸到集合中
boolean addRes = FaceUtil.addFace(str);
System.out.println("添加结果:" + addRes);
boolean res = FaceUtil.search(str);//人脸搜索
System.out.println("搜索结果:" + res);
//获取人脸的集合
// res = FaceUtil.getDetail();

// if (!res) //如果没有该集合,就创建一个
// res = FaceUtil.createFaceset();
// System.out.println("如果么有指定的人脸集合,则创建新的");
//
// System.out.println("outer_id为linaFaceset的人脸集合:" + res);

catch (Exception e)
throw new RuntimeException(e);



aip.properties
API_KEY=自己的key
API_SECRET=自己的value
DISPLAY_NAME=FaceSet
OUTER_ID=FaceSet

 

Python人脸识别最佳教材典范,40行代码搭建人脸识别系统!

Face Id是一款高端的人脸解锁软件,官方称:“在一百万张脸中识别出你的脸。”百度、谷歌、腾讯等各大企业都花费数亿来鞭策人工智能的崛起,而实际的人脸识别技术是否有那么神奇?

技术分享图片

绿帽识别器

固然是没有的!万万别再当一只井底之蛙!技术分享图片

互联网火速的发展,网络上大量Python程序员共享的各类资源库,人脸识别早就是各位程序员必备技能之一了,一点也不神奇。

如今只需用Python的数四十行代码就可以完成人脸定位!小编用马蓉照片做一个五官定位!固然python库使用到人工智能定位五官。让机器学习上千张人脸来进行特征提取。然后用这个模子在新的照片中自动找出五官!

技术分享图片

五官定位

开发环境:

Python 3 ;

Windows 7或MacOS,以及Linux等所有系统;

一个摄像头、PyCharm;

技术分享图片

技术分享图片

安装所必要的包

项目python代码:

技术分享图片

技术分享图片

技术分享图片

技术分享图片

技术分享图片

末了打印出脸部五官的详细坐标,用线条描绘脸部的详细特征。

看小编自拍照的效果:

技术分享图片

是不是很棒棒?用了短短不到40行的python代码就完成了人脸面部特征定位的使命,是不是很有造诣感呢?

固然这只是非常傻瓜的入门人脸识别,若是想深入得学习,请关注我。

技术分享图片

以上是关于旷视人脸识别代码的主要内容,如果未能解决你的问题,请参考以下文章

AI落地步入深水区 , 旷视依图云从商汤该学会赚钱了

iOS 使用百度的人脸识别登录验证,解决认证失败在头像页面继续识别认证问题

ECCV 2018 | 旷视科技提出GridFace:通过学习局部单应变换实现人脸校正

系列视频AI产品 之 图像识别

Python人脸识别最佳教材典范,40行代码搭建人脸识别系统!

40行代码的人脸识别实践