我想使用Basler相机在C#中将一个PictureBox放在WinForm上。 但我想将IGrabImage转换为Mat。因为我想用Mat。将它插入PictureBox。
请告诉我你的提示或解决方案。
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图片:
答案 0 :(得分:1)
这是将IGrabResult转换为OpenCvSharp.Mat的正确方法。 我没有转换器就没有尝试过,但是您的主要问题是新Mat(..)参数的顺序。在OpenCV中,首先声明行,然后声明列。这意味着首先是高度,然后是宽度。彩色图像的MatType也像@Nyerguds所说的那样是错误的。必须是CV_8UC3。
更正的代码:
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);
}