Reputation: 153
I want to crop(cut off) face that I recognized with opencv3.0 on the image. I tried do this task in Java. Can you help me to do it? Bottom i fetch code that i use to save image with recognize border around a face.
package lol;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.imgproc.Imgproc;
public class Lol {
public static void main(String[] args) {
System.out.println("Hello, OpenCV");
// Load the native library.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
new DetectFaceDemo().run();
}
}
//
// Detects faces in an image, draws boxes around them, and writes the results
// to "faceDetection.png".
//
class DetectFaceDemo {
public void run() {
System.out.println("\nRunning DetectFaceDemo");
// Create a face detector from the cascade file in the resources
// directory.
//CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("C:/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml").getPath());
CascadeClassifier faceDetector = new CascadeClassifier("C:/opencv2/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");
// Mat image = Imgcodecs.imread(getClass().getResource("E:/lol.png").getPath());
Mat image = Imgcodecs.imread("E:/lol.png");
if (faceDetector.empty()){
System.out.println("faceless");
}
if(image.empty()){
System.out.println("imageless");
}
// Detect faces in the image.
// MatOfRect is a special container class for Rect.
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// Draw a bounding box around each face.
for (Rect rect : faceDetections.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));
}
// Save the visualized detection.
String filename = "E:/faceDetection.png";
System.out.println(String.format("Writing %s", filename));
Imgcodecs.imwrite(filename, image);
}
}
Upvotes: 2
Views: 1679
Reputation: 382
You can use found rectangles to crop faces, just like this:
for (Rect rect : faceDetections.toArray()) {
Mat faceImage = image.submat(rect);
Imgcodecs.imwrite(String.valueOf(System.currentTimeMillis()) + ".jpg", faceImage)
}
Upvotes: 4