Java通过摄像头捕捉人脸识别和已有的照片进行相似度比对(OpenCV + face++)

好像是face++,又好像不是,具体的忘记了,为了以后自己可以好找代码:

package com.common.face;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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;

import javax.net.ssl.SSLException;

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

/**
 * 得到pic的face_token
 */
public class FacePlus {
    public static void main(String[] args) throws Exception{

        File file = new File("C:\\Users\\Administrator\\Desktop\\abc\\erwa.jpg");
        byte[] buff = getBytesFromFile(file);
        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, byte[]> byteMap = new HashMap<>();
        map.put("api_key", "NCZxjJtNcTsQJLNc_zhEp6OeWyC3OgW6");
        map.put("api_secret", "X8ymk7AKMFWrWJP6RHr_NZOO9eZmAvzw");
        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);
        try{
            byte[] bacd = post(url, map, byteMap);
            String str = new String(bacd);
            System.out.println(str);
            
            JSONObject jsonObject = JSONObject.parseObject(str);
            JSONArray jsonArray = (JSONArray) jsonObject.get("faces");
            JSONObject jsonfac = (JSONObject) jsonArray.get(jsonArray.size()-1);
            String face_token = (String) jsonfac.get("face_token");
            System.out.println(face_token);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String getFaceId(byte[] buff){
        String url = "https://api-cn.faceplusplus.com/facepp/v3/detect";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, byte[]> byteMap = new HashMap<>();
        map.put("api_key", "NCZxjJtNcTsQJLNc_zhEp6OeWyC3OgW6");
        map.put("api_secret", "X8ymk7AKMFWrWJP6RHr_NZOO9eZmAvzw");
        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);
        String face_token = "";
        try{
            byte[] bacd = post(url, map, byteMap);
            String str = new String(bacd);
            System.out.println("str:"+str);
            
            JSONObject jsonObject = JSONObject.parseObject(str);
            JSONArray jsonArray = (JSONArray) jsonObject.get("faces");
            int size = jsonArray.size();
            System.out.println("size:"+size);
            if(size == 0){
                return "-1";
            }
            JSONObject jsonfac = (JSONObject) jsonArray.get(size-1);
            face_token = (String) jsonfac.get("face_token");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return face_token;
    }
    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();
    protected 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;
    }
}

 

package com.common.face;

import java.awt.Graphics;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.ml.SVM;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.objdetect.HOGDescriptor;
import org.opencv.videoio.VideoCapture;
import org.opencv.videoio.Videoio;

import com.alibaba.fastjson.JSONObject;
/**
 * 基础运行  
 * @author Administrator
 *
 */
public class CaptureBasic extends JPanel {  
      
    private BufferedImage mImg;  
      
    private BufferedImage mat2BI(Mat mat){  
        int dataSize =mat.cols()*mat.rows()*(int)mat.elemSize();  
        byte[] data=new byte[dataSize];  
        mat.get(0, 0,data);  
        int type=mat.channels()==1?  
                BufferedImage.TYPE_BYTE_GRAY:BufferedImage.TYPE_3BYTE_BGR;  
          
        if(type==BufferedImage.TYPE_3BYTE_BGR){  
            for(int i=0;i<dataSize;i+=3){  
                byte blue=data[i+0];  
                data[i+0]=data[i+2];  
                data[i+2]=blue;  
            }  
        }  
        BufferedImage image=new BufferedImage(mat.cols(),mat.rows(),type);  
        image.getRaster().setDataElements(0, 0, mat.cols(), mat.rows(), data);  
          
        return image;  
    }  
  
    public void paintComponent(Graphics g){  
        if(mImg!=null){  
            g.drawImage(mImg, 0, 0, mImg.getWidth(),mImg.getHeight(),this);  
        }  
    }  
      
    public static void main(String[] args) {  
        try{  
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);  
          
            Mat capImg=new Mat();  
            VideoCapture capture = new VideoCapture(0);  
            int height = (int)capture.get(Videoio.CAP_PROP_FRAME_HEIGHT);  
            int width = (int)capture.get(Videoio.CAP_PROP_FRAME_WIDTH);  
            if(height==0||width==0){  
                throw new Exception("camera not found!");  
            }  
              
            JFrame frame=new JFrame("camera");  
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);  
            CaptureBasic panel=new CaptureBasic();
            
