org.opencv.objdetect.CascadeClassifier Java Examples

The following examples show how to use org.opencv.objdetect.CascadeClassifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DetectObject.java    From classchecks with Apache License 2.0 7 votes vote down vote up
/**
 * 
* @Title: detectMany 
* @Description: 检测多人图片,返回检测的人脸区域对象
* @param mImgSRC
* @return
* MatOfRect
 */
public static MatOfRect detectMany(Mat mImgSRC) {
	
	if(mImgSRC.empty()) {
		LOG.info("检测多人图片检测时没有找到图片");
		return null;
	}
	// 人脸检测器文件的所在路径的文件夹名称数组
	String [] pathKey = {ServletContextHolder.getOpenCVHaarcascades(), "haarcascade_frontalface_alt.xml"};
	CascadeClassifier cascade = new CascadeClassifier(FileUtils.buildFilePath(pathKey));
	if(cascade.empty()) {
		LOG.info("人脸检测级联加载器为null");
		return null;
	}
	// 记录搜索到的人脸区域
	MatOfRect mOfRect = new MatOfRect();
	// 用于计算缩放比例
	int scaledWidth = mImgSRC.width();
	detectManyObject(mImgSRC, cascade, mOfRect, scaledWidth);
	if(mOfRect.toArray().length <= 0) {
		LOG.info("没有检测到人脸...");
		return null;
	}
	return mOfRect;
}
 
Example #2
Source File: DetectEyes.java    From classchecks with Apache License 2.0 6 votes vote down vote up
/**
 * 检测左眼
 * @param faceImg
 * @param leftEyePoint
 * @param searchedLeftEye
 * @param scaledWidth
 */
protected static void detectLeftEye(Mat faceImg, Rect leftEyeRect, int scaledWidth) {
	CascadeClassifier cascade = new CascadeClassifier();
	cascade.load(DetectorXMLPath + HAARCASCADE_MCS_LEFTEYE);
	// 第一次检测左眼
	if(!cascade.empty()) {
		DetectObject.detectLargestObject(faceImg, cascade, leftEyeRect, scaledWidth);
	}
	// 如果没有检测到眼睛,使用不同的级联加载器继续尝试
	if(leftEyeRect.width <= 0) {
		cascade.load(DetectorXMLPath+HAARCASCADE_EYE_TREE_EYEGLASSES);
		if(!cascade.empty()) {
			DetectObject.detectLargestObject(faceImg, cascade, leftEyeRect, scaledWidth);
		}
	}
	if(leftEyeRect.width <= 0) {
		cascade.load(DetectorXMLPath+HAARCASCADE_EYE);
		if(!cascade.empty()) {
			DetectObject.detectLargestObject(faceImg, cascade, leftEyeRect, scaledWidth);
		}
	}
}
 
