当前位置: 首页 > article >正文

C#用SDK打开海康工业相机,callback取图Bitmap格式,并保存

上次写了python版本的,但是python虽好不方便发布,她带着重重的解释器有时候不方便玩耍.于是C#来了哦.

C#图像一般用Bitmap表示,所以完全C#就够,别的格式可以自行想转换.

命令行哦,没界面.

MVCamera.cs从MVS示例里面添加到项目中,using MvCamCtrl.NET; 就可以,不需要添加mvcameracrtlnet.dll引用;

build BMP的部分程序是自动生成  后面我人工调试出来的. 

using System;

using MvCamCtrl.NET;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using SC = System.Console;

using System.IO;


using System.Threading;
using System.Diagnostics.Eventing.Reader;
using static System.Net.Mime.MediaTypeNames;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Grab_Callback
{

    class Grab_Callback
    {
        public static MyCamera.cbOutputExdelegate ImageCallback;
        public static MyCamera device = new MyCamera();

        public static Bitmap buildBMP(int width, int height, byte[] imgBytes)
        {
            Bitmap bmp;
            bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
            ImageLockMode.WriteOnly, bmp.PixelFormat);
            Marshal.Copy(imgBytes, 0, bmpData.Scan0, imgBytes.Length);
            bmp.UnlockBits(bmpData);
           // EventTask.Run
            return bmp;
        }
        public static byte[] m_BufForDriver1=null;
        public static Bitmap Bbmp = null;
        private static Bitmap bmpNow;

        public static string Getcwd = System.Environment.CurrentDirectory + "\\";
        public static Bitmap buildBMP(int width, int height, byte[] imgBytes, bool isGrayScale)
        {
            Bitmap bmp;

            if (isGrayScale)
            {
                bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
                ColorPalette palette = bmp.Palette;
                for (int i = 0; i < palette.Entries.Length; i++)
                {
                    palette.Entries[i] = Color.FromArgb(i, i, i);
                }
                bmp.Palette = palette;
            }
            else
            {
                bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
            }
            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
                ImageLockMode.WriteOnly, bmp.PixelFormat);
            Marshal.Copy(imgBytes, 0, bmpData.Scan0, imgBytes.Length);
            bmp.UnlockBits(bmpData);
            return bmp;
        }

        static void ImageCallbackFunc(IntPtr pData, ref MyCamera.MV_FRAME_OUT_INFO_EX pFrameInfo, IntPtr pUser)
        {
            string x = $"{pFrameInfo.nWidth}/" + $"{pFrameInfo.nHeight}:" + $"{pFrameInfo.nFrameNum} ";
            m_BufForDriver1 = new byte[pFrameInfo.nFrameLen];

            Marshal.Copy(pData, m_BufForDriver1, 0, ((int)pFrameInfo.nFrameLen));

            // 检查图像是否为灰度图
         //   bool isGrayScale = pFrameInfo.nPixelFormat == MyCamera.MV_PIXEL_FORMAT.MONO8 ||
         //                      pFrameInfo.nPixelFormat == MyCamera.MV_PIXEL_FORMAT.MONO16; // 根据实际像素格式常量进行调整

            Bbmp = buildBMP(pFrameInfo.nWidth, pFrameInfo.nHeight, m_BufForDriver1, false);
            Bbmp.Save(Getcwd + pFrameInfo.nFrameNum.ToString() + ".bmp", ImageFormat.Bmp);
            SC.WriteLine(x);

        }

        static void Main(string[] args)
        {
            int nRet = MyCamera.MV_OK;
            MyCamera.MV_CC_Initialize_NET();// ch: 初始化 SDK | en: Initialize SDK

            do
            {
                // ch:枚举设备 | en:Enum device
                MyCamera.MV_CC_DEVICE_INFO_LIST stDevList = new MyCamera.MV_CC_DEVICE_INFO_LIST();
                nRet = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref stDevList);
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Enum device failed:{0:x8}", nRet);
                    break;
                }
                Console.WriteLine("Enum device count : " + Convert.ToString(stDevList.nDeviceNum));
                if (0 == stDevList.nDeviceNum)
                {
                    break;
                }

                MyCamera.MV_CC_DEVICE_INFO stDevInfo;                            // 通用设备信息

                // ch:打印设备信息 en:Print device info
                for (Int32 i = 0; i < stDevList.nDeviceNum; i++)
                {
                    stDevInfo = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDevList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));

                    if (MyCamera.MV_GIGE_DEVICE == stDevInfo.nTLayerType)
                    {
                        MyCamera.MV_GIGE_DEVICE_INFO_EX stGigEDeviceInfo = (MyCamera.MV_GIGE_DEVICE_INFO_EX)MyCamera.ByteToStruct(stDevInfo.SpecialInfo.stGigEInfo, typeof(MyCamera.MV_GIGE_DEVICE_INFO_EX));
                        uint nIp1 = ((stGigEDeviceInfo.nCurrentIp & 0xff000000) >> 24);
                        uint nIp2 = ((stGigEDeviceInfo.nCurrentIp & 0x00ff0000) >> 16);
                        uint nIp3 = ((stGigEDeviceInfo.nCurrentIp & 0x0000ff00) >> 8);
                        uint nIp4 = (stGigEDeviceInfo.nCurrentIp & 0x000000ff);
                        Console.WriteLine("[device " + i.ToString() + "]:");
                        Console.WriteLine("DevIP:" + nIp1 + "." + nIp2 + "." + nIp3 + "." + nIp4);
                        Console.WriteLine("ModelName:" + stGigEDeviceInfo.chModelName + "\n");
                    }
                    else if (MyCamera.MV_USB_DEVICE == stDevInfo.nTLayerType)
                    {
                        MyCamera.MV_USB3_DEVICE_INFO_EX stUsb3DeviceInfo = (MyCamera.MV_USB3_DEVICE_INFO_EX)MyCamera.ByteToStruct(stDevInfo.SpecialInfo.stUsb3VInfo, typeof(MyCamera.MV_USB3_DEVICE_INFO_EX));
                        Console.WriteLine("[device " + i.ToString() + "]:");
                        Console.WriteLine("SerialNumber:" + stUsb3DeviceInfo.chSerialNumber);
                        Console.WriteLine("ModelName:" + stUsb3DeviceInfo.chModelName + "\n");
                    }
                }

                Int32 nDevIndex = 0;
                Console.Write("Please input index(0-{0:d}):", stDevList.nDeviceNum - 1);
                try
                {
                    nDevIndex = Convert.ToInt32(Console.ReadLine());
                }
                catch
                {
                    Console.Write("Invalid Input!\n");
                    break;
                }

                if (nDevIndex > stDevList.nDeviceNum - 1 || nDevIndex < 0)
                {
                    Console.Write("Input Error!\n");
                    break;
                }
                stDevInfo = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(stDevList.pDeviceInfo[nDevIndex], typeof(MyCamera.MV_CC_DEVICE_INFO));

                // ch:创建设备 | en:Create device
                nRet = device.MV_CC_CreateDevice_NET(ref stDevInfo);
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Create device failed:{0:x8}", nRet);
                    break;
                }

                // ch:打开设备 | en:Open device
                nRet = device.MV_CC_OpenDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Open device failed:{0:x8}", nRet);
                    break;
                }

                // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
                if (stDevInfo.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                {
                    int nPacketSize = device.MV_CC_GetOptimalPacketSize_NET();
                    if (nPacketSize > 0)
                    {
                        nRet = device.MV_CC_SetIntValueEx_NET("GevSCPSPacketSize", nPacketSize);
                        if (nRet != MyCamera.MV_OK)
                        {
                            Console.WriteLine("Warning: Set Packet Size failed {0:x8}", nRet);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Warning: Get Packet Size failed {0:x8}", nPacketSize);
                    }
                }

                // ch:设置触发模式为off || en:set trigger mode as off
                nRet = device.MV_CC_SetEnumValue_NET("TriggerMode", 0);
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Set TriggerMode failed:{0:x8}", nRet);
                    break;
                }

                // ch:注册回调函数 | en:Register image callback
                ImageCallback = new MyCamera.cbOutputExdelegate(ImageCallbackFunc);
                nRet = device.MV_CC_RegisterImageCallBackEx_NET(ImageCallback, IntPtr.Zero);
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Register image callback failed!");
                    break;
                }

                // ch:开启抓图 || en: start grab image
                nRet = device.MV_CC_StartGrabbing_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Start grabbing failed:{0:x8}", nRet);
                    break;
                }

                Console.WriteLine("Press enter to exit");
                Console.ReadLine();

                // ch:停止抓图 | en:Stop grabbing
                nRet = device.MV_CC_StopGrabbing_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Stop grabbing failed:{0:x8}", nRet);
                    break;
                }

                // ch:关闭设备 | en:Close device
                nRet = device.MV_CC_CloseDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Close device failed:{0:x8}", nRet);
                    break;
                }

                // ch:销毁设备 | en:Destroy device
                nRet = device.MV_CC_DestroyDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Destroy device failed:{0:x8}", nRet);
                    break;
                }
            } while (false);

            if (MyCamera.MV_OK != nRet)
            {
                // ch:销毁设备 | en:Destroy device
                nRet = device.MV_CC_DestroyDevice_NET();
                if (MyCamera.MV_OK != nRet)
                {
                    Console.WriteLine("Destroy device failed:{0:x8}", nRet);
                }
            }
            // ch: 反初始化SDK | en: Finalize SDK
            MyCamera.MV_CC_Finalize_NET();
            Console.WriteLine("Press enter to exit");
            Console.ReadKey();
        }
    }
}


