C# 获取baser工业相机

本文提供了一个名为BaslerClass的C#类,用于管理Basler相机,包括连接指定序列号的相机、开始和停止采集、设置曝光时间和触发模式等功能。此外,还介绍了读取图像数据并进行格式转换的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、新建 baslerClass类

  1、 引用Basler.Pylon.dll
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HalconDotNet;
using Basler.Pylon;
using System.Runtime.InteropServices;

 
    class BaslerClass
    {
        List<ICameraInfo> allCameras = null;//创建ICameraInfo对象的列表,用于保存遍历到的所有相机信息
        Camera myCamera = null;//创建相机对象
        HImage image = null;
        
        public BaslerClass(string sn)
        {
        }

        public int connectCamera(string id)//连接相机,返回-1为失败,0为成功
        {
            string m_SerialNumber = "";//接收设备返回的序列号
            allCameras = CameraFinder.Enumerate();//获取所有相机设备
            for (int i = 0; i < allCameras.Count; i++)
            {
                try
                {
                    if (allCameras[i][CameraInfoKey.SerialNumber] == id)
                    {
                        //如果当前相机信息中序列号是指定的序列号,则实例化相机类
                        myCamera = new Camera(allCameras[i]);
                        myCamera.Open();//打开相机
                        return 0;
                    }
                    continue;
                }
                catch
                {
                    return -1;
                }
            }
            return -1;
        }
        
        public int startCamera()//相机开始采集,返回-1为失败,0为成功
        {
            try
            {
                myCamera.StreamGrabber.Start();
            }
            catch
            {
                return -1;
            }
            return 0;
        }
        
        public int stopCamera()//停止相机采集,返回-1为失败,1为成功
        {
            try
            {
                myCamera.StreamGrabber.Stop();
            }
            catch
            {
                return -1;
            }
            return 0;
        }
        
        public int closeCamera()//关闭相机,返回-1为失败,1为成功
        {
            try
            {
                myCamera.Close();
            }
            catch
            {
                return -1;
            }
            return 0;
        }
        
        public int softTrigger()//发送软触发命令
        {
            try
            {
                myCamera.ExecuteSoftwareTrigger();
            }
            catch
            {
                return -1;
            }
            return 0;
        }
        
        public HImage ReadBuffer()//读取相机buffer并生成HImage格式的图像
        {
            IGrabResult grabResult = myCamera.StreamGrabber.RetrieveResult(4000, TimeoutHandling.ThrowException);//读取buffer,超时时间为4000ms
            image = new HImage();
            using (grabResult)
            {
                if (grabResult.GrabSucceeded)
                {
                    if (IsMonoData(grabResult))
                    {
                        //如果是黑白图像,则利用GenImage1算子生成黑白图像
                        byte[] buffer = grabResult.PixelData as byte[];
                        IntPtr p = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
                        image.GenImage1("byte", grabResult.Width, grabResult.Height, p);
                    }
                    else
                    {
                        if (grabResult.PixelTypeValue != PixelType.RGB8packed)
                        {
                            //如果图像不是RGB8格式,则将图像转换为RGB8,然后生成彩色图像
                            //因为GenImageInterleaved算子能够生成的图像的数据,常见的格式只有RGB8
                            //如果采集的图像是RGB8则不需转换,具体生成图像方法请自行测试编写。
                            byte[] buffer_rgb = new byte[grabResult.Width * grabResult.Height * 3];
                            Basler.Pylon.PixelDataConverter convert = new PixelDataConverter();
                            convert.OutputPixelFormat = PixelType.RGB8packed;
                            convert.Convert(buffer_rgb, grabResult);
                            IntPtr p = Marshal.UnsafeAddrOfPinnedArrayElement(buffer_rgb, 0);
                            image.GenImageInterleaved(p, "rgb", grabResult.Width, grabResult.Height, 0, "byte", grabResult.Width, grabResult.Height, 0, 0, -1, 0);
                        }
                    }
                    return image;
                }
                else
                {
                    return null;
                }
            }
        }
        
        public int setExposureTime(longExposureTimeNum)//设置曝光时间us
        {
            try
            {
                myCamera.Parameters[PLCamera.ExposureTimeAbs].SetValue(ExposureTimeNum);
            }
            catch
            {
                return -1;
            }
            return 0;
        }

        public int pixelFormat(uint pixelType)//设置图像格式
        {
            //1:Mono8 2:彩色YUV422
            try
            {
                if (pixelType == 1)
                {
                    myCamera.Parameters[PLCamera.PixelFormat].TrySetValue(PLCamera.PixelFormat.Mono8);
                }
                else if(pixelType == 2)
                {
                    myCamera.Parameters[PLCamera.PixelFormat].TrySetValue(PLCamera.PixelFormat.YUV422Packed);
                }
            }
            catch
            {
                return -1;
            }
            return 0;
        }
        
        public int setHeight(longheight)//设置图像高度
        {
            try
            {
                if (myCamera.Parameters[PLCamera.Height].TrySetValue()height))
                    return 0;
                else
                    return  -1;
            }
            catch
            {
                return -1;
            }
        }
        
        public int setWidth(longwidth)//设置图像宽度
        {
            try
            {
                if (myCamera.Parameters[PLCamera.Width].TrySetValue(width))
                    return 0;
                else
                    return -1;
            }
            catch
            {
                return -1;
            }
        }
        
        public int setOffsetX(longoffsetX)//设置图像水平偏移
        {
            try
            {
                if (myCamera.Parameters[PLCamera.OffsetX].TrySetValue(offsetX))
                    return 0;
                else
                    return -1;
            }
            catch
            {
                return -1;
            }
        }
        
        public int setOffsetY(longoffsetY)//设置图像竖直偏移
        {
            try
            {
                if (myCamera.Parameters[PLCamera.OffsetY].TrySetValue(offsetY))
                    return 0;
                else
                    return -1;
            }
            catch
            {
                return -1;
            }
        }
    
        public int setTriggerMode(uint TriggerModeNum)//设置触发模式
        {
            //1:为On 触发模式
            //0:Off 触发模式
            try
            {
                if (myCamera.Parameters[PLCamera.TriggerMode].TrySetValue(TriggerModeNum==1?"On":"Off"))
                    return 0;
                else
                    return -1;
            }
            catch
            {
                return -1;
            }
        }
        
        public int closeBalanceAuto()//关闭自动白平衡
        {
            try
            {
                myCamera.Parameters[PLCamera.BalanceWhiteAuto].TrySetValue("Off");
            }
            catch
            {
                return -1;
            }
            return 0;
        }
        
        public int setTriggerSource(uint TriggerSourceNum)//设置触发源
        {
            //直接改为软触发,此处已经写死
            try
            {
                if (myCamera.Parameters[PLCamera.TriggerSource].TrySetValue("Software"))
                    return 0;
                else
                    return -1;
            }
            catch
            {
                return -1;
            }
        }
        
         private Boolean IsMonoData(IGrabResult iGrabResult)//判断图像是否为黑白格式
        {
            switch (iGrabResult.PixelTypeValue)
            {
                case PixelType.Mono1packed:
                case PixelType.Mono2packed:
                case PixelType.Mono4packed:
                case PixelType.Mono8:
                case PixelType.Mono8signed:
                case PixelType.Mono10:
                case PixelType.Mono10p:
                case PixelType.Mono10packed:
                case PixelType.Mono12:
                case PixelType.Mono12p:
                case PixelType.Mono12packed:
                case PixelType.Mono16:
                    return true;
                default:
                    return false;
            }
        }
 }

