Java中的图像处理——人脸检测
先决条件:
- Java中的图像处理——读写
- Java中的图像处理——获取和设置像素
- Java中的图像处理——彩色图像到灰度图像的转换
- Java中的图像处理——彩色图像到负图像的转换
- Java中的图像处理——彩色到红绿蓝图像的转换
- Java中的图像处理——彩色图像到棕褐色图像的转换
- Java中的图像处理——创建随机像素图像
- Java中的图像处理——创建镜像
使用 OpenCV 进行人脸检测
在图像处理入门集, Java的BufferedImage类用于处理图像,BufferedImage类的应用仅限于一些操作,即我们可以修改给定输入图像的R、G、B值并生成修改后的图像。图片。对于复杂的图像处理,例如人脸/物体检测,我们将在本文中使用 OpenCV 库。
首先,我们需要为Java设置 OpenCV,我们建议使用 eclipse,因为它易于使用和设置。现在让我们了解一些人脸检测所需的方法。
- CascadeClassifier() :此类用于加载经过训练的级联人脸集,我们将使用这些人脸来检测任何输入图像的人脸。
- Imcodecs.imread()/Imcodecs.imwrite() :这些方法用于读取和写入由 OpenCV 渲染的 Mat 对象的图像。
- Imgproc.rectangle() :用于生成矩形框轮廓检测到的人脸,它需要四个参数——input_image、top_left_point、bottom_right_point、color_of_border。
执行:
Note: The front face cascade file can be downloaded from a local git repository.
输入图像如下:
例子:
Java
// Java Program to Demonstrate Face Detection
// Using OpenCV Library
// Importing package module
package ocv;
// Importing required classes
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.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
// Main class
// FaceDetector
public class GFG {
// Main driver method
public static void main(String[] args)
{
// For proper execution of native libraries
// Core.NATIVE_LIBRARY_NAME must be loaded before
// calling any of the opencv methods
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// Face detector creation by loading source cascade
// xml file using CascadeClassifier and must be
// placed in same directory of the source java file
// File is available here on git as mentioned above
// prior to code
CascadeClassifier faceDetector
= new CascadeClassifier();
faceDetector.load(
"haarcascade_frontalface_alt.xml");
// Reading the input image
Mat image = Imgcodecs.imread("E:\\input.jpg");
// Detecting faces
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image,
faceDetections);
// Creating a rectangular box which represents for
// faces detected
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));
}
// Saving the output image
String filename = "Ouput.jpg";
Imgcodecs.imwrite("E:\\" + filename, image);
// Display message for successful execution of
// program
System.out.print("Face Detected");
}
}
输出:
Face Detected
该程序的输出显示在我的人脸检测前后的图片下方
输出说明:
- 它加载本机 OpenCV 库以使用Java API。创建 CascadeClassifier 的一个实例,将加载分类器的文件的名称传递给它。
- 接下来,在将给定图像和 MatOfRect 对象传递给它的分类器上使用 detectMultiScale 方法。
- MatOfRect 负责处理后进行人脸检测。
- 重复该过程以进行所有面部检测并用矩形标记图像,最后,图像被保存为“output.png”文件。