Image acquisition camera capture program ---

Getting to AI, eye and ear is not it? So you need to get through the critical voice capture, and image capture . In particular program, his importance is self-evident. Although this is a play, in support under Microsoft, simple, over the air, but he was excited to explore and interest (curiosity) never go out of style, it makes you more open professional basler camera, gray dot (grey) the camera image acquisition (for machine vision) of the door, if you are not interested in the colorful world of eye and ear collected, how it would be interested in algorithms and consciousness?

Look finishing c # camera capture program: We gave him a name usbcamscale (usb camera zoom), image acquisition only express the code here:

第一,声明: WebCamera wc = null;
          public ShowVideo.CAPDRIVERCAPS capDriverCaps;
        public ShowVideo.CAPSTATUS capStatus;
        public ShowVideo.CAPTUREPARMS captureparms;

第二,初始化:  capDriverCaps = new ShowVideo.CAPDRIVERCAPS();
            capStatus = new ShowVideo.CAPSTATUS();
            captureparms = new ShowVideo.CAPTUREPARMS();

Third, the image-taking:

  wc = new WebCamera(pictureBox1.Handle, pictureBox1.Width, pictureBox1.Height);//
            wc.StartWebCam();

            if (!wc.capDriverConnect(wc.IwndC, 0))
            {
                return;
            }
            ShowVideo.SendMessage(wc.IwndC, ShowVideo.WM_CAP_DRIVER_GET_CAPS, ShowVideo.SizeOf(capDriverCaps), ref capDriverCaps);

            IF (capDriverCaps.fCaptureInitialized)
            {
                wc.capPreviewRate (wc.IwndC, 25);
                wc.capPreview (wc.IwndC, to true); // not shown, it is provided . To display the settings for the WS_VISIBLE (backward-looking).
            }

ok, imaging success. Well, this is Microsoft's convenient for us, we only look at the eyes wide open, then how to remove one like it? carry on:

            int mod = wc.mWidth% 4; // This is vfw mode (opencv1.0 too ), and by testing on win8.1, win10 you can find a way to clearance
            glob_buffer32 = new byte [640 * 480 * 4] ; // vfw mode, only remove the pixels 640 * 480, win8.1 can run the camera 800 * 600
            glob_buffer8 = new byte [640 * 480 ]; // but take out is still 640 * 480, so you and need brains clearance
            glob_buffer8G = new new byte [640 * 480];
            glob_buffer8B = new new byte [640 * 480];
            timer1.Start ();

Fourth, remove an image:

 Bitmap  glob_curBitmap=null;
      Bitmap transBmp = null;
        private void timer1_Tick(object sender, EventArgs e)
        {
                      
            if (ShowVideo.SendMessage(wc.IwndC, ShowVideo.WM_CAP_SINGLE_FRAME_OPEN, 0, 0))
            {
                if (ShowVideo.SendMessage(wc.IwndC, ShowVideo.WM_CAP_SINGLE_FRAME, 0, 0))
                {
                    if (ShowVideo.SendMessage(wc.IwndC, ShowVideo.WM_CAP_SINGLE_FRAME_CLOSE, 0, 0))
                    {
                     

                        ShowVideo.SendMessage(wc.IwndC, ShowVideo.WM_CAP_EDIT_COPY, 0, 0);
                        IDataObject iData = Clipboard.GetDataObject();
                        iData.GetDataPresent(DataFormats.Bitmap);
                     
                        transBmp = (Bitmap)iData.GetData(DataFormats.Bitmap);
                       this.pictureBox1.Image = (Bitmap)iData.GetData(DataFormats.Bitmap);//这里显示彩色图像
                        Clipboard.Clear();
                
                        glob_curBitmap = (Bitmap)transBmp.Clone();
                   

                    }
                }
            }
            int ww=640;
            int hh=480;
            BitmapData _cutPic = glob_curBitmap.LockBits(new Rectangle(0, 0, ww, hh),//PixelFormat.Format32bppArgb
                  ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);//glob_curBitmap.
            IntPtr ptr = _cutPic.Scan0;//得到首地址
            //把cutvalues数组给ptr
      
            Marshal.Copy(ptr, glob_buffer32, 0, 640*480* 4);
            glob_curBitmap.UnlockBits(_cutPic);
        
            for (int j = 0; j < 640; j++)
            {
                for (int i = 0; i < 480; i++)
                {
                    * 480 NN J = int + I;
                    glob_buffer8 [NN] = glob_buffer32 [NN *. 4 + 0]; // here, RGB image has been removed on the r, g, b array (byte []) in
                    glob_buffer8G [nn] = glob_buffer32 [nn * 4 + 1] ; // you need to think of ways to write bitmap, and display
                    glob_buffer8B [nn] = glob_buffer32 [nn * 4 + 2]; // buffer8B here is stored inside the red component, found no?
                }
            }
            Drawload2scale (640, 480, glob_buffer8, pictureBox2); // Shown here is a grayscale image, the image processing can be used to

} // we have an array of blue color components b as a grayscale image is wrong, it should be 0.3 red, green, 0.59, 0.11 blue

