OpenCV Java开发环境配置
Java 开发的IDE,推荐选择IDEA这个,真的比较好用,我下载的是社区版,免费可用。
安装好以后直接点击打开,选择 New Project
添加本地的OpenCV Java SDK的 Jar文件依赖包
从Project Structure到 Modules 到 Module SDK 添加Jars or Dependence
OpenCV Java 代码测试
OpenCV Java配置好以后,测试代码首先需要加载DLL,然后依赖Java SDK,可以实现图像加载与显示。测试代码如下:
package org.example;
import org.opencv.core.*;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class YOLOv5DNNDetector {
public static void main(String[] args) {
System.load("D:/opencv-4.8.0/opencv/build/java/x64/opencv_java480.dll");
System.out.println("start to read image...");
Mat inputImage = Imgcodecs.imread("D:/images/lena.jpg");
HighGui.imshow("Java OpenCV开发测试", inputImage);
HighGui.waitKey(0);
HighGui.destroyAllWindows();
System.exit(0);
}
}
运行结果如下:
YOLOv5模型部署
基于YOLOv5 7.0版本,完成了对象检测
public static void main(String[] args) {
System.load("D:/opencv-4.8.0/opencv/build/java/x64/opencv_java480.dll");
System.out.println("start to read image...");
String file_path = "D:/python/yolov5-7.0/classes.txt";
try {
Mat inputImage = Imgcodecs.imread("D:/bird_test/city-walk.jpg");
java.util.ArrayList<Rect> boxes = new ArrayList<>();
FileInputStream fis = new FileInputStream(file_path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
YOLOv5DNNDetector detector = new YOLOv5DNNDetector("D:/python/yolov5-7.0/yolov5s.onnx", 0.5f, 0.5f, 640, 640);
String line;
ArrayList<String> map_labels = new ArrayList<>();
while ((line = br.readLine()) != null) {
map_labels.add(line);
}
detector.addAllLabels(map_labels);
detector.infer_image(inputImage, boxes);
HighGui.imshow("OpenCV4.8 for Java YOLOv5对象检测演示", inputImage);
HighGui.waitKey(0);
HighGui.destroyAllWindows();
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}