Example #3
Source File: FaceDetection.java    From tutorials with MIT License 6 votes vote down vote up
public static void detectFace(String sourceImagePath, String targetImagePath) {
    Mat loadedImage = loadImage(sourceImagePath);
    MatOfRect facesDetected = new MatOfRect();
    CascadeClassifier cascadeClassifier = new CascadeClassifier();
    int minFaceSize = Math.round(loadedImage.rows() * 0.1f);
    cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
    cascadeClassifier.detectMultiScale(loadedImage,
            facesDetected,
            1.1,
            3,
            Objdetect.CASCADE_SCALE_IMAGE,
            new Size(minFaceSize, minFaceSize),
            new Size()
    );
    Rect[] facesArray =  facesDetected.toArray();
    for(Rect face : facesArray) {
        Imgproc.rectangle(loadedImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
    }
    saveImage(loadedImage, targetImagePath);
}
 
Example #4
Source File: CameraStream.java    From tutorials with MIT License 6 votes vote down vote up
public static Mat detectFace(Mat inputImage) {
    MatOfRect facesDetected = new MatOfRect();
    CascadeClassifier cascadeClassifier = new CascadeClassifier();
    int minFaceSize = Math.round(inputImage.rows() * 0.1f);
    cascadeClassifier.load("./src/main/resources/haarcascades/haarcascade_frontalface_alt.xml");
    cascadeClassifier.detectMultiScale(inputImage,
            facesDetected,
            1.1,
            3,
            Objdetect.CASCADE_SCALE_IMAGE,
            new Size(minFaceSize, minFaceSize),
            new Size()
    );
    Rect[] facesArray =  facesDetected.toArray();
    for(Rect face : facesArray) {
        Imgproc.rectangle(inputImage, face.tl(), face.br(), new Scalar(0, 0, 255), 3 );
    }
    return inputImage;
}
 
Example #5
Source File: FaceDetectionTest.java    From opencv-fun with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void loop (CascadeClassifier classifier, Mat mat, ImgWindow window, VideoCapture video) {
	video.read(mat);
	System.out.println(mat);
	if (!mat.empty()) {
		MatOfRect rects = new MatOfRect();
		long start = System.nanoTime();
		classifier.detectMultiScale(mat, rects);
		System.out.println((System.nanoTime()-start)/1000000000.0);
		window.setImage(mat);
		Graphics2D g = window.begin();
		g.setColor(Color.RED);
		for(Rect r: rects.toArray()) {
			g.drawRect(r.x, r.y, r.width, r.height);
		}
		window.end();
	}
}
 
Example #6
Source File: PreProcessFace.java    From classchecks with Apache License 2.0 6 votes vote down vote up
/**
	 * 
	* @Title: rawProcessedFace 
	* @Description: 收集的原始图片预处理
	* @param faceImg
	* @return
	* Mat 
	* @throws
	 */
	public static Mat rawProcessedFace(Mat faceImg) {
		String DetectorFilename = "haarcascade_frontalface_alt.xml";
//		String XMLFilePath = Thread.currentThread().getClass().getResource("/").getPath().substring(1)
//				+"haarcascades/";
		String DetectorXMLPath = ServletContextHolder.getOpenCVHaarcascades() + DetectorFilename;
		LOG.info("DetectorXMLPath------>>>"+DetectorXMLPath);
		CascadeClassifier faceCascade = new CascadeClassifier(DetectorXMLPath);
		int faceWidth = 320;
		boolean preprocessLeftAndRightSeparately = true;
		Rect faceRect = new Rect();
		Mat getFace = PreProcessFace.pretreatmentFace(faceImg, faceWidth, faceCascade, 
				preprocessLeftAndRightSeparately, faceRect, faceWidth);
		
		return getFace;
	}
 
Example #7
Source File: DetectEyes.java    From classchecks with Apache License 2.0 6 votes vote down vote up
protected static void detectRightEye(Mat faceImg, Rect rightEyeRect, int scaledWidth) {
	CascadeClassifier cascade = new CascadeClassifier();
	cascade.load(DetectorXMLPath+HAARCASCADE_MCS_RIGHTEYE);
	// 第一次检测右眼
	if(!cascade.empty()) {
		DetectObject.detectLargestObject(faceImg, cascade, rightEyeRect, scaledWidth);
	}
	if(rightEyeRect.width <= 0) {
		cascade.load(DetectorXMLPath+HAARCASCADE_EYE_TREE_EYEGLASSES);
		if(!cascade.empty()) {
			DetectObject.detectLargestObject(faceImg, cascade, rightEyeRect, scaledWidth);
		}
	}
	if(rightEyeRect.width <= 0) {
		cascade.load(DetectorXMLPath+HAARCASCADE_EYE);
		if(!cascade.empty()) {
			DetectObject.detectLargestObject(faceImg, cascade, rightEyeRect, scaledWidth);
		}
	}
}
 
Example #8
Source File: DetectObject.java    From classchecks with Apache License 2.0 6 votes vote down vote up
/**
 * 检测一张人脸
 * @param img
 * @param cascade
 * @param largestObject
 * @param scaledWidth
 */
public static void detectLargestObject(Mat img, CascadeClassifier cascade, 
		Rect largestObject, int scaledWidth) {
	int flags = Objdetect.CASCADE_FIND_BIGGEST_OBJECT;
	Size minFeatureSize = new Size(10, 10);
	float searchScaleFactor = 1.1f; // 表示有多少不同大小的人脸要搜索,设置的大检测更快,但正确率降低
	int minNeighbors = 4; // 使检测的正确率更高,通常设为3

	MatOfRect objects = new MatOfRect();
	detectObjectsCustom(img, cascade, objects, scaledWidth, flags, minFeatureSize, searchScaleFactor, minNeighbors);
	if (!objects.empty()) {
		Rect tmpRect = objects.toList().get(0);
		largestObject.x = tmpRect.x;
		largestObject.y = tmpRect.y;
		largestObject.width = tmpRect.width;
		largestObject.height = tmpRect.height;
	} else {// 返回一个无效的rect
		largestObject.x = -1;
		largestObject.y = -1;
		largestObject.width = -1;
		largestObject.height = -1;
	}
}
 
Example #9
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 6 votes vote down vote up
/**
 * Detects faces in an image, draws boxes around them, and writes the results
 * @param fileName
 * @param destName
 */
public static void drawRect(String fileName, String destName){
    Mat image = Imgcodecs.imread(fileName);
    // Create a face detector from the cascade file in the resources
    // directory.
    CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml");
    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);
    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width,
                rect.y + rect.height), new Scalar(0, 255, 0));
    }

    Imgcodecs.imwrite(destName, image);

}
 
