简体   繁体   English

Basler 相机图像 OpenCvSharp3

[英]Basler camera image OpenCvSharp3

I want to put a PictureBox on WinForm in C # using a Basler camera.我想使用 Basler 相机在 C# 中的 WinForm 上放置一个 PictureBox。 But I want to convert IGrabImage to Mat.但我想将 IGrabImage 转换为 Mat。 because I want to insert it into the PictureBox using Mat.因为我想使用 Mat 将它插入到 PictureBox 中。

Please let me know your hint or solution.请让我知道您的提示或解决方案。

PixelDataConverter converter = new PixelDataConverter();

    public Form1() {
        InitializeComponent();
        using (Camera camera = new Camera())
        {
            camera.CameraOpened += Configuration.AcquireContinuous;

            camera.Open();
            camera.Parameters[PLCameraInstance.MaxNumBuffer].SetValue(5);
            camera.StreamGrabber.Start();

            IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);

            using (grabResult)
            {
                if (grabResult.GrabSucceeded) {
                    Mat rtnMat = convertToMat(grabResult);                       
                    Cv2.ImShow("test", rtnMat);
                    pictureBox1.Image = BitmapConverter.ToBitmap(frame);
                }
            }

            camera.StreamGrabber.Stop();
            camera.Close();
        }
    }

    private Mat convertToMat(IGrabResult rtnGrabResult) {
        IImage image = rtnGrabResult;
        converter.OutputPixelFormat = PixelType.BGR8packed;
        byte[] buffer = image.PixelData as byte[];
        return new Mat(rtnGrabResult.Width, rtnGrabResult.Height, MatType.CV_8UC1, buffer);
    }

Basler Image:巴斯勒图片:

巴斯勒影像

OpenCvSharp Image: OpenCvSharp 图片:

OpenCvSharp 图像

Here is the correct way to convert an IGrabResult into an OpenCvSharp.Mat.这是将 IGrabResult 转换为 OpenCvSharp.Mat 的正确方法。 I didn't try it without the converter but your main problem was the sequence of the new Mat(..) arguments.我没有在没有转换器的情况下尝试过,但您的主要问题是新 Mat(..) 参数的顺序。 In OpenCV, you declare the rows first and then the columns.在 OpenCV 中,首先声明行,然后声明列。 That means first height and then width.这意味着首先是高度,然后是宽度。 And also the MatType for an colored image was wrong like @Nyerguds said.而且像@Nyerguds 说的那样,彩色图像的 MatType 也是错误的。 It has to be CV_8UC3.它必须是 CV_8UC3。

Corrected code:更正的代码:

private Mat convertToMat(IGrabResult rtnGrabResult) {
        converter.OutputPixelFormat = PixelType.BGR8packed;
        byte[] buffer = new byte[conv.GetBufferSizeForConversion(rtnGrabResult];
        converter.Convert(buffer, rtnGrabResult);
        return new Mat(rtnGrabResult.Height, rtnGrabResult.Width, MatType.CV_8UC3, buffer);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM