I detected the face in the image using opencv 2.4.10 in java
I put my face detection code.
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.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class FaceDetector {
public static void main(String[] args)throws Exception {
int x,y,height,width;
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
System.out.println("\nRunning FaceDetector");
//CascadeClassifier faceDetector = new CascadeClassifier(FaceDetector.class.getResource("haarcascade_frontalface_alt.xml").getPath());
CascadeClassifier faceDetector=new CascadeClassifier();
faceDetector.load("C:/opencv-2.4.10/opencv/sources/data/haarcascades/haarcascade_frontalface_alt.xml");
//System.out.println(""+faceDetector);
// Mat image = Highgui .imread(FaceDetector.class.getResource("D:/shekar.jpg").getPath());
Mat image = Highgui .imread("D:/Eclipse - New Juno/New Juno Projects/detectface/man1.jpg");
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
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));
}
String filename = "china.jpg";
System.out.println(String.format("Writing %s", filename));
Highgui.imwrite(filename, image);
}
}
Now i want to crop the detected face and save it as new jpg image in opencv java.
Crop code is
Rect rectCrop = new Rect(x, y, width, height);
Mat image_roi = image(rectCrop);
image_roi.copyTo(cropimage);
imwrite("cropimage.jpg",image_roi);
The error is
The method image(Rect) is undefined for the type FaceDetector The method imwrite(String, Mat) is undefined for the type FaceDetector
Please anyone help me to solve this.
Thanks
Explanation: We use cv2. CascadeClassifier for load haarcascade file in face_cascade. detectMultiScale() function used for detect faces.It takes 3 parameters: Gray: input image(gray scale image)
how to crop multiple faces? dhvani.
for (Rect rect : face_Detections.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));
rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height);
}
Mat image_roi = new Mat(image,rectCrop);
Highgui.imwrite("C:\\cropimage_912.jpg",image_roi);
}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With