如何在Java中实现图像识别
package cn.juwatech.example;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ImageRecognition {
static {
// 加载OpenCV库
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) {
// 读取图像
String imagePath = "path/to/your/";
Mat image = Imgcodecs.imread(imagePath);
// 图像预处理(灰度化、边缘检测等)
Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, Imgproc.COLOR_BGR2GRAY);
Imgproc.GaussianBlur(grayImage, grayImage, new Size(3, 3), 0);
// 图像识别处理(示例:检测人脸)
String cascadePath = "path/to/opencv/haarcascade_frontalface_default.xml";
CascadeClassifier faceDetector = new CascadeClassifier(cascadePath);
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(grayImage, faceDetections);
System.out.println(String.format("检测到 %s 张人脸", faceDetections.toArray().length));
// 在图像上绘制检测到的人脸
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), 2);
}
// 保存处理后的图像
String outputImagePath = "path/to/output/";
Imgcodecs.imwrite(outputImagePath, image);
System.out.println("图像处理完成,结果保存在:" + outputImagePath);
}
}