http://www.kler.cn/a/314212.html

相关文章:

  • Elasticsearch集群和Kibana部署流程
  • ISUP协议视频平台EasyCVR视频设备轨迹回放平台智慧农业视频远程监控管理方案
  • k8s 1.28.2 集群部署 docker registry 接入 MinIO 存储
  • ssm114基于SSM框架的网上拍卖系统的设计与实现+vue(论文+源码)_kaic
  • 高防服务器的费用受到哪些原因影响?
  • HBase使用create创建表时报错ERROR: KeeperErrorCode = NoNode for /hbase/master
  • 如何使用ssm实现基于Web的数字家庭网站设计与实现+vue
  • Netty+HTML5+Canvas 网络画画板实时在线画画
  • 嵌入式 开发技巧和经验分享
  • 电脑ip地址怎么换地区:操作步骤与利弊分析
  • Elasticsearch如何排序,分页以及高亮查询
  • Rust GUI框架 tauri V2 项目创建
  • 如何安装部署kafka
  • JAVA自助高效安全无人台球茶室棋牌室系统小程序源码
  • 篮球运动场景物体检测系统源码分享
  • 解决在Nignx下Thinkphp路由不生效问题
  • 音视频入门基础:AAC专题(7)——FFmpeg源码中计算AAC裸流每个packet的size值的实现
  • 计算机网络(八) —— Udp协议
  • YMTC Xtacking 4.0(Gen5)技术深度分析
  • MCS-51汇编
  • Linux进程(一)
  • 推动高效能:东芝TB67H301FTG全桥直流电机驱动IC
  • Spring 框架简介 ----- Java 开发利器
  • 【赵渝强老师】K8s中的Deployment控制器
  • 研究生如何利用 ChatGPT 帮助开展日常科研工作?
  • 【Taro】初识 Taro