Java Code Examples for org.opencv.imgproc.Imgproc#rectangle()

The following examples show how to use org.opencv.imgproc.Imgproc#rectangle() . 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: 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 2
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 3
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 4
Source File: MathFTC.java    From DogeCV with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Crops an image to two specified corners
 * @param image The image to be cropped
 * @param topLeftCorner The top-left corner of the desired final image, in pixel coordinates
 * @param bottomRightCorner The bottom-right corner of the desired final image, in pixel coordinates
 * @return The cropped image
 */
public static Mat crop(Mat image, Point topLeftCorner, Point bottomRightCorner) {
    if (topLeftCorner != null) {
        if(topLeftCorner.y > 0 && topLeftCorner.y < image.height()-1 && topLeftCorner.x > 0 && topLeftCorner.x < image.width()) {
            Imgproc.rectangle(image, new Point(0,0), new Point(image.width(),topLeftCorner.y), new Scalar(0), -1);
            Imgproc.rectangle(image, new Point(0,0), new Point(topLeftCorner.x, image.height()), new Scalar(0), -1);
        }
    }
    if(bottomRightCorner != null) {
        if(bottomRightCorner.y > 0 && bottomRightCorner.y < image.height()-1 && bottomRightCorner.x > 0 && bottomRightCorner.x < image.width()) {
            Imgproc.rectangle(image, new Point(image.width(),image.height()), new Point(bottomRightCorner.x,0), new Scalar(0), -1);
            Imgproc.rectangle(image, new Point(image.width(),image.height()), new Point(0, bottomRightCorner.y), new Scalar(0), -1);
        }
    }
    return image;
}
 
Example 5
Source File: MainActivity.java    From MOAAP with MIT License 6 votes vote down vote up
void HOGDescriptor() {
    Mat grayMat = new Mat();
    Mat people = new Mat();

    //Converting the image to grayscale
    Imgproc.cvtColor(originalMat, grayMat, Imgproc.COLOR_BGR2GRAY);

    HOGDescriptor hog = new HOGDescriptor();
    hog.setSVMDetector(HOGDescriptor.getDefaultPeopleDetector());

    MatOfRect faces = new MatOfRect();
    MatOfDouble weights = new MatOfDouble();

    hog.detectMultiScale(grayMat, faces, weights);
    originalMat.copyTo(people);
    //Draw faces on the image
    Rect[] facesArray = faces.toArray();
    for (int i = 0; i < facesArray.length; i++)
        Imgproc.rectangle(people, facesArray[i].tl(), facesArray[i].br(), new Scalar(100), 3);

    //Converting Mat back to Bitmap
    Utils.matToBitmap(people, currentBitmap);
    imageView.setImageBitmap(currentBitmap);
}
 
Example 6
Source File: CascadeClassifierProcessor.java    From Camdroid with Apache License 2.0 5 votes vote down vote up
protected void execute() {

            if (!classifierPath.equals(lastUsedClassifierPath)) {
                detector.load(classifierPath);
                lastUsedClassifierPath = classifierPath;
            }

            if (detector.empty()) {
                return;
            }

            out = gray();

            double min = (double) this.in.height() * object_min_size / 100;
            double max = (double) this.in.height() * object_max_size / 100;

            MatOfRect rects = new MatOfRect();
            detector.detectMultiScale(out, rects,
                    1 + (double) scale_factor / 100, min_neighbors, 0,
                    new Size(min, min), new Size(max, max));

            for (Rect rect : rects.toArray()) {
                Imgproc.rectangle(out, rect.tl(), rect.br(),
                        new Scalar(255, 0, 0), 1);
            }

        }
 
Example 7
Source File: MovementDetectionProcessor.java    From Camdroid with Apache License 2.0 5 votes vote down vote up
protected void execute() {
    out = gray();

    Imgproc.equalizeHist(out, out);

    synchronized (mog) {
        mog.apply(out, this.mask, (double) (-10 + learning_rate) / 10);
    }

    Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_DILATE,
            new Size(3, 3));
    Imgproc.dilate(mask, mask, kernel);

    ArrayList<MatOfPoint> contours = new ArrayList<MatOfPoint>();
    Imgproc.findContours(this.mask, contours, new Mat(),
            Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);

    double maxheight = object_max_size * this.in.height() / 100;
    double minheight = object_min_size * this.in.height() / 100;

    Iterator<MatOfPoint> each = contours.iterator();
    each = contours.iterator();
    while (each.hasNext()) {
        MatOfPoint contour = each.next();
        Rect rect = Imgproc.boundingRect(contour);
        if (rect.height > minheight && rect.height < maxheight) {
            Imgproc.rectangle(out, rect.tl(), rect.br(), new Scalar(255,
                    0, 0), 1);
        }
    }
}
 
Example 8
Source File: DetectActivity.java    From FaceDetectDemo with Apache License 2.0 5 votes vote down vote up
@Override
// 这里执行人脸检测的逻辑, 根据OpenCV提供的例子实现(face-detection)
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
    mRgba = inputFrame.rgba();
    mGray = inputFrame.gray();
    // 翻转矩阵以适配前后置摄像头
    if (isFrontCamera) {
        Core.flip(mRgba, mRgba, 1);
        Core.flip(mGray, mGray, 1);
    } else {
        Core.flip(mRgba, mRgba, -1);
        Core.flip(mGray, mGray, -1);
    }
    float mRelativeFaceSize = 0.2f;
    if (mAbsoluteFaceSize == 0) {
        int height = mGray.rows();
        if (Math.round(height * mRelativeFaceSize) > 0) {
            mAbsoluteFaceSize = Math.round(height * mRelativeFaceSize);
        }
    }
    MatOfRect faces = new MatOfRect();
    if (classifier != null)
        classifier.detectMultiScale(mGray, faces, 1.1, 2, 2,
                new Size(mAbsoluteFaceSize, mAbsoluteFaceSize), new Size());
    Rect[] facesArray = faces.toArray();
    Scalar faceRectColor = new Scalar(0, 255, 0, 255);
    for (Rect faceRect : facesArray)
        Imgproc.rectangle(mRgba, faceRect.tl(), faceRect.br(), faceRectColor, 3);
    return mRgba;
}
 
Example 9
Source File: ImageMatchers.java    From onetwo with Apache License 2.0 5 votes vote down vote up
static  public void drawMatchedImage(String destImagePath, String srcImagePath) {
       //将文件读入为OpenCV的Mat格式
       Mat source = Imgcodecs.imread(srcImagePath);
       Mat destImage = Imgcodecs.imread(destImagePath);
	Core.MinMaxLocResult result = matchResult(source, destImage);
	Point matchLoc = result.minLoc;
       //在原图上的对应模板可能位置画一个绿色矩形
       Imgproc.rectangle(source, matchLoc, new Point(matchLoc.x + destImage.width(), matchLoc.y + destImage.height()), new Scalar(0, 255, 0));
       //将结果输出到对应位置
       String srcDir = new File(srcImagePath).getParent();
   	String srcImageName = FileUtils.getFileNameWithoutExt(srcImagePath);
   	String srcExt = FileUtils.getExtendName(srcImagePath);
   	String destImageName = FileUtils.getFileNameWithoutExt(destImagePath);
       Imgcodecs.imwrite(srcDir + "/" + srcImageName + "-matched-"+destImageName+"." + srcExt, source);
}
 
Example 10
Source File: FaceDetectionController.java    From ExoVisix with MIT License 5 votes vote down vote up
/**
 * Method for face detection and tracking
 * 
 * @param frame
 *            it looks for faces in this frame
 */
private void detectAndDisplay(Mat frame)
{
	MatOfRect faces = new MatOfRect();
	Mat grayFrame = new Mat();
	
	// convert the frame in gray scale
	Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
	// equalize the frame histogram to improve the result
	Imgproc.equalizeHist(grayFrame, grayFrame);
	
	// compute minimum face size (20% of the frame height, in our case)
	if (this.absoluteFaceSize == 0)
	{
		int height = grayFrame.rows();
		if (Math.round(height * 0.2f) > 0)
		{
			this.absoluteFaceSize = Math.round(height * 0.2f);
		}
	}
	
	// detect faces
	this.faceCascade.detectMultiScale(grayFrame, faces, 1.1, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE,
			new Size(this.absoluteFaceSize, this.absoluteFaceSize), new Size());
			
	// each rectangle in faces is a face: draw them!
	Rect[] facesArray = faces.toArray();
	for (int i = 0; i < facesArray.length; i++)
	{
		Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(7, 255, 90), 4);
		System.out.println(facesArray[i].tl());	
		System.out.println(facesArray[i].br());	
	}
	
		
	

}
 
Example 11
Source File: ImgprocessUtils.java    From classchecks with Apache License 2.0 5 votes vote down vote up
/**
 * 
* @Title: rectangle 
* @Description: 以检测的人脸图像区域数组在源图像上画矩形框
* @param mImgSRC
* @param rects
* @return
* Mat 
 */
