package com.cloud.user.utils; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.io.IOUtils; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.imgcodecs.Imgcodecs; import com.cloud.common.exception.ApplicationException; import com.zeroc.Ice.ConnectionRefusedException; import ExtFaceWithImgOrUrl.ExtractFacePrx; import ExtFaceWithImgOrUrl.InParameters; import ExtFaceWithImgOrUrl.OutParameters; import nu.pattern.OpenCV; /** * 人脸工具类 */ public class FaceUtil { private final String ST_FACE_SERVER = "ExtractFace:default -h 139.224.105.107 -p 10019"; com.zeroc.Ice.Communicator communicator = com.zeroc.Ice.Util.initialize(new String[] { "/home" }); private ExtractFacePrx stFaceServer = null; private ExtractFacePrx getServer() { if (stFaceServer != null) { return stFaceServer; } else { com.zeroc.Ice.ObjectPrx base = communicator.stringToProxy(ST_FACE_SERVER); stFaceServer = ExtractFacePrx.checkedCast(base); return stFaceServer; } } /** * 传入文件的字节数组, 返回人脸的feature * @param byteArray * @param imageUrl * @return */ public static String extractFeature(byte[] byteArray, String imageUrl) { FaceUtil client = new FaceUtil(); try { OpenCV.loadShared(); ExtractFacePrx server = client.getServer(); if (server != null) { if (byteArray != null) { Mat image = Imgcodecs.imdecode(new MatOfByte(byteArray), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); MatOfByte buffer = new MatOfByte(); Imgcodecs.imencode(".jpg", image, buffer); byte[] array = buffer.toArray(); InParameters inParm = new InParameters(array, imageUrl); OutParameters outParm = server.extractFaceWithImgOrUrl(inParm); return outParm.faceFeaBase64; } else if (imageUrl != null && imageUrl.length() > 0) { // Mat image = Imgcodecs.imdecode(new MatOfByte(byteArray), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); // MatOfByte buffer = new MatOfByte(); // Mat image =Imgcodecs.imread("/home/bsk7/图片/image/6.jpg"); // Imgcodecs.imencode(".jpg", image, buffer); // byte[] array = buffer.toArray(); // InParameters inParm = new InParameters(array, imageUrl); // OutParameters outParm = server.extractFaceWithImgOrUrl(inParm); // return outParm.faceFeaBase64; } } } catch (ConnectionRefusedException e) { throw new ApplicationException("连接人脸识别服务器失败."); } catch (Exception e) { e.printStackTrace(); } finally { client.communicator.destroy(); } return null; } public static void main(String[] args) { try { String ret = extractFeature(IOUtils.toByteArray(new FileInputStream("d:\\7_1.jpg")), null); System.out.println(ret); } catch (Exception e) { e.printStackTrace(); } } }