好像是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 map = new HashMap<>();
HashMap 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 map = new HashMap<>();
HashMap 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 map, HashMap 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 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 fileEntry = (Map.Entry) 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 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 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 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 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类下!
另外,参考了别人的微博,只是,感觉出处太多, 也不知道具体的到底是谁写的。有需要的,只当参考,学习!