public static Mat rectangle(Mat mImgSRC, Rect ...rects ) {
	Mat tmp = new Mat();
	mImgSRC.copyTo(tmp);
	for(Rect r : rects) {
		Imgproc.rectangle(tmp, new Point(r.x, r.y), new Point(r.x + r.width, r.y + r.height), new Scalar(0, 0, 255));
	}
	
	return tmp;
}
 
Example 12
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 13
Source File: MainActivity.java    From MOAAP with MIT License 5 votes vote down vote up
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

        //Get image size and draw a rectangle on the image for reference
        Mat temp = inputFrame.rgba();
        Imgproc.rectangle(temp, new Point(temp.cols()/2 - 200, temp.rows() / 2 - 200), new Point(temp.cols() / 2 + 200, temp.rows() / 2 + 200), new Scalar(255,255,255),1);
        Mat digit = temp.submat(temp.rows()/2 - 180, temp.rows() / 2 + 180, temp.cols() / 2 - 180, temp.cols() / 2 + 180).clone();
        Core.transpose(digit,digit);
        int predict_result = mnist.FindMatch(digit);
        Imgproc.putText(temp, Integer.toString(predict_result), new Point(50, 150), FONT_HERSHEY_SIMPLEX, 3.0, new Scalar(0, 0, 255), 5);

        return temp;
    }
 
Example 14
Source File: FXController.java    From Face-Recognition with Apache License 2.0 4 votes vote down vote up
/**
	 * Method for face detection and tracking
	 * 
	 * @param frame
	 *            it looks for faces in this frame
	 */
	private void detectAndDisplay(Mat frame)
	{
		MatOfRect faces = new MatOfRect();
		Mat grayFrame = new Mat();
		
		// convert the frame in gray scale
		Imgproc.cvtColor(frame, grayFrame, Imgproc.COLOR_BGR2GRAY);
		// equalize the frame histogram to improve the result
		Imgproc.equalizeHist(grayFrame, grayFrame);
		
		// compute minimum face size (20% of the frame height, in our case)
		if (this.absoluteFaceSize == 0)
		{
			int height = grayFrame.rows();
			if (Math.round(height * 0.2f) > 0)
			{
				this.absoluteFaceSize = Math.round(height * 0.2f);
			}
		}
		
		// detect faces
		this.faceCascade.detectMultiScale(grayFrame, faces, 1.1, 2, 0 | Objdetect.CASCADE_SCALE_IMAGE,
				new Size(this.absoluteFaceSize, this.absoluteFaceSize), new Size());
				
		// each rectangle in faces is a face: draw them!
		Rect[] facesArray = faces.toArray(); 
		for (int i = 0; i < facesArray.length; i++) {
			Imgproc.rectangle(frame, facesArray[i].tl(), facesArray[i].br(), new Scalar(0, 255, 0), 3);

			// Crop the detected faces
			Rect rectCrop = new Rect(facesArray[i].tl(), facesArray[i].br());
			Mat croppedImage = new Mat(frame, rectCrop);
			// Change to gray scale
			Imgproc.cvtColor(croppedImage, croppedImage, Imgproc.COLOR_BGR2GRAY);
			// Equalize histogram
			Imgproc.equalizeHist(croppedImage, croppedImage);
			// Resize the image to a default size
			Mat resizeImage = new Mat();
			Size size = new Size(250,250);
			Imgproc.resize(croppedImage, resizeImage, size);
			
			// check if 'New user' checkbox is selected
			// if yes start collecting training data (50 images is enough)
			if ((newUser.isSelected() && !newname.isEmpty())) {
				if (index<20) {
					Imgcodecs.imwrite("resources/trainingset/combined/" +
					random + "-" + newname + "_" + (index++) + ".png", resizeImage);
				}
			}
//			int prediction = faceRecognition(resizeImage);
			double[] returnedResults = faceRecognition(resizeImage);
			double prediction = returnedResults[0];
			double confidence = returnedResults[1];
			
//			System.out.println("PREDICTED LABEL IS: " + prediction);
			int label = (int) prediction;
			String name = "";
			if (names.containsKey(label)) {
				name = names.get(label);
			} else {
				name = "Unknown";
			}
			
			// Create the text we will annotate the box with:
//            String box_text = "Prediction = " + prediction + " Confidence = " + confidence;
            String box_text = "Prediction = " + name + " Confidence = " + confidence;
            // Calculate the position for annotated text (make sure we don't
            // put illegal values in there):
            double pos_x = Math.max(facesArray[i].tl().x - 10, 0);
            double pos_y = Math.max(facesArray[i].tl().y - 10, 0);
            // And now put it into the image:
            Imgproc.putText(frame, box_text, new Point(pos_x, pos_y), 
            		Core.FONT_HERSHEY_PLAIN, 1.0, new Scalar(0, 255, 0, 2.0));
		}
	}
 
