www in docker support
This commit is contained in:
parent
539a848e95
commit
c227fce036
2145 changed files with 399596 additions and 58 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,53 @@
|
|||
package it.acxent.face.api;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class FaceRecognitionApiResult {
|
||||
private String msg;
|
||||
|
||||
public FaceRecognitionApiResult(String msg, boolean status, Object result) {
|
||||
this.msg = msg;
|
||||
this.ok = status;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
private boolean ok = true;
|
||||
|
||||
private Object result;
|
||||
|
||||
public FaceRecognitionApiResult() {}
|
||||
|
||||
public String getMsg() {
|
||||
return (this.msg == null) ? "" : this.msg.trim();
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public boolean isOk() {
|
||||
return this.ok;
|
||||
}
|
||||
|
||||
public void setOk(boolean status) {
|
||||
this.ok = status;
|
||||
}
|
||||
|
||||
public Object getResult() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
public JsonObject getJsonObjectResult() {
|
||||
return (JsonObject)getResult();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public JSONObject getJSONObjectResult() {
|
||||
return (JSONObject)getResult();
|
||||
}
|
||||
|
||||
public void setResult(Object result) {
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package it.acxent.face.api;
|
||||
|
||||
public class TrainingImage {
|
||||
private String imageFileName;
|
||||
|
||||
private long label;
|
||||
|
||||
private String md5;
|
||||
|
||||
public TrainingImage(String imageFileName, long label) {
|
||||
this.imageFileName = imageFileName;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public TrainingImage(String imageFileName, long label, String md5) {
|
||||
this.imageFileName = imageFileName;
|
||||
this.label = label;
|
||||
this.md5 = md5;
|
||||
}
|
||||
|
||||
public TrainingImage(String imageFileName, String md5) {
|
||||
this.imageFileName = imageFileName;
|
||||
this.md5 = md5;
|
||||
}
|
||||
|
||||
public TrainingImage() {}
|
||||
|
||||
public String getImageFileName() {
|
||||
return this.imageFileName;
|
||||
}
|
||||
|
||||
public void setImageFileName(String imageFileName) {
|
||||
this.imageFileName = imageFileName;
|
||||
}
|
||||
|
||||
public long getLabel() {
|
||||
return this.label;
|
||||
}
|
||||
|
||||
public void setLabel(long label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public String getMd5() {
|
||||
return this.md5;
|
||||
}
|
||||
|
||||
public void setMd5(String md5) {
|
||||
this.md5 = md5;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,554 @@
|
|||
package it.acxent.face.api.opencv;
|
||||
|
||||
import it.acxent.db.ApplParm;
|
||||
import it.acxent.db.ApplParmFull;
|
||||
import it.acxent.db.DBAdapter;
|
||||
import it.acxent.dm.FaceDetectionMethod;
|
||||
import it.acxent.face.api.vision.GoogleVisionApi;
|
||||
import it.acxent.face.api.vision.GoogleVisionResult;
|
||||
import it.acxent.face.fr.Face;
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.TreeMap;
|
||||
import org.apache.commons.math3.util.Pair;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.opencv.core.CvType;
|
||||
import org.opencv.core.Mat;
|
||||
import org.opencv.core.MatOfInt;
|
||||
import org.opencv.core.MatOfRect;
|
||||
import org.opencv.core.Point;
|
||||
import org.opencv.core.Rect;
|
||||
import org.opencv.core.Scalar;
|
||||
import org.opencv.core.Size;
|
||||
import org.opencv.dnn.Dnn;
|
||||
import org.opencv.dnn.Net;
|
||||
import org.opencv.face.FaceRecognizer;
|
||||
import org.opencv.face.LBPHFaceRecognizer;
|
||||
import org.opencv.imgcodecs.Imgcodecs;
|
||||
import org.opencv.imgproc.Imgproc;
|
||||
import org.opencv.objdetect.CascadeClassifier;
|
||||
|
||||
public class FaceRecognition {
|
||||
private static boolean debug = false;
|
||||
|
||||
public static final boolean _IS_LOCAL = false;
|
||||
|
||||
private static final int WIDTH_DETECT = 416;
|
||||
|
||||
private static final int HEIGHT_DETECT = 416;
|
||||
|
||||
private static final int WIDTH_NUMBER = 140;
|
||||
|
||||
private static final int HEIGHT_NUMBER = 120;
|
||||
|
||||
private static final double SCALE = 0.00392D;
|
||||
|
||||
private static final double CONFIDENCE_THRESHOLD_NUMBER = 0.5D;
|
||||
|
||||
private static final double NMS_THRESHOLD = 0.4D;
|
||||
|
||||
private static final List<String> NUMBER_CLASSES = new ArrayList<>();
|
||||
|
||||
private static final double CONFIDENCE_CALC_MAX_DISTANCE = 200.0D;
|
||||
|
||||
private FaceRecognitionProperties faceRecognitionProperties;
|
||||
|
||||
private static FaceRecognition instance;
|
||||
|
||||
private static final String cascadePath = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_default.xml";
|
||||
|
||||
public static final String pretrainedFrontFace = "/usr/local/share/opencv4/lbpcascades/lbpcascade_frontalface.xml";
|
||||
|
||||
public static final String pretrainedFrontFaceImproved = "/usr/local/share/opencv4/lbpcascades/lbpcascade_frontalface_improved.xml";
|
||||
|
||||
private FaceRecognizer recognizerLBPH;
|
||||
|
||||
private FaceRecognizer faceRecognizerEigen;
|
||||
|
||||
private FaceRecognizer faceRecognizerFish;
|
||||
|
||||
private Mat referenceImage;
|
||||
|
||||
static {
|
||||
NUMBER_CLASSES.add("0");
|
||||
NUMBER_CLASSES.add("1");
|
||||
NUMBER_CLASSES.add("2");
|
||||
NUMBER_CLASSES.add("3");
|
||||
NUMBER_CLASSES.add("4");
|
||||
NUMBER_CLASSES.add("5");
|
||||
NUMBER_CLASSES.add("6");
|
||||
NUMBER_CLASSES.add("7");
|
||||
NUMBER_CLASSES.add("8");
|
||||
NUMBER_CLASSES.add("9");
|
||||
}
|
||||
|
||||
private FaceRecognition(ApplParmFull l_apFull) {
|
||||
this.apFull = l_apFull;
|
||||
getFaceRecognitionProperties();
|
||||
}
|
||||
|
||||
private String fileModelloLBPH = null;
|
||||
|
||||
private ApplParmFull apFull;
|
||||
|
||||
public static void main(String[] args) {
|
||||
String hostname = "localhost:3308";
|
||||
String db = "fr";
|
||||
ApplParmFull ap = new ApplParmFull(new ApplParm(17, "//" + hostname + "/" + db, db, "root", "root", 1, 10, 300));
|
||||
FaceRecognition fr = new FaceRecognition(ap);
|
||||
String pathImgDir = "/Users/acolzi/Downloads/_ocv/img/";
|
||||
String pathToSelfie1 = pathImgDir + "selfie_652_r.JPG";
|
||||
String pathToSelfie2 = pathImgDir + "652_2_si.jpg";
|
||||
String testDetect = pathImgDir + "652_2_volti.jpg";
|
||||
String testDetect2 = pathImgDir + "AMG_4123_10_VOLTI.jpeg";
|
||||
JSONObject jo = fr.detectFaces(testDetect2, true);
|
||||
if (debug)
|
||||
System.out.println(jo.toString(4));
|
||||
}
|
||||
|
||||
public void faceRecognitionTest(String imgToCheck, String modelFileName) {
|
||||
if (imgToCheck == null)
|
||||
imgToCheck = "652_2_volti.jpg";
|
||||
String imagePath = getFaceRecognitionProperties().getPathImgBase() + getFaceRecognitionProperties().getPathImgBase();
|
||||
if (debug)
|
||||
System.out.println("imgToCheck: " + imagePath);
|
||||
Mat originalImage = Imgcodecs.imread(imagePath, 0);
|
||||
CascadeClassifier faceCascade = new CascadeClassifier("/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_default.xml");
|
||||
MatOfRect faceRectangles = new MatOfRect();
|
||||
faceCascade.detectMultiScale(originalImage, faceRectangles);
|
||||
Rect[] comparisonFaceRectangles = faceRectangles.toArray();
|
||||
if (debug)
|
||||
System.out.println("Recognizer training");
|
||||
this.recognizerLBPH = (FaceRecognizer)LBPHFaceRecognizer.create();
|
||||
this.recognizerLBPH.read(modelFileName);
|
||||
comparisoRect(comparisonFaceRectangles, originalImage, imagePath, this.recognizerLBPH);
|
||||
if (debug)
|
||||
System.out.println("Recognizer pretrainedFrontFaceImproved");
|
||||
this.recognizerLBPH = (FaceRecognizer)LBPHFaceRecognizer.create();
|
||||
this.recognizerLBPH.read("/usr/local/share/opencv4/lbpcascades/lbpcascade_frontalface_improved.xml");
|
||||
comparisoRect(comparisonFaceRectangles, originalImage, imagePath, this.recognizerLBPH);
|
||||
}
|
||||
|
||||
public void comparisoRect(Rect[] comparisonFaceRectangles, Mat originalImage, String imagePath, FaceRecognizer l_recognizerLBPH) {
|
||||
for (Rect faceRect : comparisonFaceRectangles) {
|
||||
Mat faceImage = originalImage.submat(faceRect);
|
||||
Imgproc.resize(faceImage, faceImage, this.referenceImage.size());
|
||||
int[] predictedLabel = new int[1];
|
||||
double[] confidenceLBPH = new double[1];
|
||||
double[] confidenceEigen = new double[1];
|
||||
double[] confidenceFish = new double[1];
|
||||
l_recognizerLBPH.predict(faceImage, predictedLabel, confidenceLBPH);
|
||||
if (debug)
|
||||
System.out.println("LBPH Confidenza di confronto. Immagine:" + imagePath + " per faccia su x,y" + faceRect.x + "," + faceRect.y + " --> " + confidenceLBPH[0]);
|
||||
}
|
||||
}
|
||||
|
||||
public void trainingCreateTest(List<TrainingImage> trainingImages, String modelFilename) {
|
||||
Mat labels = new Mat(trainingImages.size(), 1, CvType.CV_32SC1);
|
||||
MatOfInt labelsMat = new MatOfInt();
|
||||
List<Mat> trainingImagesMat = new ArrayList<>();
|
||||
int counter = 0;
|
||||
for (TrainingImage trainingImage : trainingImages) {
|
||||
File imageFile = new File(trainingImage.getImageFileName());
|
||||
if (this.referenceImage == null)
|
||||
this.referenceImage = Imgcodecs.imread(trainingImage.getImageFileName(), 0);
|
||||
Mat image = Imgcodecs.imread(imageFile.getAbsolutePath());
|
||||
Mat grayImage = new Mat();
|
||||
Imgproc.cvtColor(image, grayImage, 6);
|
||||
trainingImagesMat.add(grayImage);
|
||||
labels.put(trainingImage.getLabel(), 0, new double[] { (double)trainingImage.getLabel() });
|
||||
counter++;
|
||||
}
|
||||
labels.convertTo((Mat)labelsMat, CvType.CV_32SC1);
|
||||
this.recognizerLBPH = (FaceRecognizer)LBPHFaceRecognizer.create();
|
||||
this.recognizerLBPH.train(trainingImagesMat, labels);
|
||||
this.recognizerLBPH.save(modelFilename);
|
||||
}
|
||||
|
||||
public String getFileModelloLBPH() {
|
||||
return this.fileModelloLBPH;
|
||||
}
|
||||
|
||||
public void setFileModelloLBPH(String fileModelloLBPH) {
|
||||
this.fileModelloLBPH = fileModelloLBPH;
|
||||
}
|
||||
|
||||
public JSONObject detectFaces(String l_img, boolean isNumbers) {
|
||||
return detectFaces(l_img, 2L, isNumbers);
|
||||
}
|
||||
|
||||
public JSONObject detectFaces(String l_img) {
|
||||
return detectFaces(l_img, 2L, false);
|
||||
}
|
||||
|
||||
public JSONObject detectFaces(String l_img, long methodNumber) {
|
||||
return detectFaces(l_img, methodNumber, false);
|
||||
}
|
||||
|
||||
public JSONObject detectFaces(String l_img, long methodNumber, boolean isNumbers) {
|
||||
JSONObject res = new JSONObject();
|
||||
System.gc();
|
||||
try {
|
||||
FaceDetectionMethod fdm = new FaceDetectionMethod(getApFull());
|
||||
fdm.findByCodice(methodNumber);
|
||||
if (debug)
|
||||
System.out.println(fdm.getDescrizione());
|
||||
JSONObject response = new JSONObject();
|
||||
String l_md5 = l_img.substring(l_img.lastIndexOf('/') + 1, l_img.lastIndexOf("."));
|
||||
response.put("md5", l_md5);
|
||||
JSONArray faceAnnotationsA = new JSONArray();
|
||||
String tempImagePath = getApFull().getParm("path_img_tmp").getTesto() + getApFull().getParm("path_img_tmp").getTesto();
|
||||
Mat originalImage = Imgcodecs.imread(l_img, 0);
|
||||
if (debug)
|
||||
Imgcodecs.imwrite(tempImagePath + "_gray.jpg", originalImage);
|
||||
if (isNumbers) {
|
||||
JSONArray numbers = detectNumbers(l_img, getFaceRecognitionProperties());
|
||||
response.put("numbers", numbers);
|
||||
res.put("numOfNumbers", numbers.length());
|
||||
}
|
||||
if (methodNumber < 0L) {
|
||||
res.put("numOfFaces", 0);
|
||||
} else {
|
||||
int numberOfFaces = 0;
|
||||
if (fdm.getFlgDetectionType() == 0L) {
|
||||
CascadeClassifier faceCascade = new CascadeClassifier(fdm.getPathModello());
|
||||
MatOfRect faceRectangles = new MatOfRect();
|
||||
try {
|
||||
System.out.print("detectMultiscale: " + l_md5 + " ...");
|
||||
faceCascade.detectMultiScale(originalImage, faceRectangles);
|
||||
System.out.println("OK");
|
||||
Rect[] comparisonFaceRectangles = faceRectangles.toArray();
|
||||
for (Rect faceRect : comparisonFaceRectangles) {
|
||||
numberOfFaces++;
|
||||
JSONObject faceAnnotations = new JSONObject();
|
||||
JSONObject fdBoundingPoly = new JSONObject();
|
||||
JSONArray verticesA = new JSONArray();
|
||||
JSONObject j1 = new JSONObject();
|
||||
j1.put("x", faceRect.x);
|
||||
j1.put("y", faceRect.y);
|
||||
verticesA.put(j1);
|
||||
JSONObject j2 = new JSONObject();
|
||||
j2.put("x", faceRect.x + faceRect.width);
|
||||
j2.put("y", faceRect.y);
|
||||
verticesA.put(j2);
|
||||
JSONObject j3 = new JSONObject();
|
||||
j3.put("x", faceRect.x + faceRect.width);
|
||||
j3.put("y", faceRect.y + faceRect.height);
|
||||
verticesA.put(j3);
|
||||
JSONObject j4 = new JSONObject();
|
||||
j4.put("x", faceRect.x);
|
||||
j4.put("y", faceRect.y + faceRect.height);
|
||||
verticesA.put(j4);
|
||||
fdBoundingPoly.put("vertices", verticesA);
|
||||
faceAnnotations.put("fdBoundingPoly", fdBoundingPoly);
|
||||
faceAnnotationsA.put(faceAnnotations);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("detectFaces..");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (fdm.getFlgDetectionType() == 1L) {
|
||||
System.out.println("image " + l_img + " md5: " + l_md5 + " ... trying google vision...");
|
||||
GoogleVisionApi gva = new GoogleVisionApi(fdm.getApiKey());
|
||||
GoogleVisionResult resF = gva.annotateFaces(l_img);
|
||||
if (resF.isOk()) {
|
||||
JSONObject jo = (JSONObject)resF.getResult();
|
||||
JSONArray jaResponses = jo.getJSONArray("responses");
|
||||
if (jaResponses.length() > 0) {
|
||||
JSONObject joResponse = jaResponses.getJSONObject(0);
|
||||
if (joResponse.has("faceAnnotations")) {
|
||||
faceAnnotationsA = joResponse.getJSONArray("faceAnnotations");
|
||||
numberOfFaces = faceAnnotationsA.length();
|
||||
System.out.println(l_md5 + " google vision OK. Number of faces: " + l_md5);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
response.put("faceAnnotations", faceAnnotationsA);
|
||||
res.put("numOfFaces", numberOfFaces);
|
||||
}
|
||||
res.put("response", response);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public FaceRecognitionProperties getFaceRecognitionProperties() {
|
||||
if (this.faceRecognitionProperties == null)
|
||||
this.faceRecognitionProperties = FaceRecognitionProperties.getInstance(this.apFull);
|
||||
return this.faceRecognitionProperties;
|
||||
}
|
||||
|
||||
private static List<Rect> detectBoundingBoxes(Net detectionNet, Mat image) {
|
||||
Mat blob = Dnn.blobFromImage(image, 0.00392D, new Size(416.0D, 416.0D), new Scalar(0.0D, 0.0D, 0.0D), true, false);
|
||||
detectionNet.setInput(blob);
|
||||
List<String> layerNames = getOutputLayers(detectionNet);
|
||||
List<Double> confidences = new ArrayList<>();
|
||||
List<Mat> outputs = new ArrayList<>();
|
||||
List<Rect> boundingBoxes = new ArrayList<>();
|
||||
try {
|
||||
detectionNet.forward(outputs, layerNames);
|
||||
for (Mat output : outputs) {
|
||||
for (int j = 0; j < output.rows(); j++) {
|
||||
Mat detectionsMat = output.row(j);
|
||||
double confidence = (Double)confidence(detectionsMat).getSecond();
|
||||
if (confidence > 0.5D) {
|
||||
confidences.add(Double.valueOf(confidence));
|
||||
boundingBoxes.add(getRectFromDetection(detectionsMat, image));
|
||||
}
|
||||
}
|
||||
}
|
||||
boundingBoxes = NMSBoxes(boundingBoxes, confidences, 0.5F, 0.4F);
|
||||
} catch (Exception e) {
|
||||
System.out.println("detectBoundingBoxes: ");
|
||||
e.printStackTrace();
|
||||
}
|
||||
return boundingBoxes;
|
||||
}
|
||||
|
||||
private static void printMat(Mat mat) {
|
||||
System.out.println("\n" + String.valueOf(mat));
|
||||
for (int i = 0; i < mat.rows(); i++) {
|
||||
System.out.println();
|
||||
for (int j = 0; j < mat.cols(); j++) {
|
||||
double[] f = mat.get(i, j);
|
||||
System.out.print("[");
|
||||
for (int k = 0; k < f.length; k++)
|
||||
System.out.print("" + f[k] + ",");
|
||||
System.out.print("]\t");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Pair<Integer, Double> confidence(Mat mat) {
|
||||
int classid = 0;
|
||||
double confidence = 0.0D;
|
||||
if (mat.rows() == 1 && mat.cols() > 5)
|
||||
for (int k = 5; k < mat.cols(); k++) {
|
||||
double item = mat.get(0, k)[0];
|
||||
if (item > confidence) {
|
||||
confidence = item;
|
||||
classid = k - 5;
|
||||
}
|
||||
}
|
||||
Pair<Integer, Double> resP = new Pair(classid, confidence);
|
||||
return resP;
|
||||
}
|
||||
|
||||
private static Rect getRectFromDetection(Mat dec, Mat image) {
|
||||
Rect res = null;
|
||||
if (dec.rows() == 1 && dec.cols() > 4) {
|
||||
int width = (int)(dec.get(0, 2)[0] * (double)image.width());
|
||||
int height = (int)(dec.get(0, 3)[0] * (double)image.height());
|
||||
int x = (int)(dec.get(0, 0)[0] * (double)image.width()) - width / 2;
|
||||
int y = (int)(dec.get(0, 1)[0] * (double)image.height()) - height / 2;
|
||||
res = new Rect(x, y, width, height);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private static JSONArray detectNumbers(String fileName, FaceRecognitionProperties prop) {
|
||||
Mat image = Imgcodecs.imread(fileName);
|
||||
int width = image.width();
|
||||
int height = image.height();
|
||||
JSONArray numbers = new JSONArray();
|
||||
Net detectionNet = Dnn.readNet(prop.getNumberBoxDetectionModel(), prop.getNumberBoxDetectionConfig());
|
||||
Net recognitionNet = Dnn.readNet(prop.getNumberRecognitionDetectionModel(), prop.getNumberRecognitionDetectionConfig());
|
||||
List<Rect> boundingBoxes = detectBoundingBoxes(detectionNet, image);
|
||||
String text = "";
|
||||
String tempImagePath = prop.getPathImgTmp() + prop.getPathImgTmp();
|
||||
for (Rect boundingBox : boundingBoxes) {
|
||||
Mat plateImage = cropImage(image, boundingBox);
|
||||
if (debug)
|
||||
Imgcodecs.imwrite(tempImagePath + "_" + tempImagePath + "_" + boundingBox.x + ".jpg", plateImage);
|
||||
JSONObject number = new JSONObject();
|
||||
number.put("xCenter", boundingBox.x + boundingBox.width / 2);
|
||||
number.put("yCenter", boundingBox.y + boundingBox.height / 2);
|
||||
String numberValue = recognizeNumber(recognitionNet, plateImage);
|
||||
number.put("value", numberValue);
|
||||
numbers.put(number);
|
||||
drawBoundingBox(image, numberValue, boundingBox);
|
||||
text = text + text + ",";
|
||||
}
|
||||
if (debug)
|
||||
Imgcodecs.imwrite(tempImagePath + "_bounding.jpg", image);
|
||||
if (debug)
|
||||
System.out.println("pettorali:" + text);
|
||||
return numbers;
|
||||
}
|
||||
|
||||
private static List<String> getOutputLayers(Net net) {
|
||||
List<String> layerNames = net.getLayerNames();
|
||||
List<String> outputLayers = new ArrayList<>();
|
||||
List<Integer> unconnectedLayers = new ArrayList<>();
|
||||
for (String layerName : layerNames) {
|
||||
List<String> outLayers = net.getUnconnectedOutLayersNames();
|
||||
if (outLayers.contains(layerName))
|
||||
unconnectedLayers.add(Integer.valueOf(layerNames.indexOf(layerName)));
|
||||
}
|
||||
for (Iterator<Integer> iterator = unconnectedLayers.iterator(); iterator.hasNext(); ) {
|
||||
int i = iterator.next();
|
||||
outputLayers.add(layerNames.get(i));
|
||||
}
|
||||
return outputLayers;
|
||||
}
|
||||
|
||||
private static void drawBoundingBox(Mat image, String licenseStr, Rect boundingBox) {
|
||||
int x = boundingBox.x;
|
||||
int y = boundingBox.y;
|
||||
int width = boundingBox.width;
|
||||
int height = boundingBox.height;
|
||||
Point tl = new Point((double)x, (double)y);
|
||||
Point br = new Point((double)(x + width), (double)(y + height));
|
||||
Imgproc.rectangle(image, tl, br, new Scalar(0.0D, 255.0D, 0.0D), 2);
|
||||
int fontFace = 0;
|
||||
double fontScale = 0.5D;
|
||||
int thickness = 1;
|
||||
int baseline = 0;
|
||||
Imgproc.putText(image, licenseStr, new Point((double)x, (double)(y - baseline)), fontFace, fontScale, new Scalar(0.0D, 0.0D, 255.0D), thickness);
|
||||
}
|
||||
|
||||
private static Mat cropImage(Mat image, Rect boundingBox) {
|
||||
int x = boundingBox.x;
|
||||
int y = boundingBox.y;
|
||||
int width = boundingBox.width;
|
||||
int height = boundingBox.height;
|
||||
Mat cropImage = new Mat(image, new Rect(x, y, width, height));
|
||||
return cropImage;
|
||||
}
|
||||
|
||||
private static String recognizeNumber(Net recognitionNet, Mat image) {
|
||||
Mat blob = Dnn.blobFromImage(image, 0.00392D, new Size(140.0D, 120.0D), new Scalar(0.0D, 0.0D, 0.0D), true, false);
|
||||
recognitionNet.setInput(blob);
|
||||
List<Double> confidences = new ArrayList<>();
|
||||
List<Integer> class_ids = new ArrayList<>();
|
||||
List<Double> center_X = new ArrayList<>();
|
||||
String text = "";
|
||||
List<String> layerNames = getOutputLayers(recognitionNet);
|
||||
List<Mat> outputs = new ArrayList<>();
|
||||
recognitionNet.forward(outputs, layerNames);
|
||||
List<Rect> boundingBoxes = new ArrayList<>();
|
||||
HashMap<Integer, String> hmLetters = new HashMap<>();
|
||||
for (Mat output : outputs) {
|
||||
for (int j = 0; j < output.rows(); j++) {
|
||||
Mat detectionsMat = output.row(j);
|
||||
Pair<Integer, Double> pClassConfidence = confidence(detectionsMat);
|
||||
double confidence = (Double)pClassConfidence.getSecond();
|
||||
int class_id = (Integer)pClassConfidence.getFirst();
|
||||
if (confidence > 0.5D) {
|
||||
Rect currentRect = getRectFromDetection(detectionsMat, image);
|
||||
boundingBoxes.add(currentRect);
|
||||
confidences.add(Double.valueOf(confidence));
|
||||
hmLetters.put(Integer.valueOf(currentRect.x), NUMBER_CLASSES.get(class_id));
|
||||
String classLabel = NUMBER_CLASSES.get(class_id);
|
||||
text = text + text;
|
||||
}
|
||||
}
|
||||
}
|
||||
List<Rect> indices = NMSBoxes(boundingBoxes, confidences, 0.5F, 0.4F);
|
||||
TreeMap<Integer, String> tmLetters = new TreeMap<>();
|
||||
for (Rect currentbox : indices) {
|
||||
if (hmLetters.containsKey(Integer.valueOf(currentbox.x)))
|
||||
tmLetters.put(Integer.valueOf(currentbox.x), hmLetters.get(Integer.valueOf(currentbox.x)));
|
||||
}
|
||||
StringBuilder sbNumber = new StringBuilder();
|
||||
for (Iterator<Integer> iterator = tmLetters.keySet().iterator(); iterator.hasNext(); ) {
|
||||
int currentX = iterator.next();
|
||||
sbNumber.append(tmLetters.get(Integer.valueOf(currentX)));
|
||||
}
|
||||
return sbNumber.toString();
|
||||
}
|
||||
|
||||
private static List<Rect> NMSBoxes(List<Rect> boundingBoxes, List<Double> confidences, float confidenceThreshold, float nmsThreshold) {
|
||||
List<Rect> nmsBoxes = new ArrayList<>();
|
||||
boundingBoxes.sort((a, b) -> b.x - a.x);
|
||||
for (int i = 0; i < boundingBoxes.size(); i++) {
|
||||
Rect currentBox = boundingBoxes.get(i);
|
||||
for (int j = i + 1; j < boundingBoxes.size(); j++) {
|
||||
Rect remainingBox = boundingBoxes.get(j);
|
||||
float iou = IOU(currentBox, remainingBox);
|
||||
if (iou > nmsThreshold) {
|
||||
boundingBoxes.remove(j);
|
||||
j--;
|
||||
}
|
||||
}
|
||||
nmsBoxes.add(currentBox);
|
||||
}
|
||||
return nmsBoxes;
|
||||
}
|
||||
|
||||
private static float IOU(Rect a, Rect b) {
|
||||
int intersectionX = Math.max(a.x, b.x);
|
||||
int intersectionY = Math.max(a.y, b.y);
|
||||
int intersectionWidth = Math.min(a.x + a.width, b.x + b.width) - intersectionX;
|
||||
int intersectionHeight = Math.min(a.y + a.height, b.y + b.height) - intersectionY;
|
||||
float intersectionArea = 0.0F;
|
||||
if (intersectionWidth > 0 && intersectionHeight > 0)
|
||||
intersectionArea = (float)intersectionWidth * (float)intersectionHeight;
|
||||
float unionArea = (float)(a.width * a.height + b.width * b.height) - intersectionArea;
|
||||
return intersectionArea / unionArea;
|
||||
}
|
||||
|
||||
public ApplParmFull getApFull() {
|
||||
return this.apFull;
|
||||
}
|
||||
|
||||
public JSONArray faceRecognition(String imgToCheck, it.acxent.face.fr.FaceRecognizer frzer) {
|
||||
JSONArray jLabelsA = new JSONArray();
|
||||
boolean debug = true;
|
||||
if (debug)
|
||||
DBAdapter.printDebug(debug, " faceRecognition imgToCheck: " + imgToCheck);
|
||||
Mat originalImage = Imgcodecs.imread(imgToCheck, 0);
|
||||
int[] predictedLabel = new int[4];
|
||||
double[] confidenceLBPH = new double[4];
|
||||
if (debug)
|
||||
DBAdapter.printDebug(debug, " faceRecognition carico recognizer dalla cache: " +
|
||||
frzer.getFullFileName(0L));
|
||||
FaceRecognizer ocvFr = frzer.getOcvFaceRecognizerWithLoadedModel(0L);
|
||||
if (ocvFr == null) {
|
||||
if (debug)
|
||||
DBAdapter.printDebug(debug, " faceRecognition recognizer senza file modello!!!!!!");
|
||||
JSONObject jSONObject = new JSONObject();
|
||||
jSONObject.put("label", -1);
|
||||
jSONObject.put("confidence", 0);
|
||||
jSONObject.put("recognizerType", 0L);
|
||||
jSONObject.put("labelMd5", "");
|
||||
jLabelsA.put(jSONObject);
|
||||
return jLabelsA;
|
||||
}
|
||||
if (debug)
|
||||
DBAdapter.printDebug(debug, " faceRecognition predict.....: ");
|
||||
ocvFr.predict(originalImage, predictedLabel, confidenceLBPH);
|
||||
double confidence = confidenceLBPH[0];
|
||||
confidence = 100.0D * (1.0D - confidence / 200.0D);
|
||||
if (debug)
|
||||
DBAdapter.printDebug(debug, " faceRecognition LBPH Confidenza di confronto.\nImmagine:" + imgToCheck + "\npredictedLabel;" + predictedLabel[0] + "\ndistanza: " + confidenceLBPH[0] + "\nconfidenza: " + confidence + "\n--------");
|
||||
JSONObject joLabelsRow = new JSONObject();
|
||||
joLabelsRow.put("label", predictedLabel[0]);
|
||||
joLabelsRow.put("confidence", confidence);
|
||||
joLabelsRow.put("recognizerType", 0L);
|
||||
if (predictedLabel[0] > 0) {
|
||||
Face face = new Face(getApFull());
|
||||
face.findByPrimaryKey((long)predictedLabel[0]);
|
||||
joLabelsRow.put("labelMd5", face.getMd5());
|
||||
} else {
|
||||
joLabelsRow.put("labelMd5", "");
|
||||
}
|
||||
jLabelsA.put(joLabelsRow);
|
||||
return jLabelsA;
|
||||
}
|
||||
|
||||
public static FaceRecognition getInstance(ApplParmFull l_apFull) {
|
||||
if (instance == null) {
|
||||
instance = new FaceRecognition(l_apFull);
|
||||
Thread.setDefaultUncaughtExceptionHandler(new JniExceptionHandler());
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
package it.acxent.face.api.opencv;
|
||||
|
||||
import it.acxent.db.ApplParmFull;
|
||||
|
||||
public class FaceRecognitionProperties {
|
||||
public static final String mainConfigFile = "/etc/com-acxent-face/acxent-face.properties";
|
||||
|
||||
public static final String PROP_path_opencv_lib = "path_opencv_lib";
|
||||
|
||||
public static final String PROP_NUMBER_BOX_DECT_CONFIG = "NUMBER_BOX_DECT_CONFIG";
|
||||
|
||||
public static final String PROP_NUMBER_BOX_DECT_MODEL = "NUMBER_BOX_DECT_MODEL";
|
||||
|
||||
public static final String PROP_NUMBER_RECOG_CONFIG = "NUMBER_RECOG_CONFIG";
|
||||
|
||||
public static final String PROP_NUMBER_RECOG_MODEL = "NUMBER_RECOG_MODEL";
|
||||
|
||||
public static final String PROP_path_img_base = "path_img_base";
|
||||
|
||||
public static final String PROP_path_img_tmp = "path_img_tmp";
|
||||
|
||||
public static final String PROP_PATH_FACE_TRAINING_MODELS = "PATH_FACE_TRAINING_MODELS";
|
||||
|
||||
public static final String PROP_PATH_ZOO_FACE_RECOGNITION_SCRIPT = "PATH_ZOO_FACE_RECOGNITION_SCRIPT";
|
||||
|
||||
public static final String PROP_PATH_ZOO_FACE_DETECTION_SCRIPT = "PATH_ZOO_FACE_DETECTION_SCRIPT";
|
||||
|
||||
public static final String PROP_PATH_ZOO_BACKEND_TARGET = "PATH_ZOO_BACKEND_TARGET";
|
||||
|
||||
private static FaceRecognitionProperties instance;
|
||||
|
||||
private ApplParmFull apFull;
|
||||
|
||||
private String openCvLibPath;
|
||||
|
||||
private String numberBoxDetectionModel;
|
||||
|
||||
private String numberBoxDetectionConfig;
|
||||
|
||||
private String numberRecognitionDetectionModel;
|
||||
|
||||
private String numberRecognitionDetectionConfig;
|
||||
|
||||
private String pathImgBase;
|
||||
|
||||
private String pathImgTmp;
|
||||
|
||||
private String pathFaceTrainingModels;
|
||||
|
||||
public static FaceRecognitionProperties getInstance(ApplParmFull l_apFull) {
|
||||
if (instance == null) {
|
||||
instance = new FaceRecognitionProperties(l_apFull);
|
||||
System.load(instance.getOpenCvLibPath());
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
public FaceRecognitionProperties(ApplParmFull l_apfFull) {
|
||||
this.apFull = l_apfFull;
|
||||
setOpenCvLibPath(this.apFull.getParm("path_opencv_lib").getTesto());
|
||||
setPathImgBase(this.apFull.getParm("path_img_base").getTesto());
|
||||
setPathImgTmp(this.apFull.getParm("path_img_tmp").getTesto());
|
||||
setPathFaceTrainingModels(this.apFull.getParm("PATH_FACE_TRAINING_MODELS").getTesto());
|
||||
setNumberBoxDetectionConfig(this.apFull.getParm("NUMBER_BOX_DECT_CONFIG").getTesto());
|
||||
setNumberBoxDetectionModel(this.apFull.getParm("NUMBER_BOX_DECT_MODEL").getTesto());
|
||||
setNumberRecognitionDetectionConfig(this.apFull.getParm("NUMBER_RECOG_CONFIG").getTesto());
|
||||
setNumberRecognitionDetectionModel(this.apFull.getParm("NUMBER_RECOG_MODEL").getTesto());
|
||||
}
|
||||
|
||||
public String getOpenCvLibPath() {
|
||||
return this.openCvLibPath;
|
||||
}
|
||||
|
||||
public void setOpenCvLibPath(String openCvLibPath) {
|
||||
this.openCvLibPath = openCvLibPath;
|
||||
}
|
||||
|
||||
public String getPathImgBase() {
|
||||
return this.pathImgBase;
|
||||
}
|
||||
|
||||
public void setPathImgBase(String patImgBase) {
|
||||
this.pathImgBase = patImgBase;
|
||||
}
|
||||
|
||||
public String getNumberBoxDetectionModel() {
|
||||
return this.numberBoxDetectionModel;
|
||||
}
|
||||
|
||||
public void setNumberBoxDetectionModel(String numberBoxDetectionModel) {
|
||||
this.numberBoxDetectionModel = numberBoxDetectionModel;
|
||||
}
|
||||
|
||||
public String getNumberBoxDetectionConfig() {
|
||||
return this.numberBoxDetectionConfig;
|
||||
}
|
||||
|
||||
public void setNumberBoxDetectionConfig(String numberBoxDetectionConfig) {
|
||||
this.numberBoxDetectionConfig = numberBoxDetectionConfig;
|
||||
}
|
||||
|
||||
public String getNumberRecognitionDetectionModel() {
|
||||
return this.numberRecognitionDetectionModel;
|
||||
}
|
||||
|
||||
public void setNumberRecognitionDetectionModel(String numberRecognitionDetectionModel) {
|
||||
this.numberRecognitionDetectionModel = numberRecognitionDetectionModel;
|
||||
}
|
||||
|
||||
public String getNumberRecognitionDetectionConfig() {
|
||||
return this.numberRecognitionDetectionConfig;
|
||||
}
|
||||
|
||||
public void setNumberRecognitionDetectionConfig(String numberRecognitionDetectionConfig) {
|
||||
this.numberRecognitionDetectionConfig = numberRecognitionDetectionConfig;
|
||||
}
|
||||
|
||||
public String getPathFaceTrainingModels() {
|
||||
return this.pathFaceTrainingModels;
|
||||
}
|
||||
|
||||
public void setPathFaceTrainingModels(String patFaceTrainingModels) {
|
||||
this.pathFaceTrainingModels = patFaceTrainingModels;
|
||||
}
|
||||
|
||||
public String getPathImgTmp() {
|
||||
return this.pathImgTmp;
|
||||
}
|
||||
|
||||
public void setPathImgTmp(String pathImgTmp) {
|
||||
this.pathImgTmp = pathImgTmp;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
package it.acxent.face.api.opencv;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Vector;
|
||||
|
||||
public class FileIniManager {
|
||||
private String fileName;
|
||||
|
||||
private PrintWriter out;
|
||||
|
||||
public FileIniManager(String s) {
|
||||
this.fileName = s;
|
||||
}
|
||||
|
||||
public boolean deleteProperty(String s) {
|
||||
return writeProperty(s, "");
|
||||
}
|
||||
|
||||
private PrintWriter getOut() {
|
||||
if (this.out == null)
|
||||
try {
|
||||
this.out = new PrintWriter(new BufferedWriter(new FileWriter(this.fileName)));
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace(System.out);
|
||||
return null;
|
||||
}
|
||||
return this.out;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
FileIniManager fileinimanager = new FileIniManager("c:/00/aa.ini");
|
||||
System.out.println("LETTURA1 " + fileinimanager.get("MaxDoc"));
|
||||
fileinimanager.writeProperty("MaxDoc", "ANDREA");
|
||||
System.out.println("LETTURA DOPO WRITE " + fileinimanager.get("MaxDoc"));
|
||||
fileinimanager.deleteProperty("MaxDoc");
|
||||
System.out.println("Dopo cancella: " + fileinimanager.get("MaxDoc"));
|
||||
fileinimanager.writeProperty("MaxDoc", "111 riwrite");
|
||||
System.out.println("Dopo riwrite: " + fileinimanager.get("MaxDoc"));
|
||||
}
|
||||
|
||||
private boolean outClose() {
|
||||
try {
|
||||
getOut().flush();
|
||||
getOut().close();
|
||||
this.out = null;
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace(System.out);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public String get(String s) {
|
||||
BufferedReader bufferedreader = null;
|
||||
try {
|
||||
bufferedreader = new BufferedReader(new FileReader(this.fileName));
|
||||
String s1;
|
||||
while ((s1 = bufferedreader.readLine()) != null) {
|
||||
if (s1.startsWith(s + "="))
|
||||
return s1.substring(s.length() + 1);
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace(System.out);
|
||||
} finally {
|
||||
if (bufferedreader != null)
|
||||
try {
|
||||
bufferedreader.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public boolean writeProperty(String s, String s1) {
|
||||
try {
|
||||
BufferedReader bufferedreader = new BufferedReader(new FileReader(this.fileName));
|
||||
Vector<String> vector = new Vector();
|
||||
boolean flag = false;
|
||||
String s2;
|
||||
while ((s2 = bufferedreader.readLine()) != null) {
|
||||
if (s2.startsWith(s + "=")) {
|
||||
if (!s1.isEmpty())
|
||||
vector.addElement(s + "=" + s);
|
||||
flag = true;
|
||||
continue;
|
||||
}
|
||||
vector.addElement(s2);
|
||||
}
|
||||
bufferedreader.close();
|
||||
if (!flag && !s1.isEmpty())
|
||||
vector.addElement(s + "=" + s);
|
||||
if (flag || !s1.isEmpty()) {
|
||||
for (Enumeration<String> enumeration = vector.elements(); enumeration.hasMoreElements();)
|
||||
getOut()
|
||||
.println(enumeration.nextElement());
|
||||
outClose();
|
||||
}
|
||||
} catch (Exception exception) {
|
||||
exception.printStackTrace(System.out);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
package it.acxent.face.api.opencv;
|
||||
|
||||
public class JniExceptionHandler implements Thread.UncaughtExceptionHandler {
|
||||
public void uncaughtException(Thread thread, Throwable ex) {
|
||||
System.err.println("Errore JNI non intercettato nel thread " + String.valueOf(thread) + ": " + String.valueOf(ex));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package it.acxent.face.api.opencv;
|
||||
|
||||
public class TrainingImage {
|
||||
private String imageFileName;
|
||||
|
||||
private int label;
|
||||
|
||||
public TrainingImage(String imageFileName, int label) {
|
||||
this.imageFileName = imageFileName;
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public TrainingImage() {}
|
||||
|
||||
public String getImageFileName() {
|
||||
return this.imageFileName;
|
||||
}
|
||||
|
||||
public void setImageFileName(String imageFileName) {
|
||||
this.imageFileName = imageFileName;
|
||||
}
|
||||
|
||||
public int getLabel() {
|
||||
return this.label;
|
||||
}
|
||||
|
||||
public void setLabel(int label) {
|
||||
this.label = label;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
package it.acxent.face.api.opencv;
|
||||
|
|
@ -0,0 +1 @@
|
|||
package it.acxent.face.api;
|
||||
|
|
@ -0,0 +1,243 @@
|
|||
package it.acxent.face.api.vision;
|
||||
|
||||
import it.acxent.cc.Attivita;
|
||||
import it.acxent.common.Parm;
|
||||
import it.acxent.common.StatusMsg;
|
||||
import it.acxent.db.ApplParm;
|
||||
import it.acxent.db.ApplParmFull;
|
||||
import it.acxent.db.DBAdapter;
|
||||
import java.io.File;
|
||||
import java.util.Base64;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class GoogleVisionApi {
|
||||
private Attivita attivita;
|
||||
|
||||
private boolean debug = false;
|
||||
|
||||
private ApplParmFull apFull = null;
|
||||
|
||||
private String googleApiKey;
|
||||
|
||||
private String imageFileName;
|
||||
|
||||
public static final String CUPS_SESSION_ID = "_CUPS_SESSION_ID";
|
||||
|
||||
public static final String API_PRODUCTION = "https://vision.googleapis.com/v1/";
|
||||
|
||||
public static final String P_GOOGLE_API_KEY_VISION = "GOOGLE_API_KEY_VISION";
|
||||
|
||||
private static final String URI_CMD_IMAGE_ANNOTATE = "images:annotate?key={key}";
|
||||
|
||||
public GoogleVisionApi(ApplParmFull apFull) {
|
||||
this.apFull = apFull;
|
||||
this.googleApiKey = apFull.getParm("GOOGLE_API_KEY_VISION").getTesto();
|
||||
}
|
||||
|
||||
public GoogleVisionApi(String l_googleApiKey) {
|
||||
this.googleApiKey = l_googleApiKey;
|
||||
}
|
||||
|
||||
public GoogleVisionApi() {}
|
||||
|
||||
public static void initApplicationParms(ApplParmFull ap) {
|
||||
if (ap != null) {
|
||||
DBAdapter.logDebug(true, "GOOGLE VISION initParms: start");
|
||||
String l_tipoParm = "GOOGLE VISION";
|
||||
StatusMsg.updateMsgByTag(ap, "INIT", l_tipoParm);
|
||||
Parm bean = new Parm(ap);
|
||||
bean.findByCodice("GOOGLE_API_KEY_VISION");
|
||||
bean.setFlgAdmin(1L);
|
||||
bean.setTipoParm(l_tipoParm);
|
||||
bean.setCodice("GOOGLE_API_KEY_VISION");
|
||||
bean.setDescrizione("GOOGLE_API_KEY_VISION");
|
||||
if (bean.getTesto().isEmpty())
|
||||
bean.setTesto("AIzaSyBYEytX_RU1GDazEC4wCVz5SuxmM_XWUvU");
|
||||
bean.setNota("API KEY ACCESSO AL CLOUD VISION DI GOOGLE<br>AIzaSyBYEytX_RU1GDazEC4wCVz5SuxmM_XWUvU su comm<br>AIzaSyBYEytX_RU1GDazEC4wCVz5SuxmM_XWUvU qui");
|
||||
bean.save();
|
||||
DBAdapter.logDebug(true, "GOOGLE VISION initParms: stop");
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String hostname = "localhost";
|
||||
String db = "tr";
|
||||
ApplParmFull ap = new ApplParmFull(new ApplParm(3, "//" + hostname + "/" + db, "root", "root", 1, 10, 300));
|
||||
GoogleVisionApi bean = new GoogleVisionApi("AIzaSyBYEytX_RU1GDazEC4wCVz5SuxmM_XWUvU");
|
||||
GoogleVisionResult resF = bean.annotateFaces("/Users/acolzi/Downloads/_testFace/bastogi1.jpg");
|
||||
System.out.println(resF.getMsg() + "\n" + resF.getMsg());
|
||||
}
|
||||
|
||||
protected String getBase64BasicCredential() {
|
||||
String encoding = "aa:bb";
|
||||
return "Basic " + Base64.getEncoder().encodeToString(encoding.getBytes());
|
||||
}
|
||||
|
||||
public ApplParmFull getApFull() {
|
||||
return this.apFull;
|
||||
}
|
||||
|
||||
public void setApFull(ApplParmFull apFull) {
|
||||
this.apFull = apFull;
|
||||
}
|
||||
|
||||
public Attivita getAttivita() {
|
||||
if (this.attivita == null)
|
||||
this.attivita = Attivita.getDefaultInstance(getApFull());
|
||||
return this.attivita;
|
||||
}
|
||||
|
||||
public String getApiEndpoint() {
|
||||
return "https://vision.googleapis.com/v1/";
|
||||
}
|
||||
|
||||
public GoogleVisionResult annotateImage(String l_imageFileName) {
|
||||
GoogleVisionResult resER = new GoogleVisionResult();
|
||||
try {
|
||||
if (this.debug)
|
||||
System.out.println("GoogleVisionApi --> annotateImage");
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpPost request = new HttpPost(getApiEndpoint() + getApiEndpoint());
|
||||
if (this.debug)
|
||||
System.out.println(getApiEndpoint() + getApiEndpoint());
|
||||
request.setHeader("Accept", "application/json");
|
||||
request.setHeader("Content-Type", "application/json");
|
||||
request.setHeader("Content-Language", "it-IT");
|
||||
JSONObject jBody = new JSONObject();
|
||||
jBody.put("parent", "");
|
||||
JSONArray jRequest = new JSONArray();
|
||||
JSONObject jRequestRow = new JSONObject();
|
||||
JSONObject jImage = new JSONObject();
|
||||
byte[] fileContent = FileUtils.readFileToByteArray(new File(l_imageFileName));
|
||||
String encodedString = Base64.getEncoder().encodeToString(fileContent);
|
||||
jImage.put("content", encodedString);
|
||||
jRequestRow.put("image", jImage);
|
||||
JSONArray jFeatures = new JSONArray();
|
||||
JSONObject jType = new JSONObject();
|
||||
jType.put("type", "DOCUMENT_TEXT_DETECTION");
|
||||
jFeatures.put(jType);
|
||||
jRequestRow.put("features", jFeatures);
|
||||
jRequest.put(jRequestRow);
|
||||
jBody.put("requests", jRequest);
|
||||
if (!this.debug);
|
||||
System.out.println(jBody.toString(4));
|
||||
StringEntity postingString = new StringEntity(jBody.toString());
|
||||
request.setEntity((HttpEntity)postingString);
|
||||
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
|
||||
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
|
||||
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
|
||||
if (this.debug) {
|
||||
System.out.println("Status Code: " + statusCode);
|
||||
System.out.println("\ncontent = " + content);
|
||||
}
|
||||
if (statusCode >= 400) {
|
||||
resER.setOk(false);
|
||||
JSONObject jo = new JSONObject(content);
|
||||
resER.setMsg(jo.toString(2));
|
||||
resER.setResult(jo);
|
||||
} else {
|
||||
JSONObject jo = new JSONObject(content);
|
||||
if (this.debug)
|
||||
System.out.println(jo.toString(4));
|
||||
resER.setMsg("Text Found");
|
||||
resER.setOk(true);
|
||||
resER.setResult(jo.toString());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
resER.setOk(false);
|
||||
resER.setMsg(e.getMessage());
|
||||
}
|
||||
return resER;
|
||||
}
|
||||
|
||||
public String getGoogleApiKey() {
|
||||
return (this.googleApiKey == null) ? "" : this.googleApiKey.trim();
|
||||
}
|
||||
|
||||
public void setGoogleApiKey(String googleApiKey) {
|
||||
this.googleApiKey = googleApiKey;
|
||||
}
|
||||
|
||||
public String getImageFileName() {
|
||||
return (this.imageFileName == null) ? "" : this.imageFileName.trim();
|
||||
}
|
||||
|
||||
public void setImageFileName(String imageFile) {
|
||||
this.imageFileName = imageFile;
|
||||
}
|
||||
|
||||
public GoogleVisionResult annotateFaces(String l_imageFileName) {
|
||||
GoogleVisionResult resER = new GoogleVisionResult();
|
||||
File l_imageFileNameFile = new File(l_imageFileName);
|
||||
if (!l_imageFileNameFile.exists()) {
|
||||
resER.setOk(false);
|
||||
resER.setMsg("File " + l_imageFileName + " not found!");
|
||||
return resER;
|
||||
}
|
||||
try {
|
||||
if (this.debug)
|
||||
System.out.println("GoogleVisionApi --> annotateImage");
|
||||
CloseableHttpClient client = HttpClients.createDefault();
|
||||
HttpPost request = new HttpPost(getApiEndpoint() + getApiEndpoint());
|
||||
if (this.debug)
|
||||
System.out.println(getApiEndpoint() + getApiEndpoint());
|
||||
request.setHeader("Accept", "application/json");
|
||||
request.setHeader("Content-Type", "application/json");
|
||||
request.setHeader("Content-Language", "it-IT");
|
||||
JSONObject jBody = new JSONObject();
|
||||
jBody.put("parent", "");
|
||||
JSONArray jRequest = new JSONArray();
|
||||
JSONObject jRequestRow = new JSONObject();
|
||||
JSONObject jImage = new JSONObject();
|
||||
byte[] fileContent = FileUtils.readFileToByteArray(l_imageFileNameFile);
|
||||
String encodedString = Base64.getEncoder().encodeToString(fileContent);
|
||||
jImage.put("content", encodedString);
|
||||
jRequestRow.put("image", jImage);
|
||||
JSONArray jFeatures = new JSONArray();
|
||||
JSONObject jType = new JSONObject();
|
||||
jType.put("type", "FACE_DETECTION");
|
||||
jFeatures.put(jType);
|
||||
jRequestRow.put("features", jFeatures);
|
||||
jRequest.put(jRequestRow);
|
||||
jBody.put("requests", jRequest);
|
||||
StringEntity postingString = new StringEntity(jBody.toString());
|
||||
request.setEntity((HttpEntity)postingString);
|
||||
CloseableHttpResponse closeableHttpResponse = client.execute((HttpUriRequest)request);
|
||||
String content = EntityUtils.toString(closeableHttpResponse.getEntity());
|
||||
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
|
||||
if (this.debug) {
|
||||
System.out.println("Status Code: " + statusCode);
|
||||
System.out.println("\ncontent = " + content);
|
||||
}
|
||||
if (statusCode >= 400) {
|
||||
resER.setOk(false);
|
||||
JSONObject jo = new JSONObject(content);
|
||||
resER.setMsg(jo.toString(2));
|
||||
resER.setResult(jo);
|
||||
} else {
|
||||
JSONObject jo = new JSONObject(content);
|
||||
resER.setMsg("Faces found");
|
||||
resER.setOk(true);
|
||||
resER.setResult(jo);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getMessage());
|
||||
e.printStackTrace();
|
||||
resER.setOk(false);
|
||||
resER.setMsg(e.getMessage());
|
||||
}
|
||||
return resER;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package it.acxent.face.api.vision;
|
||||
|
||||
public class GoogleVisionResult {
|
||||
private String msg;
|
||||
|
||||
public GoogleVisionResult(String msg, boolean status, Object result) {
|
||||
this.msg = msg;
|
||||
this.ok = status;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
private boolean ok = true;
|
||||
|
||||
private Object result;
|
||||
|
||||
public GoogleVisionResult() {}
|
||||
|
||||
public String getMsg() {
|
||||
return (this.msg == null) ? "" : this.msg.trim();
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public boolean isOk() {
|
||||
return this.ok;
|
||||
}
|
||||
|
||||
public void setOk(boolean status) {
|
||||
this.ok = status;
|
||||
}
|
||||
|
||||
public Object getResult() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
public void setResult(Object result) {
|
||||
this.result = result;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
package it.acxent.face.api.vision;
|
||||
Loading…
Add table
Add a link
Reference in a new issue