The rest is to explain in front of key classes : first

  class WebCamera
    {
       
            public delegate void RecievedFrameEventHandler(byte[] data);
            public event RecievedFrameEventHandler RecievedFrame;
            public IntPtr IwndC;
            public IntPtr mControlPtr;
            public int mWidth;
            public int mHeight;
            public ShowVideo.FrameEventHandler mFrameEventHandler;
            public void FrameCallBack(IntPtr Iwnd, IntPtr lpVHdr)
            {
                ShowVideo.VIDEOHDR videoHeader = new ShowVideo.VIDEOHDR();
                byte[] VideoData;
                videoHeader = (ShowVideo.VIDEOHDR)ShowVideo.GetStructure(lpVHdr, videoHeader);
                VideoData=new byte[videoHeader.dwBytesUsed];
                ShowVideo.Copy(videoHeader.lpData, VideoData);
                if (this.RecievedFrame != null)
                {
                    this.RecievedFrame(VideoData);
                }
            }
            public WebCamera(IntPtr handle, int width, int height)
            {
                mControlPtr = handle;
                mWidth = width;
                mHeight = height;
            }
            public void StartWebCam()        
            {
                byte[] abc = new byte[32];
                abc[0] = (byte)'u';
                abc[1] = (byte)'s';
                abc[2] = (byte)'b';
                abc[3] = (byte)'C';
                abc[4] = (byte)'a';
                abc[5] = (byte)'m';

                for (int i = 6; i < 32; i++)
                {
                    abc[i] = (byte)'0';
                }


               // IwndC = ShowVideo.capCreateCaptureWindowA (abc, ShowVideo.WS_CHILD | ShowVideo.WS_VISIBLE, 0, 0, mWidth, mHeight, mControlPtr, 0); // To display an image, use this line of code
                // WS_DISABLED
                IwndC ShowVideo.capCreateCaptureWindowA = ( abc, ShowVideo.WS_CHILD | ShowVideo.WS_DISABLED, 0, 0, mWidth, mHeight, mControlPtr, 0); // Note that this is set to not display .
            }
            Public void CloseCamera ()
            {
                this.capDriverDisconnect (this.IwndC);
            }
            public BOOL capDriverConnect (IntPtr Iwnd, Short I)
            {
                return ShowVideo.SendMessage (Iwnd, ShowVideo.WM_CAP_DRIVER_CONNECT, I, 0);
            }
            public bool capDriverDisconnect(IntPtr Iwnd)
            {
                return ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_DRIVER_DISCONNECT, 0, 0);
            }
            public bool capPreview(IntPtr Iwnd, bool f)
            {
                return ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_SET_PREVIEW, f, 0);
            }
            public bool capPreviewRate(IntPtr Iwnd, short wMS)
            {
                return ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_SET_PREVIEWRATE, wMS, 0);
            }
            public bool capSetVideoFormat(IntPtr hWnd, ref ShowVideo.BITMAPINFO bitmapinfo, int size)
            {
                //return ShowVideo.capGetVideoFormat(hWnd, bitmapinfo, size);
                return ShowVideo.SendMessage(hWnd, ShowVideo.WM_CAP_SET_VIDEOFORMAT, size, ref bitmapinfo);
            }
            public bool capSetCallbackOnFrame(IntPtr IWnd, ShowVideo.FrameEventHandler lpProc)
            {
                return ShowVideo.SendMessage(IWnd, ShowVideo.WM_CAP_SET_CALLBACK_FRAME, 0, lpProc);
            }
            public void StartCamera()
            {
                byte[] lpszName = new byte[100];
                byte[] lpszVer = new byte[100];

                this.IwndC = ShowVideo.capCreateCaptureWindowA(lpszName, ShowVideo.WS_VISIBLE + ShowVideo.WS_CHILD,
                    0, 0, mWidth, mHeight, mControlPtr, 0);
            }
            public void caprecord(IntPtr Iwnd, string path)
            {
                IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
                ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_FILE_SET_CAPTURE_FILEA, 0, hBmp.ToInt32());
                ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_SEQUENCE, 0, 0);
            }
            public void caprecordstop(IntPtr Iwnd)
            {
                ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_STOP, 0, 0);
            }
            public void capsnapimage(IntPtr Iwnd, string path)
            {
                ShowVideo.BITMAPINFO bmpinfo = new ShowVideo.BITMAPINFO();
                IntPtr hBmp = Marshal.StringToHGlobalAnsi(path);
                ShowVideo.SendMessage(Iwnd, ShowVideo.WM_CAP_SAVEDIB, 0, hBmp.ToInt32());
            }
        
    }///////////////////////////////////////////////////////////////////