Example 15
Source File: Drawing.java    From FTCVision with MIT License 4 votes vote down vote up
public static void drawRectangle(Mat img, Point topLeft, Point bottomRight, Color color, int thickness) {
    Imgproc.rectangle(img, topLeft, bottomRight, color.getScalarRGBA(), thickness);
}
 
Example 16
Source File: FtcTestOpenCv.java    From FtcSamples with MIT License 4 votes vote down vote up
/**
     * This method is called on every captured camera frame. It will do face detection on the
     * captured frame.
     *
     * @param inputFrame specifies the captured frame object.
     */
    @Override
    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
    {
        final String funcName = "onCameraFrame";
        //
        // Subject the captured frame for face detection. The face detector produces an array
        // of rectangles representing faces detected.
        //
        if (doColor)
        {
            image = inputFrame.rgba();
        }
        else
        {
            image = inputFrame.gray();
            doOverlayImage = false;
        }
//        rotateImage(image, image, 90.0);
        long startTime = System.currentTimeMillis();
        faceDetector.detectMultiScale(image, faceRects);
        long elapsedTime = System.currentTimeMillis() - startTime;

        if (perfCheckEnabled)
        {
            totalProcessingTime += elapsedTime;
            framesProcessed++;
        }

        //
        // We may want to overlay a circle or rectangle on each detected faces or
        // we can overlay a fun image onto a detected face. Play with the code in
        // this for-loop and let your imagination run wild.
        //

        Rect[] rects = faceRects.toArray();
        int maxArea = 0;
        int maxIndex = -1;
        //
        // Draw rectangles on faces found and find the largest face.
        //
        for (int i = 0; i < rects.length; i++)
        {
            //
            // Overlay a rectangle on the detected faces.
            //
            if (overlayRectangle)
            {
                Imgproc.rectangle(image, rects[i].tl(), rects[i].br(), FACE_RECT_COLOR, 3);
            }

            //
            // Find the largest detected face.
            //
            if (doOverlayImage)
            {
                int area = rects[i].width * rects[i].height;
                if (area > maxArea)
                {
                    maxArea = area;
                    maxIndex = i;
                }
            }
        }

        //
        // Overlay an image only on the largest detected face.
        //
        if (doOverlayImage && maxIndex != -1)
        {
            //
            // Scale the fun image to the same size as the face.
            //
            Mat scaledOverlay = new Mat();
            Imgproc.resize(overlayImage, scaledOverlay, rects[maxIndex].size());
            //
            // Overlay the scaled image to the camera image.
            //
            combineImage(image, scaledOverlay, rects[maxIndex].x, rects[maxIndex].y);
        }

        return image;
    }
 
Example 17
Source File: Application.java    From opencv-object-detection with MIT License 4 votes vote down vote up
public static void main(String[] args)
{
    System.loadLibrary("opencv_java340");
    DeepNeuralNetworkProcessor processor = new DeepNeuralNetworkProcessor();
    List<DnnObject> detectObject = new ArrayList<>();
    VideoCapture capturre = new VideoCapture(0);
    while (true)
    {
       Mat frame = new Mat();
       capturre.read(frame);
       detectObject = processor.getObjectsInFrame(frame, false);
       for (DnnObject obj: detectObject)
       {
           Imgproc.rectangle(frame,obj.getLeftBottom(),obj.getRightTop(),new Scalar(255,0,0),1);
       }
       Imgcodecs.imwrite("DetectedObject.jpg",frame);
    }

}
 
Example 18
Source File: FaceDrawerOpenCV.java    From Image-Detection-Samples with Apache License 2.0 4 votes vote down vote up
public static void drawEyeRectangle(Rect eyeArea, Mat matrixRgba) {
    Imgproc.rectangle(matrixRgba, eyeArea.tl(), eyeArea.br(),
            new Scalar(255, 0, 0, 255), 2);
}
 