SDK调用方法:
BaslerSDK camera = new BaslerSDKcamera ();//创建相机对象并实例化
camera.connectCamera(“123456”);//连接相机,传入相机序列号123456
camera.startCamera();//开启相机采集
camera.setExposureTime(10000);//设置曝光时间为10ms
camera.softTrigger();//发送软触发采集图像
Himage image=camera.readImage();//获取采集到且转换后的图像
camera.stopCamera();//停止相机采集
————————————————
版权声明:本文为优快云博主「大_樱_桃」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.youkuaiyun.com/biggestcherry/article/details/98884073

以下是一个示例的C#窗体程序,结合Halcon调用工业相机实现实时对图像中的圆形识别,并对每个圆形提取RGB值后,分别绘制RGB值变化曲线的代码: ```csharp using HalconDotNet; using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace CircleDetection { public partial class MainForm : Form { private HWindowControl windowControl; private HFramegrabber framegrabber; private List<List<double>> rgbValues; public MainForm() { InitializeComponent(); // 创建Halcon窗口控件 windowControl = new HWindowControl(); windowControl.Dock = DockStyle.Fill; Controls.Add(windowControl); // 创建图像采集对象 framegrabber = new HFramegrabber("GigEVision", 1, 1, 0, 0, 0, 0, "default", -1, "default", -1, "false", "default", "default", "default"); // 打开图像采集设备 framegrabber.Open(); // 初始化RGB值列表 rgbValues = new List<List<double>>(); // 启动定时器 timer.Start(); } private void timer_Tick(object sender, EventArgs e) { // 采集图像 HImage image = framegrabber.GrabImageAsync(-1); // 转换为灰度图像 HImage grayImage = image.Rgb1ToGray(); // 边缘检测 HRegion edges = grayImage.EdgesSubPix("canny", 50, 80, 3); // 查找圆形 HTuple rows, columns, radius; HOperatorSet.FindCircle(edges, out rows, out columns, out radius); // 获取图像的RGB数据 HTuple pointer, type, width, height; HOperatorSet.GetImagePointer3(image, out pointer, out type, out width, out height); byte[] imageData = pointer.ToDArr().ToByteArray(); // 存储当前帧的RGB值 List<double> frameRGBValues = new List<double>(); // 遍历每个圆形 for (int i = 0; i < rows.Length; i++) { double row = rows[i].D; double column = columns[i].D; double circleRadius = radius[i].D; // 提取圆形RGB值 int centerX = (int)row; int centerY = (int)column; int circleSize = (int)circleRadius; double sumR = 0, sumG = 0, sumB = 0; for (int x = centerX - circleSize; x <= centerX + circleSize; x++) { for (int y = centerY - circleSize; y <= centerY + circleSize; y++) { int index = (x * (int)width + y) * 3; byte red = imageData[index]; byte green = imageData[index + 1]; byte blue = imageData[index + 2]; // 累加RGB值 sumR += red; sumG += green; sumB += blue; } } // 计算平均RGB值 double avgR = sumR / ((circleSize * 2 + 1) * (circleSize * 2 + 1)); double avgG = sumG / ((circleSize * 2 + 1) * (circleSize * 2 + 1)); double avgB = sumB / ((circleSize * 2 + 1) * (circleSize * 2 + 1)); // 存储RGB值到当前帧的列表 frameRGBValues.Add(avgR); frameRGBValues.Add(avgG); frameRGBValues.Add(avgB); // 绘制圆形和RGB值 windowControl.HalconWindow.DispObj(edges); windowControl.HalconWindow.SetColor("red"); windowControl.HalconWindow.DispCircle(row, column, circleRadius); windowControl.HalconWindow.SetColor("yellow"); windowControl.HalconWindow.DispText(row, column, $"{avgR:0.00}, {avgG:0.00}, {avgB:0.00}"); } // 存储当前帧的RGB值到总列表 rgbValues.Add(frameRGBValues); // 绘制RGB值变化曲线 DrawRGBValueCurve(); // 释放资源 grayImage.Dispose(); edges.Dispose(); image.Dispose(); } private void DrawRGBValueCurve() { Bitmap bitmap = new Bitmap(rgbValues.Count, 256); Graphics graphics = Graphics.FromImage(bitmap); for (int i = 0; i < rgbValues.Count; i++) { List<double> values = rgbValues[i]; for (int j = 0; j < values.Count; j += 3) { double r = values[j]; double g = values[j + 1]; double b = values[j + 2]; graphics.DrawLine(Pens.Red, i, 255, i, 255 - (int)r); graphics.DrawLine(Pens.Green, i, 255, i, 255 - (int)g); graphics.DrawLine(Pens.Blue, i, 255, i, 255 - (int)b); } } pictureBox.Image = bitmap; } protected override void OnFormClosing(FormClosingEventArgs e) { // 关闭图像采集设备 framegrabber.Close(); base.OnFormClosing(e); } } } ``` 在上述代码中,我们使用了一个定时器来实现定时采集图像和处理。每次定时器触发时,我们采集图像,进行边缘检测和圆形识别,提取圆形的RGB值,并在Halcon窗口中绘制圆形和RGB值。同时,我们将每个帧的RGB值存储在`rgbValues`列表中,并调用`DrawRGBValueCurve`方法绘制RGB值变化曲线。最后,我们在窗体上的PictureBox控件中显示RGB值变化曲线。 请注意,在使用Halcon对象和图像采集设备后,需要在窗体关闭时释放相应的资源。同时,确保你已正确引用HalconDotNet库,并且根据你的实际情况进行相应的配置和参数调整。 此外,你需要在窗体上添加以下控件: - 一个名为`windowControl`的Halcon窗口控件(类型为HWindowControl),用于显示图像和绘制圆形。 - 一个名为`timer`的定时器控件(类型为Timer),用于定时采集和处理图像。 - 一个名为`pictureBox`的PictureBox控件,用于显示RGB值变化曲线。 确保将上述控件添加到窗体上,并设置相应的属性和事件处理程序。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值