static void dnn(){
Net net= Dnn.readNetFromONNX("yolov8n.onnx");
String tempPath = "36.jpg";
Mat mat = Imgcodecs.imread(tempPath);
Mat blob = Dnn.blobFromImage(mat, 1/255.0, new Size(640,640));
net.setInput(blob);
Mat predict = net.forward();
Mat mask = predict.reshape(0,1).reshape(0, predict.size(1));
double width = mat.cols() /640.0;
double height = mat.rows() /640.0;
Rect2d[] rect2d = new Rect2d[mask.cols()];
float[] scoref = new float[mask.cols()];
int[] classid = new int[mask.cols()];
for (int i = 0; i < mask.cols(); i++) {
double[] x = mask.col(i).get(0, 0);
double[] y = mask.col(i).get(1, 0);
double[] w = mask.col(i).get(2, 0);
double[] h = mask.col(i).get(3, 0);
rect2d[i] = new Rect2d((x[0]-w[0]/2)*width, (y[0]-h[0]/2)*height, w[0]*width, h[0]*height);
Mat score = mask.col(i).submat(4, predict.size(1)-1, 0, 1);
MinMaxLocResult mmr = Core.minMaxLoc(score);
scoref[i] = (float)mmr.maxVal;
classid[i] = (int) mmr.maxLoc.y;
}
MatOfRect2d bboxes = new MatOfRect2d(rect2d);
MatOfFloat scores = new MatOfFloat(scoref);
MatOfInt indices = new MatOfInt();
Dnn.NMSBoxes(bboxes, scores, 0.3f, 0.5f, indices);
List<Integer> result = indices.toList();
for (Integer integer : result) {
Imgproc.rectangle(mat, new Rect(rect2d[integer].tl(), rect2d[integer].size()),
new Scalar(255, 0, 0), 1);
Imgproc.putText(mat, classid[integer]+":"+scoref[integer], rect2d[integer].tl(),
Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar(0, 255, 0));
}
OpencvUtil.imshow("展示图片", mat);
}
python 资料不少,找着很简单。转过来用java,唉一言难尽啊,可以说基本找不到,对着python c++ 改了一个月终于改的可以了真不容易啊