VisionCamera.cs 12.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Asa.CameraFactory;
using System.Drawing.Imaging;
using Basler.Pylon;

namespace Asa.Basler
{
    /// <summary>
    /// 机器视觉面阵相机
    /// </summary>
    public class VisionCamera : CameraFactory.ICamera
    {
        /// <summary>
        /// 当前相机
        /// </summary>
        private global::Basler.Pylon.Camera[] cameraCurr;
        /// <summary>
        /// 所有相机列表
        /// </summary>
        private List<ICameraInfo> cameraAll;
        /// <summary>
        /// 所有相机的名称
        /// </summary>
        private List<string> cameraName;

        private byte[] _buffer = null;
        private Bitmap _image = null;
        private IntPtr _handle = IntPtr.Zero;
        private PixelFormat _format = PixelFormat.Format24bppRgb;

        /// <summary>
        /// 机器视觉面阵相机
        /// </summary>
        /// <param name="logName"></param>
        public VisionCamera(string logName = "Basler.VisionCamera")
        {
            cameraName = new List<string>();
            if (!string.IsNullOrWhiteSpace(logName))
                Log.Load(logName);
        }



        /// <summary>
        /// 相机名称
        /// </summary>
        public string[] Name { get => cameraName.ToArray(); }

        /// <summary>
        /// 相机总数
        /// </summary>
        public int Count { get => cameraName.Count; }

        /// <summary>
        /// 相机是否打开
        /// </summary>
        public bool[] IsOpen { private set; get; }

        /// <summary>
        /// 图像分辨率
        /// </summary>
        public Size[] Size { private set; get; }
        
        /// <summary>
        /// 相机获取到的图像
        /// </summary>
        public Bitmap Image { private set; get; }

        IntPtr CameraFactory.ICamera.Preview { set; get; } = IntPtr.Zero;



        /// <summary>
        /// 加载
        /// </summary>
        /// <returns></returns>
        public bool Load()
        {
            try
            {
                cameraAll = CameraFinder.Enumerate();

                //相机名称
                cameraName.Clear();
                foreach (ICameraInfo info in cameraAll)
                    cameraName.Add(string.Format("{0}({1})", info[CameraInfoKey.ModelName], info[CameraInfoKey.SerialNumber]));

                IsOpen = new bool[cameraName.Count];
                Size = new Size[cameraName.Count];
                cameraCurr = new global::Basler.Pylon.Camera[cameraName.Count];
                Log.Info("Load OK");
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("Load", ex);
                return false;
            }
        }

        /// <summary>
        /// 释放所有
        /// </summary>
        public void Dispose()
        {
            CloseAll();
        }

        /// <summary>
        /// 打开所有摄像机
        /// </summary>
        /// <returns></returns>
        public bool OpenAll()
        {
            bool rtn = false;
            for (int i = 0; i < cameraName.Count; i++)
            {
                rtn = OpenDevice(i);
                if (!rtn) break;
            }
            return rtn;
        }

        /// <summary>
        /// 关闭所有摄像机
        /// </summary>
        public void CloseAll()
        {
            for (int i = 0; i < cameraName.Count; i++)
                CloseDevice(i);
        }

        /// <summary>
        /// 打开摄像机
        /// </summary>
        /// <param name="cameraIndex"></param>
        /// <returns></returns>
        public bool Open(int cameraIndex)
        {
            return OpenDevice(cameraIndex);
        }

        /// <summary>
        /// 打开相机
        /// </summary>
        /// <param name="cameraName"></param>
        /// <returns></returns>
        public bool Open(string cameraName)
        {
            int idx = this.cameraName.FindIndex(s => s == cameraName);
            return Open(idx);
        }

        /// <summary>
        /// 关闭摄像机
        /// </summary>
        /// <param name="cameraIndex"></param>
        public void Close(int cameraIndex)
        {
            CloseDevice(cameraIndex);
        }

        /// <summary>
        /// 抓取所有摄像机一张图像
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public bool GrabOne(out Bitmap[] bmp)
        {
            bmp = new Bitmap[cameraCurr.Length];
            bool rtn = false;
            for (int i = 0; i < cameraCurr.Length; i++)
            {
                rtn = GrabDevice(i, out bmp[i]);
                if (!rtn) break;
            }
            return rtn;
        }

        /// <summary>
        /// 抓取一张图像
        /// </summary>
        /// <param name="cameraIndex">相机索引</param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex)
        {
            bool rtn = GrabDevice(cameraIndex, out Bitmap bmp);
            Image = bmp;
            return rtn;
        }

        /// <summary>
        /// 抓取一张图像
        /// </summary>
        /// <param name="cameraIndex">相机索引</param>
        /// <param name="bmp">Bitmap图像</param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex, out Bitmap bmp)
        {
            return GrabDevice(cameraIndex, out bmp);
        }

        /// <summary>
        /// 抓取一张图像
        /// </summary>
        /// <param name="cameraName">相机名称</param>
        /// <param name="bmp">Bitmap图像</param>
        /// <returns></returns>
        public bool GrabOne(string cameraName, out Bitmap bmp)
        {
            bmp = null;
            int index = this.cameraName.FindIndex(match => match.Contains(cameraName));
            if (index == -1) return false;
            return GrabDevice(index, out bmp);
        }

        /// <summary>
        /// 抓取一张图像字节
        /// </summary>
        /// <param name="cameraIndex">相机索引</param>
        /// <param name="buff">图像字节数组</param>
        /// <param name="format"></param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex, out byte[] buff, out PixelFormat format)
        {
            return GrabDevice(cameraIndex, out buff, out format);
        }