            frame.setContentPane(panel);  
            frame.setVisible(true);  
            frame.setSize(width+frame.getInsets().left+frame.getInsets().right,  
                    height+frame.getInsets().top+frame.getInsets().bottom);  
            int n=0;
            Mat temp=new Mat();
            String face_token = "-1";
            while(face_token.equals("-1")){
                capture.read(capImg);
                Imgproc.cvtColor(capImg, temp, Imgproc.COLOR_RGB2GRAY);
                panel.mImg = panel.mat2BI(detectFace(capImg));
                panel.repaint();
                
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(panel.mImg, "jpg", out);
                byte[] im = out.toByteArray();
                face_token = FacePlus.getFaceId(im);
            }
            /**
             * 当前调用的face_token,是摄像头捕捉到的,内部还有一个face_token,是之前就做好的;
             */
            String content = Compare.com(face_token);
            JSONObject jsonObject = JSONObject.parseObject(content);
            BigDecimal con = (BigDecimal) jsonObject.get("confidence");
            float c = con.floatValue();
            if(c > 50){
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_ALT);
                robot.keyPress(KeyEvent.VK_TAB);
                robot.keyRelease(KeyEvent.VK_TAB);
                robot.keyPress(KeyEvent.VK_TAB);
                robot.keyRelease(KeyEvent.VK_TAB);
                robot.keyRelease(KeyEvent.VK_ALT);
            }
            System.out.println(con);
            
            capture.release();  
            frame.dispose();  
        }catch(Exception e){  
            System.out.println("例外:" + e);  
        }finally{  
            System.out.println("--done--");  
        }  
  
    }
    /**
     * opencv实现人脸识别
     * @param img
     */
    public static Mat detectFace(Mat img) throws Exception{

        System.out.println("Running DetectFace ... ");
        // 从配置文件lbpcascade_frontalface.xml中创建一个人脸识别器,该文件位于opencv安装目录中
        CascadeClassifier faceDetector = new CascadeClassifier("D:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");
        // 在图片中检测人脸
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(img, faceDetections);
        Rect[] rects = faceDetections.toArray();
        if(rects != null && rects.length >= 1){          
            for (Rect rect : rects) {  
                Imgproc.rectangle(img, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),new Scalar(0, 0, 255), 2);  
            } 
        }
        return img;
    }
    
    /**
     * opencv实现人型识别,hog默认的分类器。所以效果不好。
     * @param img
     */
    public static Mat detectPeople(Mat img) {
        if (img.empty()) {  
            System.out.println("image is exist");  
        }  
        HOGDescriptor hog = new HOGDescriptor();
        hog.setSVMDetector(HOGDescriptor.getDefaultPeopleDetector());
        System.out.println(HOGDescriptor.getDefaultPeopleDetector()); 
        MatOfRect regions = new MatOfRect();  
        MatOfDouble foundWeights = new MatOfDouble(); 
        hog.detectMultiScale(img, regions, foundWeights);        
        for (Rect rect : regions.toArray()) {             
            Imgproc.rectangle(img, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height),new Scalar(0, 0, 255), 2);  
        }  
        return img;  
    } 
    
}

 

 

package com.common.face;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 
 * @author Administrator
 *  根据face_token进行俩张照片的比对;
 */
public class Compare {
    
   public static void main(String[] args) throws Exception {
//     设置网址
       String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
//       创建参数队列    
       List<BasicNameValuePair> formparams = new ArrayList<>();  
       formparams.add(new BasicNameValuePair("api_key", "NCZxjJtNcTsQJLNc_zhEp6OeWyC3OgW6"));  
       formparams.add(new BasicNameValuePair("api_secret", "X8ymk7AKMFWrWJP6RHr_NZOO9eZmAvzw"));  
       formparams.add(new BasicNameValuePair("face_token1", "ff9abd289861ad17935c26b704941b18"));  
       formparams.add(new BasicNameValuePair("face_token2", "d9c502d1162cca0b0720dbd39a536804"));  
//     发送请求
       post(formparams,url);
   }
   public static String com(String faceid){
        String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
         
        List<BasicNameValuePair> formparams = new ArrayList<>();  
        formparams.add(new BasicNameValuePair("api_key", "NCZxjJtNcTsQJLNc_zhEp6OeWyC3OgW6"));  
        formparams.add(new BasicNameValuePair("api_secret", "X8ymk7AKMFWrWJP6RHr_NZOO9eZmAvzw"));  
        formparams.add(new BasicNameValuePair("face_token1", faceid));  
        formparams.add(new BasicNameValuePair("face_token2", "d9c502d1162cca0b0720dbd39a536804"));  
        
        String content = post(formparams,url);
        return content;
   }
 
    /** 
    * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
    */  
   public static String post(List<BasicNameValuePair> formparams,String url) {  
       // 创建默认的httpClient实例.    
       CloseableHttpClient httpclient = HttpClients.createDefault();  
       // 创建httppost    
       HttpPost httppost = new HttpPost(url);  
       UrlEncodedFormEntity uefEntity;  
       String content = "";
       try {  
           uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
           httppost.setEntity(uefEntity);  
           System.out.println("executing request " + httppost.getURI());  
           CloseableHttpResponse response = httpclient.execute(httppost);  
           try {  
               HttpEntity entity = response.getEntity();  
               if (entity != null) {  
                   System.out.println("--------------------------------------");  
                   //System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  
                   content = ""+EntityUtils.toString(entity, "UTF-8");
                   System.out.println(content);
                   System.out.println("--------------------------------------");  
                   
               }  
           } finally {  
               response.close();  
           }  
       } catch (ClientProtocolException e) {  
           e.printStackTrace();  
       } catch (UnsupportedEncodingException e1) {  
           e1.printStackTrace();  
       } catch (IOException e) {  
           e.printStackTrace();  
       } finally {  
           // 关闭连接,释放资源    
           try {  
               httpclient.close();  
           } catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
       return content;
   }
}

执行主函数为CaptureBasic类下!

另外,参考了别人的微博,只是,感觉出处太多, 也不知道具体的到底是谁写的。有需要的,只当参考,学习!

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值