Second: that this is a form class, you need to create a form window

 public partial class ShowVideo : Form
    {
        public const int WS_CHILD = 0x40000000;
        public const int WS_VISIBLE = 0x10000000;
        public const int WS_DISABLED=0x08000000;
        public const int WM_USER = 1024;
        public const int WM_CAP_START = WM_USER;
        public const int WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10;
        public const int WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11;
        public const int WM_CAP_SET_PREVIEW = WM_CAP_START + 50;
        public const int WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52;
        public const int WM_CAP_SET_VIDEOFORMAT = WM_USER + 45;
        public const int WM_CAP_SET_CALLBACK_FRAME = WM_USER + 5;
        public const int WM_CAP_FILE_SET_CAPTURE_FILEA = WM_USER + 20;
        public const int WM_CAP_SEQUENCE=WM_USER +62;
        public const int WM_CAP_SAVEDIB = WM_USER + 25;
        public const int WM_CAP_STOP = WM_USER + 68;
        public const int WM_CAP_GET_SEQUENCE_SETUP=WM_USER+65;
        public const int WM_CAP_DRIVER_GET_CAPS=WM_USER+14;
        public const int WM_CAP_DRIVER_GET_STATUS = WM_USER + 54;

        public delegate void FrameEventHandler(IntPtr Iwnd, IntPtr lpVHdr);
        public static object GetStructure(IntPtr ptr, ValueType structure)
        {
            return Marshal.PtrToStructure(ptr, structure.GetType());
        }
        public static object GetStructure(int ptr, ValueType structure)
        {
            return GetStructure(new IntPtr(ptr), structure);
        }
        public static void Copy(IntPtr ptr, byte[] data)
        {
            Marshal.Copy(ptr, data, 0, data.Length);
        }
        public static void Copy(int ptr, byte[] data)
        {
            Copy(new IntPtr(ptr), data);
        }

        public static int SizeOf(object structer)
        {
            unsafe
            {
                return Marshal.SizeOf(structer);
            }
        }

        [DllImport("avicap32.dll")]
        public static extern IntPtr capCreateCaptureWindowA(byte[] lpszWindowName, int dwStyle, int x, int y,
            int nwidth, int nheight, IntPtr hWndParent, int nID);

        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, short WParam, int LParam);
        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, bool WParam, int LParam);
        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd,int wMsg,short WParam,FrameEventHandler LParam);
        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, int WParam, ref BITMAPINFO LParam);
        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, int WParam, ref CAPDRIVERCAPS LParam);
        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, int WParam, ref CAPTUREPARMS LParam);
        [DllImport("User32.dll")]
        public static extern bool SendMessage(IntPtr hWnd, int wMsg, int WParam, ref CAPSTATUS LParam);

        [DllImport("User32.dll")]
        public static extern int SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags);
        [DllImport("User32.dll")]
        public static extern int capGetVideoFormat(IntPtr hWnd, IntPtr psVideoFormat, int wSize);

        public const int WM_CAP_SINGLE_FRAME_OPEN = WM_USER + 70;
        public const int WM_CAP_SINGLE_FRAME_CLOSE = WM_USER + 71;
        public const int WM_CAP_SINGLE_FRAME=WM_USER+72;
        public const int WM_CAP_EDIT_COPY = (WM_USER + 30);

        //[DllImport("User32.dll")]
        //public static extern bool EmptyClipboard();
        //[DllImport("User32.dll")]
        //public static extern bool CloseClipboard();
        //[DllImport("User32.dll")]
        //public static extern bool OpenClipboard(IntPtr hWnd);
        //[DllImport("User32.dll")]
        //public static extern bool IsClipboardFormatAvailable(uint format);
        //[DllImport("User32.dll")]
        //public static extern IntPtr GetClipboardData(uint uFormat);
        //[DllImport("User32.dll")]
        //public static extern IntPtr GlobalLock(IntPtr handle);
        //[DllImport("User32.dll")]
        //public static extern bool GlobalUnlock(IntPtr handle);
        //[DllImport("User32.dll")]
        //public static extern bool CloseClipboard();

        [StructLayout(LayoutKind.Sequential)]
        public struct VIDEOHDR
        {
            [MarshalAs(UnmanagedType.I4)]
            public int lpData;
            [MarshalAs(UnmanagedType.I4)]
            public int dwBufferLength;
            [MarshalAs(UnmanagedType.I4)]
            public int dwBytesUsed;
            [MarshalAs(UnmanagedType.I4)]
            public int dwTimeCaptured;
            [MarshalAs(UnmanagedType.I4)]
            public int dwUser;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
            public int[] dwReserved;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct BITMAPINFOHEADER
        {
            [MarshalAs(UnmanagedType.I4)]
            public Int32 biSize;
            [MarshalAs(UnmanagedType.I4)]
            public Int32 biWidth;
            [MarshalAs(UnmanagedType.I4)]
            public Int32 biHeight;
            [MarshalAs(UnmanagedType.I2)]
            public short biPlanes;
            [MarshalAs(UnmanagedType.I2)]
            public short biBitCount;
            [MarshalAs(UnmanagedType.I4)]
            public int biCompression;
            [MarshalAs(UnmanagedType.I4)]
            public int biSizeImage;
            [MarshalAs(UnmanagedType.I4)]
            public int biXpelsPerMeter;
            [MarshalAs(UnmanagedType.I4)]
            public int biYPelsPerMeter;
            [MarshalAs(UnmanagedType.I4)]
            public int biClrUsed;
            [MarshalAs(UnmanagedType.I4)]
            public int biClrImportant;

        }
        [StructLayout(LayoutKind.Sequential)]
        public struct BITMAPINFO
        {
            [MarshalAs(UnmanagedType.Struct, SizeConst = 100)]
            public BITMAPINFOHEADER bmiHeader;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
            public int[] bmiColors;

        }
        [StructLayout(LayoutKind.Sequential)]
        public struct CAPDRIVERCAPS
        {
            [MarshalAs(UnmanagedType.U2)]
            public UInt16 wDeviceIndex;
            [MarshalAs(UnmanagedType.Bool)]
            public bool fHasOverlay;
            [MarshalAs(UnmanagedType.Bool)]
            public bool fHasDlgVideoSource;
            [MarshalAs(UnmanagedType.Bool)]
            public bool fHasVideoFormat;
            [MarshalAs(UnmanagedType.Bool)]
            public bool fHasDlgVideoDisplay;
            [MarshalAs(UnmanagedType.Bool)]
            public bool fCaptureInitialized;
            [MarshalAs(UnmanagedType.Bool)]
            public bool fDriverSuppliesPalettes;
            [MarshalAs(UnmanagedType.I4)]
            public int hVideoIn;
            [MarshalAs(UnmanagedType.I4)]
            public int hVideoOut;
            [MarshalAs(UnmanagedType.I4)]
            public int hVideoExtIn;
            [MarshalAs(UnmanagedType.I4)]
            public int hVideoExtOut;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct CAPTUREPARMS
        {
            public int dwRequestMicroSecPerFrame;//默认15秒每帧
            public bool fMakeUserHitOkToCapture;//开始捕获标志
            public uint wPercentDropForError; // default frame dropping 10
            public BOOL fYield; // start a new thread logo
            public int dwIndexSize;
            public uint wChunkGranularity;
            public BOOL fUsingDOSMemory;
            public uint wNumVideoRequested; // allocate the largest cache video
            public BOOL fCaptureAudio;
            public uint wNumAudioRequested; // maximum number of audio buffers
            public uint vKeyAbort; // terminate stream capture virtual keyboard it
            [the MarshalAs (UnmanagedType.Bool)]
            public BOOL fAbortLeftMouse;
            public BOOL fAbortRightMouse;
            public BOOL fLimitEnabled; // capture operation time limit
            public uint wTimeLimit; / / specific end time
            public bool fMCIControl;
            public bool fStepMCIDevicd;
            public int dwMCIStartTime;
            public int dwMCIStopTime;
            public bool fStepCaptureAt2x;
            public int wStepCaptureAverageFrames;
            public int dwAudioBufferSize;//0.5s或10k字节
            public int fDisableWriteCache;
            public int AVStreamMaster;//音频同步标志
            
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct CAPSTATUS
        {
            public int uiImageWidth;
            public int uiImageHeight;
            public bool fOverlayWindow;
            public bool fLiveWindow;
            public bool fScale;
            public Point ptScroll;
            public bool fUsingDefaultPalette;
            public bool fAudioHardware;
            public bool fCapFileExists;
            public int dwCurrentVideoFrame;
            public int dwCurrentVideoFramesDropped;
            public int dwCurrentWaveSamples;
            public int dwCurrentTimeElapsedMS;
            public IntPtr hPalCurrent;
            public int  dwReturn;
            public bool fCapturingNow;
            public int wNumVideoAllocated;
            public int wNumAudioAllocated;
        }
        public ShowVideo()
        {
            InitializeComponent();
        }
    }

What a great place to network learning, there are a lot of great coffee needs Thank you, but more should be grateful to Microsoft! If you want to see there vc ++ version of the camera image acquisition program, please leave a message, perhaps, there is contrast in order to better learning progress, I do not think I gave vc ++, and that's the beginning of my heart! (Vc ++ can get everything right, C # is not a thing, although nobody taught)

Continued (slowly! ...........) a little small change every day ☺

My mailbox [email protected]; [email protected]

Published 66 original articles · won praise 12 · views 10000 +

Guess you like

Origin blog.csdn.net/ganggangwawa/article/details/102540998
Recommended