        /// <summary>
        /// 抓取一张图像指针
        /// </summary>
        /// <param name="cameraIndex"></param>
        /// <param name="handle"></param>
        /// <param name="format"></param>
        /// <returns></returns>
        public bool GrabOne(int cameraIndex, out IntPtr handle, out PixelFormat format)
        {
            return GrabDevice(cameraIndex, out handle, out format);
        }



        private bool OpenDevice(int idx)
        {
            try
            {
                if (cameraCurr[idx] != null)
                    CloseDevice(idx);

                cameraCurr[idx] = new global::Basler.Pylon.Camera(cameraAll[idx]);
                //cameraCur.ConnectionLost += OnConnectionLost;
                //cameraCur.CameraOpened += OnCameraOpened;
                //cameraCur.CameraClosed += OnCameraClosed;
                //cameraCur.StreamGrabber.GrabStarted += OnGrabStarted;
                //cameraCurr[idx].StreamGrabber.ImageGrabbed += OnImageGrabbed;
                //cameraCur.StreamGrabber.GrabStopped += OnGrabStopped;
                cameraCurr[idx].Open();
                int w = Convert.ToInt32(cameraCurr[idx].Parameters[PLCamera.Width].GetValue());
                int h = Convert.ToInt32(cameraCurr[idx].Parameters[PLCamera.Height].GetValue());
                Size[idx] = new Size(w, h);

                cameraCurr[idx].Parameters[PLCamera.UserSetSelector].SetValue(PLCamera.UserSetSelector.UserSet1);  //加载用户设置1
                bool bln = cameraCurr[idx].Parameters[PLCamera.UserSetLoad].TryExecute();  //执行设置

                IsOpen[idx] = true;
                Log.Info(string.Format("{0} OpenDevice OK", cameraName[idx]));
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("OpenDevice", ex);
                return false;
            }
        }

        private void CloseDevice(int idx)
        {
            if (cameraCurr[idx] == null) return;
            IsOpen[idx] = false;
            cameraCurr[idx].Close();
            cameraCurr[idx].Dispose();
            cameraCurr[idx] = null;
            Log.Info("Close OK " + cameraName[idx]);
        }

        private bool GrabDevice(int idx, out Bitmap bmp)
        {
            bmp = null;

            try
            {
                ImageCapture(idx);
                bmp = new(_image);
                Log.Info(string.Format("{0} GrabDevice OK", cameraName[idx]));
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("GrabDevice", ex);
                return false;
            }
        }

        private bool GrabDevice(int idx, out byte[] buff, out PixelFormat format)
        {
            buff = null;
            format = PixelFormat.Undefined;

            try
            {
                ImageCapture(idx);
                buff = _buffer;
                format = _format;
                Log.Info(string.Format("{0} GrabDevice OK", cameraName[idx]));
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("GrabDevice", ex);
                return false;
            }
        }

        private bool GrabDevice(int idx, out IntPtr handle, out PixelFormat format)
        {
            handle = IntPtr.Zero;
            format = PixelFormat.Undefined;

            try
            {
                ImageCapture(idx);
                handle = _handle;
                format = _format;
                Log.Info(string.Format("{0} GrabDevice OK", cameraName[idx]));
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("GrabDevice", ex);
                return false;
            }
        }

        private void ImageCapture(int idx)
        {
            cameraCurr[idx].Parameters[PLCamera.AcquisitionMode].SetValue(PLCamera.AcquisitionMode.SingleFrame);
            IGrabResult grabResult = cameraCurr[idx].StreamGrabber.GrabOne(5000);
            if (!grabResult.IsValid)
            {
                Log.Info(string.Format("{0} GrabOne failed,{1}", cameraName[idx], grabResult.ErrorCode));
                return;
            }

            _image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
            BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            IntPtr ptrBmp = bmpData.Scan0;
            int picSize = bmpData.Stride * grabResult.Height;
            PixelDataConverter conv = new() { OutputPixelFormat = PixelType.BGR8packed };
            conv.Convert(ptrBmp, picSize, grabResult);
            _buffer = new byte[picSize];
            System.Runtime.InteropServices.Marshal.Copy(ptrBmp, _buffer, 0, picSize);
            _image.UnlockBits(bmpData);
            _handle = ptrBmp;
            _format = PixelFormat.Format24bppRgb;
        }











        //private void OnImageGrabbed(object sender, ImageGrabbedEventArgs e)
        //{
        //    try
        //    {
        //        IGrabResult grabResult = e.GrabResult;
        //        if (!grabResult.IsValid) return;

        //        _image = new Bitmap(grabResult.Width, grabResult.Height, PixelFormat.Format24bppRgb);
        //        BitmapData bmpData = _image.LockBits(new Rectangle(0, 0, grabResult.Width, grabResult.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
        //        IntPtr ptrBmp = bmpData.Scan0;
        //        int picSize = bmpData.Stride * grabResult.Height;

        //        PixelDataConverter conv = new PixelDataConverter();
        //        conv.OutputPixelFormat = PixelType.BGR8packed;
        //        conv.Convert(ptrBmp, picSize, grabResult);
        //        _buffer = new byte[picSize];
        //        System.Runtime.InteropServices.Marshal.Copy(ptrBmp, _buffer, 0, picSize);

        //        _format = PixelFormat.Format24bppRgb;
        //        _handle = ptrBmp;
        //        _image.UnlockBits(bmpData);

        //        Continuous_Event?.Invoke();
        //    }
        //    catch (Exception ex)
        //    {
        //        _errInfo = ex.Message;
        //    }
        //    finally
        //    {
        //        e.DisposeGrabResultIfClone();
        //    }
        //}

    }
}