Example #10
Source File: VideoFaceTests.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * OpenCV-4.0.0 人脸识别
 * 
 * @date: 2019年5月7日12:16:55
 * @param image
 *            待处理Mat图片(视频中的某一帧)
 * @return 处理后的图片
 * @throws IOException
 */
public static Mat getFace(Mat image) throws IOException {
	// 1 读取OpenCV自带的人脸识别特征XML文件
	File faceFile = new ClassPathResourcePatternResolver().getResource("opencv/data/haarcascade_frontalface_alt.xml")
			.getFile();
	CascadeClassifier facebook = new CascadeClassifier(faceFile.getAbsolutePath());
	// 2 特征匹配类
	MatOfRect face = new MatOfRect();
	// 3 特征匹配
	facebook.detectMultiScale(image, face);
	Rect[] rects = face.toArray();
	System.out.println("匹配到 " + rects.length + " 个人脸");
	// 4 为每张识别到的人脸画一个圈
	for (int i = 0; i < rects.length; i++) {
		Imgproc.rectangle(image, new Point(rects[i].x, rects[i].y),
				new Point(rects[i].x + rects[i].width, rects[i].y + rects[i].height), new Scalar(0, 255, 0));
		Imgproc.putText(image, "Human", new Point(rects[i].x, rects[i].y), Imgproc.FONT_HERSHEY_SCRIPT_SIMPLEX, 1.0,
				new Scalar(0, 255, 0), 1, Imgproc.LINE_AA, false);
		// Mat dst=image.clone();
		// Imgproc.resize(image, image, new Size(300,300));
	}
	return image;
}
 
Example #11
Source File: DetectFaceDemo.java    From Java-for-Data-Science with MIT License 6 votes vote down vote up
public void run() {
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  String base = "C:/Books in Progress/Java for Data Science/Chapter 10/OpenCVExamples/src/resources";
  CascadeClassifier faceDetector = 
          new CascadeClassifier(base + "/lbpcascade_frontalface.xml");
  
  Mat image = Imgcodecs.imread(base + "/images.jpg");

  MatOfRect faceVectors = new MatOfRect();
  faceDetector.detectMultiScale(image, faceVectors);

  out.println(faceVectors.toArray().length + " faces found");

  for (Rect rect : faceVectors.toArray()) {
      Imgproc.rectangle(image, new Point(rect.x, rect.y), 
              new Point(rect.x + rect.width, rect.y + rect.height), 
              new Scalar(0, 255, 0));
  }
  Imgcodecs.imwrite("faceDetection.png", image);
}
 
