ivilson / Yolov7net

Yolo Detector for .Net 8
83 stars 25 forks source link

how to preload model and predict image separately ? #5

Closed phamvangiao closed 2 months ago

phamvangiao commented 1 year ago

image

if we separate the loading mode and predict the image, the prediction time is faster ? Thanks so much ivilson !

terasadi commented 1 year ago

On this sample Yolov7 model is loaded only one time and you keep using the same loaded model instance to handle with your code/inferences.

`

public partial class Form1 : Form
{
    Yolov7? yolo = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (yolo == null)
        {
            // init Yolov7 with onnx (include nms results)file path
            yolo = new Yolov7("./assets/best.onnx", true);

            // setup labels of onnx model 
            //yolo.SetupYoloDefaultLabels();   // use custom trained model should use your labels like: yolo.SetupLabels(string[] labels)
            string[] labels = { "myCustomLabel" };
            yolo.SetupLabels(labels);
        }

        var dirPos = Directory.GetFiles(@"./Assets/val/images/pos");
        var dirNeg = Directory.GetFiles(@"./Assets/val/images/neg");

        var dtNow = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

        foreach (var item in dirPos)
        {
            if (Path.GetExtension(item).Equals(".jpg") ||
                Path.GetExtension(item).Equals(".png"))
            {
                using var image = Image.FromFile(item);
                var predictions = yolo.Predict(image);

                // draw box
                using var graphics = Graphics.FromImage(image);
                foreach (var prediction in predictions) // iterate predictions to draw results
                {
                    double score = Math.Round(prediction.Score, 2);
                    graphics.DrawRectangles(new Pen(prediction.Label.Color, 1), new[] { prediction.Rectangle });
                    var (x, y) = (prediction.Rectangle.X - 3, prediction.Rectangle.Y - 23);
                    graphics.DrawString($"{prediction.Label.Name} ({score})",
                                    new Font("Consolas", 16, GraphicsUnit.Pixel), new SolidBrush(prediction.Label.Color),
                                    new PointF(x, y));
                }

                var fileName = Path.GetFileName(item);
                var path = Path.GetDirectoryName(item);
                image.Save(Path.Combine(path, (fileName + "_" + dtNow + ".png")), ImageFormat.Png);
            }
        }
    }
}

`