我想裁剪(切断)我在图像上用opencv3.0识别的脸部。我尝试用Java完成这项任务。 你能帮帮我吗? 底部我获取用于保存图像的代码,并识别面部周围的边框。
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);
}
}
答案 0 :(得分:3)
您可以使用找到的矩形裁剪面部,如下所示:
for (Rect rect : faceDetections.toArray()) {
Mat faceImage = image.submat(rect);
Imgcodecs.imwrite(String.valueOf(System.currentTimeMillis()) + ".jpg", faceImage)
}