Example 19
Source File: CVRenderer.java    From faceswap with Apache License 2.0 4 votes vote down vote up
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
        Imgproc.cvtColor(inputFrame.rgba(), displayFrame, Imgproc.COLOR_BGRA2BGR);
        if (this.delegate!=null){
            //TODO: needed so that bg encoding won't interfere with foreground getting a new image
            displayFrame.copyTo(transmitFrame);
            delegate.onCVPreviewAvailable(transmitFrame);
        }
        synchronized (this.faces){
            for (Face face:faces){
                int[] roi = face.realRoi;
                boundryCheck(roi, displayFrame.width(), displayFrame.height());
                Point leftTop=new Point(roi[0], roi[1]);
                Point rightBottom=new Point(roi[2], roi[3]);
                if (face.isRenderring && face.argbMat!=null){
                    rightBottom=new Point(roi[0]+face.argbMat.width(),
                            roi[1]+face.argbMat.height());
                    Rect pRoi = new Rect(roi[0],roi[1],
                            face.argbMat.width(), face.argbMat.height());
                    Log.d("debug", "pRoi : " + pRoi.toString());
                    Log.d("debug", "display frame width : " + displayFrame.width()
                            + " display frame height: " + displayFrame.height());
                    Mat pRoiMat=displayFrame.submat(pRoi);
                    Log.d("debug", "display frame width : " + displayFrame.width()
                            + " display frame height: " + displayFrame.height());

                    face.argbMat.copyTo(pRoiMat);
                }
                Imgproc.rectangle(displayFrame,
                        leftTop,
                        rightBottom,
                        new Scalar(255, 0, 0));
                Imgproc.putText(displayFrame,
                        face.getName(),
                        new Point(roi[0], roi[1]),
                        0,
                        0.8,
                        new Scalar(255,255,0));

            }
        }
        Log.d(LOG_TAG, "rendered");
        return displayFrame;
//                Mat pRoi=mRgba.submat(10,10+replaceImg.width(),10,10+replaceImg.height());
//                Log.d("debug", "mat width: " + pRoi.width() + " height: " + pRoi.height());
//                Log.d("debug", "img width: " + replaceImg.width() + " height: " + replaceImg.height());
//                replaceImg.copyTo(pRoi);
    }
 
Example 20
Source File: CameraActivity.java    From AndroidObjectDetection-OpenCV with MIT License 4 votes vote down vote up
@Override
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {

    Mat frame = inputFrame.rgba();
    Imgproc.cvtColor(frame, frame, Imgproc.COLOR_RGBA2RGB);
    Size frame_size = new Size(416, 416);
    Scalar mean = new Scalar(127.5);

    Mat blob = Dnn.blobFromImage(frame, 1.0 / 255.0, frame_size, mean, true, false);
    //save_mat(blob);
    net.setInput(blob);

    List<Mat> result = new ArrayList<>();
    List<String> outBlobNames = net.getUnconnectedOutLayersNames();

    net.forward(result, outBlobNames);
    float confThreshold = 0.5f;

    for (int i = 0; i < result.size(); ++i) {
        // each row is a candidate detection, the 1st 4 numbers are
        // [center_x, center_y, width, height], followed by (N-4) class probabilities
        Mat level = result.get(i);
        for (int j = 0; j < level.rows(); ++j) {
            Mat row = level.row(j);
            Mat scores = row.colRange(5, level.cols());
            Core.MinMaxLocResult mm = Core.minMaxLoc(scores);
            float confidence = (float) mm.maxVal;
            Point classIdPoint = mm.maxLoc;
            if (confidence > confThreshold) {

                int centerX = (int) (row.get(0, 0)[0] * frame.cols());
                int centerY = (int) (row.get(0, 1)[0] * frame.rows());
                int width = (int) (row.get(0, 2)[0] * frame.cols());
                int height = (int) (row.get(0, 3)[0] * frame.rows());

                int left = (int) (centerX - width * 0.5);
                int top =(int)(centerY - height * 0.5);
                int right =(int)(centerX + width * 0.5);
                int bottom =(int)(centerY + height * 0.5);

                Point left_top = new Point(left, top);
                Point right_bottom=new Point(right, bottom);
                Point label_left_top = new Point(left, top-5);
                DecimalFormat df = new DecimalFormat("#.##");

                int class_id = (int) classIdPoint.x;
                String label= classNames.get(class_id) + ": " + df.format(confidence);
                Scalar color= colors.get(class_id);

                Imgproc.rectangle(frame, left_top,right_bottom , color, 3, 2);
                Imgproc.putText(frame, label, label_left_top, Imgproc.FONT_HERSHEY_SIMPLEX, 1, new Scalar(0, 0, 0), 4);
                Imgproc.putText(frame, label, label_left_top, Imgproc.FONT_HERSHEY_SIMPLEX, 1, new Scalar(255, 255, 255), 2);
            }
        }
    }
    return frame;
}