Example #12
Source File: DetectActivity.java    From FaceDetectDemo with Apache License 2.0 6 votes vote down vote up
private void initClassifier() {
    try {
        InputStream is = getResources()
                .openRawResource(R.raw.lbpcascade_frontalface);
        File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
        File cascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
        FileOutputStream os = new FileOutputStream(cascadeFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        is.close();
        os.close();
        classifier = new CascadeClassifier(cascadeFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 6 votes vote down vote up
/**
 * Detects faces in an image, draws boxes around them, and writes the results
 * @param fileName
 * @param destName
 */
public static void drawRect(String fileName, String destName){
    Mat image = Highgui.imread(fileName);
    // Create a face detector from the cascade file in the resources
    // directory.
    CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml");
    // Detect faces in the image.
    // MatOfRect is a special container class for Rect.
    MatOfRect faceDetections = new MatOfRect();
    faceDetector.detectMultiScale(image, faceDetections);
    // Draw a bounding box around each face.
    for (Rect rect : faceDetections.toArray()) {
        Core.rectangle(image, new Point(rect.x, rect.y),
                new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
    }

    Highgui.imwrite(destName, image);

}
 
Example #14
Source File: DetectObjectTest.java    From classchecks with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetectManyObject() {
	String opencvDLL = "G:/java/JavaProjectRelease/classchecks/src/main/webapp/WEB-INF/dll/x64/opencv_java320.dll";
	System.load(opencvDLL);
	
	String haarcascade = "haarcascade_frontalface_alt.xml";
	
	
	CascadeClassifier cascade = new CascadeClassifier(XMLFilePath + haarcascade);
	
	Mat src = Imgcodecs.imread(imageDir + "/split/14.jpg");
	
	MatOfRect objects = new MatOfRect();
	int scaledWidth = src.width();
	
	DetectObject.detectManyObject(src, cascade, objects, scaledWidth);
	
	Rect [] rects = objects.toArray();
	int i = 0;
	for(Rect r : rects) {
		/*Imgproc.rectangle(src, new Point(r.x-100 , r.y-100 ), 
				new Point(r.x + r.width + 80, 
						r.y + r.height + 80), new Scalar(0, 0, 255), 3);*/
		Imgproc.rectangle(src, r.tl(), 
				r.br(), new Scalar(0, 0, 255), 3);
		/*r.width += 120;
		r.height += 120;
		r.x -= 100;
		r.y -= 100;
		System.out.println(r);
		Mat roi = new Mat(src, r);
		Imgcodecs.imwrite("e:/classchecks/2017417/split/"+i+".jpg", roi);
		i ++;*/
	}
	Imgcodecs.imwrite("e:/classchecks/2017417/dectctManyObject.jpg", src);
	//Imgcodecs.imwrite("e:/classchecks/dectctManyObject.jpg", src);
}
 
Example #15
Source File: FDOpenCVPresenter.java    From Image-Detection-Samples with Apache License 2.0 5 votes vote down vote up
private synchronized CascadeClassifier initializeJavaDetector(File cascadeFile) {
    CascadeClassifier detector = new CascadeClassifier(cascadeFile.getAbsolutePath());
    detector.load(cascadeFile.getAbsolutePath());
    if (detector.empty()) {
        Log.e(TAG, "Failed to load cascade classifier");
        detector = null;
    } else {
        Log.i(TAG, "Loaded cascade classifier from " + cascadeFile.getAbsolutePath());
    }
    return detector;
}
 
Example #16
Source File: FaceDetectionTest.java    From opencv-fun with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main (String[] args) {
	CVLoader.load();
	VideoCapture video = new VideoCapture(0);

	CascadeClassifier classifier = new CascadeClassifier("data/haarcascade_frontalface_alt.xml");
	ImgWindow window = ImgWindow.newWindow();
	if (video.isOpened()) {
	 	Mat mat = new Mat();
		while (!window.closed) {
			loop(classifier, mat, window, video);
		}
	}
	video.release();
}
 
Example #17
Source File: HaarCascadeOp.java    From StormCV with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
protected void prepareOpenCVOp(Map stormConf, TopologyContext context) throws Exception { 
	try {
		if(haarXML.charAt(0) != '/') haarXML = "/"+haarXML;
		File cascadeFile = NativeUtils.extractTmpFileFromJar(haarXML, true);
		haarDetector = new CascadeClassifier(cascadeFile.getAbsolutePath());
		Utils.sleep(100); // make sure the classifier has loaded before removing the tmp xml file
		if(!cascadeFile.delete()) cascadeFile.deleteOnExit();
	} catch (Exception e) {
		logger.error("Unable to instantiate SimpleFaceDetectionBolt due to: "+e.getMessage(), e);
		throw e;
	}
}
 
Example #18
Source File: ImageTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static MatOfRect getFace(Mat src) {
	Mat result = src.clone();
	if (src.cols() > 1000 || src.rows() > 1000) {
		Imgproc.resize(src, result, new Size(src.cols() / 3, src.rows() / 3));
	}

	CascadeClassifier faceDetector = new CascadeClassifier("D:\\mydev\\java\\opencv\\opencv\\build\\etc\\haarcascades\\haarcascade_frontalface_alt2.xml");
	MatOfRect objDetections = new MatOfRect();
	faceDetector.detectMultiScale(result, objDetections);
	
	return objDetections;
}
 
Example #19
Source File: FXController.java    From Face-Recognition with Apache License 2.0 5 votes vote down vote up
/**
 * Init the controller, at start time
 */
public void init()
{
	this.capture = new VideoCapture();
	this.faceCascade = new CascadeClassifier();
	this.absoluteFaceSize = 0;
	
	// disable 'new user' functionality
	this.newUserNameSubmit.setDisable(true);
	this.newUserName.setDisable(true);
	// Takes some time thus use only when training set
	// was updated 
	trainModel();
}
 
Example #20
Source File: PreProcessFace.java    From classchecks with Apache License 2.0 5 votes vote down vote up
public static Mat smallProcessedFace(Mat faceImg) {
		String DetectorFilename = "haarcascade_frontalface_alt.xml";
//		String XMLFilePath = Thread.currentThread().getClass().getResource("/").getPath().substring(1)
//				+"haarcascades/";
		String DetectorXMLPath = ServletContextHolder.getOpenCVHaarcascades() + DetectorFilename;
		LOG.info("DetectorXMLPath------>>>"+DetectorXMLPath);
		CascadeClassifier faceCascade = new CascadeClassifier(DetectorXMLPath);
		int faceWidth = 320;
		boolean preprocessLeftAndRightSeparately = true;
		Rect faceRect = new Rect();
		Mat getFace = PreProcessFace.pretreatmentFace(faceImg, faceWidth, faceCascade, 
				preprocessLeftAndRightSeparately, faceRect, faceWidth);
		
		return getFace;
	}
 
Example #21
Source File: DetectObject.java    From classchecks with Apache License 2.0 5 votes vote down vote up
/**
 * 检测多张人脸
 * 
 * @param img
 * @param cascade
 * @param objects
 * @param scaledWidth
 */
public static void detectManyObject(Mat img, CascadeClassifier cascade, MatOfRect objects, 
		int scaledWidth) {
	int flags = Objdetect.CASCADE_SCALE_IMAGE;
	Size minFeatureSize = new Size(10, 10);
	float searchScaleFactor = 1.1f;
	int minNeighbors = 3;
	detectObjectsCustom(img, cascade, objects, scaledWidth, flags,
			minFeatureSize, searchScaleFactor, minNeighbors);
}
 
Example #22
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取人脸范围
 * @param fileName
 * @return
 */
public static MatOfRect takeFace(String fileName) {
    CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml");
    Mat image = Highgui.imread(fileName);
    MatOfRect faceDetections = new MatOfRect();
    // 指定人脸识别的最大和最小像素范围
    Size minSize = new Size(120, 120);
    Size maxSize = new Size(250, 250);
    // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率
    faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0,
            minSize, maxSize);
    return faceDetections;
}
 
Example #23
Source File: HighGuiUtil.java    From javautils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取人脸范围
 * @param fileName
 * @return
 */
public static MatOfRect takeFace(String fileName) {
    CascadeClassifier faceDetector = new CascadeClassifier("libs/lbpcascade_frontalface.xml");
    Mat image = Imgcodecs.imread(fileName);
    MatOfRect faceDetections = new MatOfRect();
    // 指定人脸识别的最大和最小像素范围
    Size minSize = new Size(120, 120);
    Size maxSize = new Size(250, 250);
    // 参数设置为scaleFactor=1.1f, minNeighbors=4, flags=0 以此来增加识别人脸的正确率
    faceDetector.detectMultiScale(image, faceDetections, 1.1f, 4, 0,
            minSize, maxSize);
    return faceDetections;
}
 
Example #24
Source File: EyesDetectionInteractorImpl.java    From Image-Detection-Samples with Apache License 2.0 4 votes vote down vote up
public EyesDetectionInteractorImpl(CascadeClassifier detectorEye,
                                   MainThread mainThread, InteractorExecutor executor) {
    this.detectorEye = detectorEye;
    this.executor =  executor;
    this.mainThread = mainThread;
}
 
Example #25
Source File: MainActivity.java    From MOAAP with MIT License 4 votes vote down vote up
@Override
public void onManagerConnected(int status) {
    switch (status) {
        case LoaderCallbackInterface.SUCCESS:
        {
            Log.i(TAG, "OpenCV成功加载");
            try{
                InputStream is = getResources().openRawResource(R.raw.haarcascade_frontalface_alt2);
                File cascadeDir = getDir("cascade",
                        Context.MODE_PRIVATE);
                File mCascadeFile = new File(cascadeDir,"cascade.xml");
                FileOutputStream os = new
                        FileOutputStream(mCascadeFile);

                byte[] buffer = new byte[4096];
                int bytesRead;
                while((bytesRead = is.read(buffer)) != -1)
                {
                    os.write(buffer, 0, bytesRead);
                }
                is.close();
                os.close();

                haarCascade = new CascadeClassifier(
                        mCascadeFile.getAbsolutePath());
                if (haarCascade.empty())
                {
                    Log.i("Cascade Error", "级联分类器加载失败");
                    haarCascade = null;
                }
            }
            catch(Exception e)
            {
                Log.i("Cascade Error: ","找不到级联分类器文件");
            }
            mOpenCvCameraView.enableView();
        } break;
        default:
        {
            super.onManagerConnected(status);
        } break;
    }
}
 
Example #26
Source File: FaceDetection.java    From Android-Face-Recognition-with-Deep-Learning-Library with Apache License 2.0 4 votes vote down vote up
public void setCascadeClassifierForFaceDetector(Context context, String cascadeAssetName){
    CascadeClassifier cascadeClassifier = setCascadeClassifier(context.getAssets(), context.getDir("cascade", Context.MODE_PRIVATE), cascadeAssetName);
    faceDetector = cascadeClassifier;
}
 
Example #27
Source File: EyesDetectionInteractorImpl.java    From Image-Detection-Samples with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Build a template from a specific eye area previously substracted
 * uses detectMultiScale for this area, then uses minMaxLoc method to
 * detect iris from the detected eye</p>
 *
 * @param area Preformatted Area
 * @param size minimum iris size
 * @param grayMat image in gray
 * @param rgbaMat image in color
 * @param detectorEye Haar Cascade classifier
 * @return built template
 */
@NonNull
private static Mat buildTemplate(Rect area, final int size,
                                 @NonNull Mat grayMat,
                                 @NonNull Mat rgbaMat,
                                 CascadeClassifier detectorEye) {
    Mat template = new Mat();
    Mat graySubMatEye = grayMat.submat(area);
    MatOfRect eyes = new MatOfRect();
    Rect eyeTemplate;
    detectorEye.detectMultiScale(graySubMatEye, eyes, 1.15, 2,
            Objdetect.CASCADE_FIND_BIGGEST_OBJECT
                    | Objdetect.CASCADE_SCALE_IMAGE, new Size(EYE_MIN_SIZE, EYE_MIN_SIZE),
            new Size());

    Rect[] eyesArray = eyes.toArray();
    if (eyesArray.length > 0) {
        Rect e = eyesArray[0];
        e.x = area.x + e.x;
        e.y = area.y + e.y;
        Rect eyeRectangle = getEyeArea((int) e.tl().x,
                (int) (e.tl().y + e.height * 0.4),
                e.width,
                (int) (e.height * 0.6));
        graySubMatEye = grayMat.submat(eyeRectangle);
        Mat rgbaMatEye = rgbaMat.submat(eyeRectangle);


        Core.MinMaxLocResult minMaxLoc = Core.minMaxLoc(graySubMatEye);

        FaceDrawerOpenCV.drawIrisCircle(rgbaMatEye, minMaxLoc);
        Point iris = new Point();
        iris.x = minMaxLoc.minLoc.x + eyeRectangle.x;
        iris.y = minMaxLoc.minLoc.y + eyeRectangle.y;
        eyeTemplate = getEyeArea((int) iris.x - size / 2,
                (int) iris.y
                        - size / 2, size, size);
        FaceDrawerOpenCV.drawEyeRectangle(eyeTemplate, rgbaMat);
        template = (grayMat.submat(eyeTemplate)).clone();
    }
    return template;
}
 
Example #28
Source File: MainActivity.java    From SoftwarePilot with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkAndRequestPermissions();
    }

    setContentView(R.layout.activity_main);

    mHandler = new Handler(Looper.getMainLooper());

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    /*
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.INTERNET, Manifest.permission.VIBRATE,
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.WAKE_LOCK, Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.READ_PHONE_STATE,
            }
            , 1);
    */

    if(!OpenCVLoader.initDebug()){
        Log.v(TAG, "OpenCV not loaded");
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_11, this,
                new BaseLoaderCallback(this) {
            @Override
            public void onManagerConnected(int status) {
                switch (status) {
                    case LoaderCallbackInterface.SUCCESS:
                    {
                        Log.i("OpenCV", "OpenCV loaded successfully");
                        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
                        CascadeClassifier tt = new CascadeClassifier();

                        Mat imageMat=new Mat();
                    } break;
                    default:
                    {
                        super.onManagerConnected(status);
                    } break;
                }
            }
        });
    } else {
        Log.v(TAG, "OpenCV loaded");
    }


    /*DJISDKManager.getInstance().registerApp(MainActivity.this.getApplicationContext(), mDJISDKManagerCallback);

    while (hasRegistered == false) {
        System.out.println("No Registration Loop");
        try {
            Thread.sleep(10000);
        } catch (Exception e) {
        }
        DJISDKManager.getInstance().registerApp(MainActivity.this.getApplicationContext(), mDJISDKManagerCallback);
    }*/
}
 
Example #29
Source File: OrdFaceDetectionSample.java    From big-data-lite with MIT License 4 votes vote down vote up
public OrdFaceDetectionSample(Configuration conf) {
        super(conf);
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); //added loadLibrary
        faceDetector = new CascadeClassifier(CLASSIFIER_NAME);

    }
 
Example #30
Source File: FDInteractorImpl.java    From Image-Detection-Samples with Apache License 2.0 4 votes vote down vote up
public FDInteractorImpl(CascadeClassifier detectorFace,
                        MainThread mainThread, InteractorExecutor threadExecutor) {
    this.detectorFace = detectorFace;
    executorImageRecognition =  threadExecutor;
    this.mainThread = mainThread;
}