使用ONNX模型实现M-LSD算法
使用ONNX模型实现M-LSD算法的代码如下(使用OpenCvSharp读写图像):
static unsafe void Main(string[] args)
{var OnnxSession = new InferenceSession(@"Models\model_512x512_large.onnx");int TrainImageWidth = 512;int TrainImageHeight = 512;int MapSize = 256;Directory.CreateDirectory("Results");DirectoryInfo directoryInfo = new DirectoryInfo("Images");FileInfo[] fileInfos = directoryInfo.GetFiles();foreach (FileInfo fileInfo in fileInfos){Console.WriteLine(fileInfo.Name);Mat image = new Mat(fileInfo.FullName);Mat resize_image = new Mat();Cv2.Resize(image, resize_image, new Size(TrainImageWidth, TrainImageHeight));float h_ratio = (float)image.Rows / TrainImageHeight;float w_ratio = (float)image.Cols / TrainImageWidth;int row = resize_image.Rows;int col = resize_image.Cols;float[] input_tensor_data = new float[1 * 4 * row * col];int k = 0;for (int i = 0; i < row; i++){for (int j = 0; j < col; j++){for (int c = 0; c < 3; c++){float pix = ((byte*)resize_image.Ptr(i).ToPointer())[j * 3 + c];input_tensor_data[k] = pix;k++;}input_tensor_data[k] = 1;k++;}}var inputTensor = new DenseTensor<float>(input_tensor_data, new[] { 1, TrainImageWidth, TrainImageHeight, 4 });var inputContainer = new List<NamedOnnxValue>{NamedOnnxValue.CreateFromTensor("input_image_with_alpha:0", inputTensor)};var resultInfer = OnnxSession.Run(inputContainer);var resultsOnnxvalue = resultInfer.ToArray();int[] pts = resultsOnnxvalue[0].AsTensor<int>().ToArray();float[] pts_score = resultsOnnxvalue[1].AsTensor<float>().ToArray();float[] vmap = resultsOnnxvalue[2].AsTensor<float>().ToArray();var segments = new List<LineSegmentPoint>();for (int i = 0; i < pts_score.Length; i++){int y = pts[i * 2];int x = pts[i * 2 + 1];float disp_x_start = vmap[0 + y * MapSize * 4 + x * 4];float disp_y_start = vmap[1 + y * MapSize * 4 + x * 4];float disp_x_end = vmap[2 + y * MapSize * 4 + x * 4];float disp_y_end = vmap[3 + y * MapSize * 4 + x * 4];double distance = Math.Sqrt(Math.Pow((disp_x_start - disp_x_end) * 2 * w_ratio, 2) + Math.Pow((disp_y_start - disp_y_end) * 2 * h_ratio, 2));if (pts_score[i] > 0.5 && distance > 15){float x_start = (x + disp_x_start) * 2 * w_ratio;float y_start = (y + disp_y_start) * 2 * h_ratio;float x_end = (x + disp_x_end) * 2 * w_ratio;float y_end = (y + disp_y_end) * 2 * h_ratio;segments.Add(new LineSegmentPoint(new Point(x_start, y_start), new Point(x_end, y_end)));}}Mat result = image.Clone();for (int i = 0; i < segments.Count; i++){var line = segments[i];Cv2.Line(result, line.P1.X, line.P1.Y, line.P2.X, line.P2.Y, new Scalar(0, 0, 255), 2);}result.SaveImage(Path.Combine("Results", fileInfo.Name));}Console.WriteLine("完成");
}
完整Demo:
M-LSD直线检测算法C#实现(包含ONNX模型)资源-CSDN文库
实现效果如下: