c# 无法打开摄像头_c#打开摄像头 - CSDN
精华内容
参与话题
  • C#打开摄像头(Halcon)

    万次阅读 多人点赞 2017-03-23 19:42:01
    C#打开摄像头(Halcon) 1、halcon中打开摄像头 通过“助手”菜单打开“Image Acquisition”,如图所示,选择“DirectShow”表示普通USB摄像头。 通过“连接、拍照、视频”可以检测是否已经打开。 ...

    C#中打开摄像头(Halcon)

    1、halcon中打开摄像头

    通过“助手”菜单打开“Image Acquisition”,如图所示,选择“DirectShow”表示普通USB摄像头。


    通过“连接、拍照、视频”可以检测是否已经打开。

    可以看到图像窗口中已经有视频可以显示,如图


    可以选择代码生成,选择插入代码,可以看到在程序编辑区,代码已经插入。


    这里是为了在C#中打开摄像头,下面选择代码导出:“文件---->导出”。


    打开image_acp.cs代码如下:

    //
    //  File generated by HDevelop for HALCON/DOTNET (C#) Version 12.0
    //
    
    using HalconDotNet;
    
    public partial class HDevelopExport
    {
    #if !(NO_EXPORT_MAIN || NO_EXPORT_APP_MAIN)
      public HDevelopExport()
      {
        // Default settings used in HDevelop 
        HOperatorSet.SetSystem("width", 512);
        HOperatorSet.SetSystem("height", 512);
        if (HalconAPI.isWindows)
          HOperatorSet.SetSystem("use_window_thread","true");
        action();
      }
    #endif
    
    #if !NO_EXPORT_MAIN
      // Main procedure 
      private void action()
      {
    
    
    
        // Local iconic variables 
    
        HObject ho_Image=null;
    
        // Local control variables 
    
        HTuple hv_AcqHandle = null;
        // Initialize local and output iconic variables 
        HOperatorSet.GenEmptyObj(out ho_Image);
        //Image Acquisition 01: Code generated by Image Acquisition 01
        HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb", 
            -1, "false", "default", "[0] USB2.0 PC CAMERA", 0, -1, out hv_AcqHandle);
        HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
        while ((int)(1) != 0)
        {
          ho_Image.Dispose();
          HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
          //Image Acquisition 01: Do something
        }
        HOperatorSet.CloseFramegrabber(hv_AcqHandle);
        ho_Image.Dispose();
    
      }
    
    #endif
    
    
    
    }
    #if !(NO_EXPORT_MAIN || NO_EXPORT_APP_MAIN)
    public class HDevelopExportApp
    {
      static void Main(string[] args)
      {
        new HDevelopExport();
      }
    }
    #endif

    2、C#中打开摄像头

    (1)新建一个C#---WINFORM程序,在窗体上添加Halcon的HWindowControl控件(参照博客:C#(VS2010)调用HALCON12),两个按钮


    (2)Form1.cs代码如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using HalconDotNet;//添加Halcon空间
    
    using System.Threading;
    
    namespace 打开摄像头
    {
        public partial class Form1 : Form
        {
            //halcon导出的变量
            HObject ho_Image = null;
            HTuple hv_AcqHandle = null;
    
            public Form1()
            {
                InitializeComponent();
            }
            //定义一个线程
            Thread dispig;
            private void button1_Click(object sender, EventArgs e)
            {//图像采集
                dispig = new Thread(getin);
                dispig.Start();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {//停止
                dispig.Abort();
                HOperatorSet.CloseFramegrabber(hv_AcqHandle);
            }
            void getin()
            {
                HOperatorSet.GenEmptyObj(out ho_Image);
                HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb",
                                -1, "false", "default", "[0] USB2.0 PC CAMERA", 0, -1, out hv_AcqHandle);
                HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                while(true)
                {
                    HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
    
                    HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
                    ho_Image.Dispose();
                }
                
            }
        }
    
    }

    (3)效果如下:


    如果视频正在采集中,直接关闭窗体,程序会报错,其实是由于线程正在运行的问题(参照之前的博客:C#----多线程)。为窗体添加一个“FromClosing”事件即可,代码如下:

      private void Form1_FormClosing(object sender, FormClosingEventArgs e)
      {
          if (dispig != null)
          {
               dispig.Abort(); //结束这个线程
          }
      }

    到此,程序完全可以正常运行。

    其全部代码如下:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using HalconDotNet;//添加Halcon空间
    
    using System.Threading;
    
    namespace 打开摄像头
    {
        public partial class Form1 : Form
        {
            //halcon导出的变量
            HObject ho_Image = null;
            HTuple hv_AcqHandle = null;
    
            public Form1()
            {
                InitializeComponent();
            }
            //定义一个线程
            Thread dispig;
            private void button1_Click(object sender, EventArgs e)
            {//图像采集
                dispig = new Thread(getin);
                dispig.Start();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {//停止
                dispig.Abort();
                HOperatorSet.CloseFramegrabber(hv_AcqHandle);
            }
            void getin()
            {
                HOperatorSet.GenEmptyObj(out ho_Image);
                HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb",
                                -1, "false", "default", "[0] USB2.0 PC CAMERA", 0, -1, out hv_AcqHandle);
                HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
                while(true)
                {
                    HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
    
                    HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
                    ho_Image.Dispose();
                }
                
            }
    
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                if (dispig != null)
                {
                    dispig.Abort(); //结束这个线程
                }
            }
        }
    
    
    
    }
    展开全文
  • C#打开笔记本摄像头

    2020-07-15 23:30:42
    C#打开笔记本摄像头
  • 与FX PLC链接,打开笔记本摄像头 与FX PLC链接,打开笔记本摄像头 与FX PLC链接,打开笔记本摄像头
  • C# DirectShow方式打开摄像头

    热门讨论 2020-07-31 01:37:50
    win8 64位系统测试可用 需要用vs2013打开,也可以去找vs工程在线降级的,转换成低版本打开
  • C#打开电脑摄像头及拍照

    千次阅读 2015-05-21 19:49:05
    首先需要引用一个开源的程序集,叫做WPFMediaKit.dll xmal文件也需要添加引用,代码如下 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.mic

    首先需要引用一个开源的程序集,叫做WPFMediaKit.dll


    xmal文件也需要添加引用,代码如下

    <Window x:Class="HRMsys.UI.test"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            
             xmlns:wpfmedia="clr-namespace:WPFMediaKit.DirectShow.Controls;assembly=WPFMediaKit"
            
            Title="test" Height="300" Width="300" Loaded="Window_Loaded_1">
        <Grid>
            <StackPanel>
                <ComboBox Name="cb" SelectionChanged="cb_SelectionChanged"></ComboBox>
                <wpfmedia:VideoCaptureElement Height="200" Name="vce">
    
                </wpfmedia:VideoCaptureElement>
                <Button Height="30" Content="拍" Name="btnCapture" Click="btnCapture_Click"></Button>
            </StackPanel>
        </Grid>
    </Window>
    


    源代码

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    using WPFMediaKit.DirectShow.Controls;
    
    namespace HRMsys.UI
    {
        /// <summary>
        /// test.xaml 的交互逻辑
        /// </summary>
        public partial class test : Window
        {
            public test()
            {
                InitializeComponent();
            }
    
            private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                vce.VideoCaptureSource = (string)cb.SelectedItem;
            }
    
            private void btnCapture_Click(object sender, RoutedEventArgs e)
            {
                //拍照
                RenderTargetBitmap bmp = new RenderTargetBitmap(
                (int)vce.ActualWidth, (int)vce.ActualHeight,
                96, 96, PixelFormats.Default);
                bmp.Render(vce);
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                using (MemoryStream ms = new MemoryStream())
                {
                    encoder.Save(ms);
                    byte[] captureData = ms.ToArray();
                    File.WriteAllBytes("d:/1.jpg", captureData);//导出路径
                }
                vce.Pause();//画面暂停
    
            }
    
            private void Window_Loaded_1(object sender, RoutedEventArgs e)
            {
                cb.ItemsSource = MultimediaUtil.VideoInputNames;
            }
        }
    }
    




    展开全文
  • C#调用摄像头的几种方式

    万次阅读 热门讨论 2019-12-25 21:28:41
    C#调用摄像头的方式本文将讲诉在C#的winform程序中如何调用摄像头: 1.调用USB摄像头 2.调用普通IP摄像头 3.通过摄像头SDK进行调用使用的DLL首先给上我所使用的DLL 调用USB摄像头调用USB摄像头其实比较简单,就是...

    #C#调用摄像头的方式
    本文将讲诉在C#的winform程序中如何调用摄像头:
    1.调用USB摄像头
    2.调用普通IP摄像头
    3.通过摄像头SDK进行调用

    ##使用的DLL
    首先给上我所使用的DLL
    dll

    ##调用USB摄像头
    调用USB摄像头其实比较简单,就是通过读取电脑自身所拥有的设备数,再执行预览。
    videoSourcePlayer是AForge中的控件。

    private FilterInfoCollection videoDevices;
    this.videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
    if (this.videoDevices.Count > 0)
       {
           VideoCaptureDevice source = new VideoCaptureDevice(this.videoDevices[0].MonikerString);
           this.videoSourcePlayer.SignalToStop();
           this.videoSourcePlayer.WaitForStop();
           this.videoSourcePlayer.VideoSource = source;
           this.videoSourcePlayer.Start();
       }
    

    ##调用普通IP摄像头
    首先要确认HTTP方式传送的图片的地址,我用的SAMSUN地址是http://{0}/cgi-bin/video.cgi?msubmenu=jpg,还有其他的http://{0}/axis-cgi/jpg/image.cgi?camera=1
    使用JPEGStream或者MJPEGStream,有用户名和密码的就加上。有了source其他的和上面USB一样。

    JPEGStream source = new JPEGStream(URL);
    //MJPEGStream source = new MJPEGStream(URL);
    source.Login = username;
    source.Password = password;
    this.OpenVideoSource(source);
    

    ##通过摄像头SDK进行调用
    这个调用还是很简单的,一般都是使用控件的Handle来进行预览的,我们可能会想取每一帧的图片,那么如何取得每一帧呢?因为是通过Handle来预览的所以控件中无法取得,我们需要调用摄像头SDK的获取每一帧的接口,但是这个接口是直接将图片保存到本地的,感觉巨坑有木有。不过我们还是有方法处理的。下面是我对三星摄像头的处理:

    public override Bitmap CapturePicture()
    {
        Bitmap bitmap = null;
        string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Templates) + @"\SAMSUNG_CapturePicture.bmp";
        if (File.Exists(path))
        {
            File.Delete(path);
        }
        if (SSNetSDK.XNS_DEV_SaveSnapshot(playHandle, path,0))
        {
            using (MemoryStream stream = new MemoryStream(File.ReadAllBytes(path)))
            {
                bitmap = (Bitmap)Image.FromStream(stream);
            }
            File.Delete(path);
        }
        return bitmap;
    }
    

    DEMO http://download.csdn.net/detail/xujie1991618/8830347

    我看到很多人问我AForge库,其实网上找一找很多的,为了方便大家我特地找了一份放云盘了
    链接: https://pan.baidu.com/s/1Wkmykt00hdP1Jum2m_7k6Q 提取码: pr7m

    展开全文
  • OpenCvSharp打开摄像头,VideoCapture,OpenCv,Mat,相机,Camera。内有编译好的程序,可以直接运行
  • C#读取USB摄像头

    2020-07-30 23:31:49
    该程序使用C#语言编写,主要功能为调取笔记本自带摄像头以及USB摄像头,并显示在窗体中,包含有截图录像功能。
  • C# DirectShow预览摄像头并截图 本事例通过Windows DirectX Filtergraph 一些列管道将电脑所接入视频采集设备的视频流播放到制定区域,通过ISampleGrabberCB接口的BufferCB回调函数截取图片。 ui布局: 代码如下: ...

    C# DirectShow预览摄像头并截图

    本事例通过Windows DirectX Filtergraph 一些列管道将电脑所接入视频采集设备的视频流播放到制定区域,通过ISampleGrabberCB接口的BufferCB回调函数截取图片。
    用此方法预览图像cpu占用率极低,比其其他事件绑定并逐帧显示图像性能更佳。

    ui布局:
    在这里插入图片描述
    代码如下:

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    using DirectShowLib;
    using System.Runtime.InteropServices;
    using System.Runtime.InteropServices.ComTypes;
    using System.Drawing.Imaging;
    
    namespace Test
    {
        public partial class FormDirect : Form, ISampleGrabberCB
        {
            
            private int _previewWidth = 640;
            private int _previewHeight = 480;
            private int _previewStride = 0;
            private int _previewFPS = 30;
            private volatile bool isGrab = false;
    
            IVideoWindow videoWindow = null;
            IMediaControl mediaControl = null;
            IFilterGraph2 graphBuilder = null;
            ICaptureGraphBuilder2 captureGraphBuilder = null;
            
    
            DsROTEntry rot = null;
    
            public FormDirect()
            {
                InitializeComponent();
            }
    
         
    
            private void button2_Click(object sender, EventArgs e)
            {
                //截图
                isGrab = true;
                
            }
    
            private void button3_Click(object sender, EventArgs e)
            {
                string button_text = button3.Text;
                if (button_text.Equals("Start Webcam"))
                {
                    button3.Text = "Stop Webcam";
                    StartCamera();
                }
                else
                {
                    button3.Text = "Start Webcam";
                    StopCamera();
                }
            }
    
            private void StartCamera()
            {
                
                DsDevice[] devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
                if (devices.Length == 0)
                {
                    MessageBox.Show("No USB webcam connected");
                    button3.Text = "Start Webcam";
                    return;
                }
                else
                {
                    
                    CaptureVideo(devices[0]);
                }
            }
    
            private void StopCamera()
            {
                button3.Text = "Start Webcam";
                CloseInterfaces();
            }
    
           
    
            public void CaptureVideo(DsDevice device)
            {
                pictureBox1.Image = null;
                int hr = 0;
                IBaseFilter sourceFilter = null;
                ISampleGrabber sampleGrabber = null;
    
                try
                {
                    // Get DirectShow interfaces
                    GetInterfaces();
    
                    // Attach the filter graph to the capture graph
                    hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
                    DsError.ThrowExceptionForHR(hr);
    
                    // Use the system device enumerator and class enumerator to find
                    // a video capture/preview device, such as a desktop USB video camera.
                    sourceFilter = SelectCaptureDevice(device);
                    // Add Capture filter to graph.
                    hr = this.graphBuilder.AddFilter(sourceFilter, "Video Capture");
                    DsError.ThrowExceptionForHR(hr);
    
                    // Initialize SampleGrabber.
                    sampleGrabber = new SampleGrabber() as ISampleGrabber;
                    // Configure SampleGrabber. Add preview callback.
                    ConfigureSampleGrabber(sampleGrabber);
                    // Add SampleGrabber to graph.
                    hr = this.graphBuilder.AddFilter(sampleGrabber as IBaseFilter, "Frame Callback");
                    DsError.ThrowExceptionForHR(hr);
    
                    // Configure preview settings.
                    SetConfigParams(this.captureGraphBuilder, sourceFilter, _previewFPS, _previewWidth, _previewHeight);
    
                    // Render the preview
                    hr = this.captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, sourceFilter, (sampleGrabber as IBaseFilter),null);
                   
    
    
                    DsError.ThrowExceptionForHR(hr);
    
                    SaveSizeInfo(sampleGrabber);
    
                    // Set video window style and position
                    SetupVideoWindow();
    
                    // Add our graph to the running object table, which will allow
                    // the GraphEdit application to "spy" on our graph
                    rot = new DsROTEntry(this.graphBuilder);
    
                    // Start previewing video data
                    hr = this.mediaControl.Run();
                    DsError.ThrowExceptionForHR(hr);
                }
                catch
                {
                    MessageBox.Show("An unrecoverable error has occurred.");
                }
                finally
                {
                    if (sourceFilter != null)
                    {
                        Marshal.ReleaseComObject(sourceFilter);
                        sourceFilter = null;
                    }
    
                    if (sampleGrabber != null)
                    {
                        Marshal.ReleaseComObject(sampleGrabber);
                        sampleGrabber = null;
                    }
                }
            }
    
            public void CaptureVideo()
            {
                pictureBox1.Image = null;
                int hr = 0;
                IBaseFilter sourceFilter = null;
                ISampleGrabber sampleGrabber = null;
    
                try
                {
                    // Get DirectShow interfaces
                    GetInterfaces();
    
                    // Attach the filter graph to the capture graph
                    hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
                    DsError.ThrowExceptionForHR(hr);
    
                    // Use the system device enumerator and class enumerator to find
                    // a video capture/preview device, such as a desktop USB video camera.
                    sourceFilter = FindCaptureDevice();
                    // Add Capture filter to graph.
                    hr = this.graphBuilder.AddFilter(sourceFilter, "Video Capture");
                    DsError.ThrowExceptionForHR(hr);
    
                    // Initialize SampleGrabber.
                    sampleGrabber = new SampleGrabber() as ISampleGrabber;
                    // Configure SampleGrabber. Add preview callback.
                    ConfigureSampleGrabber(sampleGrabber);
    
                    // Add SampleGrabber to graph.
                    hr = this.graphBuilder.AddFilter(sampleGrabber as IBaseFilter, "Frame Callback");
                    DsError.ThrowExceptionForHR(hr);
    
                    // Configure preview settings.
                    SetConfigParams(this.captureGraphBuilder, sourceFilter, _previewFPS, _previewWidth, _previewHeight);
    
                    // Render the preview
                    hr = this.captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, sourceFilter, (sampleGrabber as IBaseFilter),null);
                    DsError.ThrowExceptionForHR(hr);
    
                    SaveSizeInfo(sampleGrabber);
    
                    // Set video window style and position
                    SetupVideoWindow();
    
                    // Add our graph to the running object table, which will allow
                    // the GraphEdit application to "spy" on our graph
                    rot = new DsROTEntry(this.graphBuilder);
    
                    // Start previewing video data
                    hr = this.mediaControl.Run();
                    DsError.ThrowExceptionForHR(hr);
                }
                catch
                {
                    MessageBox.Show("An unrecoverable error has occurred.");
                }
                finally
                {
                    if (sourceFilter != null)
                    {
                        Marshal.ReleaseComObject(sourceFilter);
                        sourceFilter = null;
                    }
    
                    if (sampleGrabber != null)
                    {
                        Marshal.ReleaseComObject(sampleGrabber);
                        sampleGrabber = null;
                    }
                }
            }
    
            public IBaseFilter SelectCaptureDevice(DsDevice device)
            {
                object source = null;
                Guid iid = typeof(IBaseFilter).GUID;
                device.Mon.BindToObject(null, null, ref iid, out source);
                return (IBaseFilter)source;
            }
    
            public IBaseFilter FindCaptureDevice()
            {
                int hr = 0;
    #if USING_NET11
          UCOMIEnumMoniker classEnum = null;
          UCOMIMoniker[] moniker = new UCOMIMoniker[1];
    #else
                IEnumMoniker classEnum = null;
                IMoniker[] moniker = new IMoniker[1];
    #endif
                object source = null;
    
                // Create the system device enumerator
                ICreateDevEnum devEnum = (ICreateDevEnum)new CreateDevEnum();
    
                // Create an enumerator for the video capture devices
                hr = devEnum.CreateClassEnumerator(FilterCategory.VideoInputDevice, out classEnum, 0);
                DsError.ThrowExceptionForHR(hr);
    
                // The device enumerator is no more needed
                Marshal.ReleaseComObject(devEnum);
    
                // If there are no enumerators for the requested type, then 
                // CreateClassEnumerator will succeed, but classEnum will be NULL.
                if (classEnum == null)
                {
                    throw new ApplicationException("No video capture device was detected.\r\n\r\n" +
                                                   "This sample requires a video capture device, such as a USB WebCam,\r\n" +
                                                   "to be installed and working properly.  The sample will now close.");
                }
    
                // Use the first video capture device on the device list.
                // Note that if the Next() call succeeds but there are no monikers,
                // it will return 1 (S_FALSE) (which is not a failure).  Therefore, we
                // check that the return code is 0 (S_OK).
    #if USING_NET11
          int i;
          if (classEnum.Next (moniker.Length, moniker, IntPtr.Zero) == 0)
    #else
                if (classEnum.Next(moniker.Length, moniker, IntPtr.Zero) == 0)
    #endif
                {
                    // Bind Moniker to a filter object
                    Guid iid = typeof(IBaseFilter).GUID;
                    moniker[0].BindToObject(null, null, ref iid, out source);
                }
                else
                {
                    throw new ApplicationException("Unable to access video capture device!");
                }
    
                // Release COM objects
                Marshal.ReleaseComObject(moniker[0]);
                Marshal.ReleaseComObject(classEnum);
    
                // An exception is thrown if cast fail
                return (IBaseFilter)source;
            }
    
            public void GetInterfaces()
            {
                int hr = 0;
    
                // An exception is thrown if cast fail
                this.graphBuilder = (IFilterGraph2)new FilterGraph();
                this.captureGraphBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
                this.mediaControl = (IMediaControl)this.graphBuilder;
                this.videoWindow = (IVideoWindow)this.graphBuilder;
                
    
                DsError.ThrowExceptionForHR(hr);
            }
    
            public void CloseInterfaces()
            {
                if (mediaControl != null)
                {
                    int hr = mediaControl.StopWhenReady();
                    DsError.ThrowExceptionForHR(hr);
                }
    
                if (videoWindow != null)
                {
                    videoWindow.put_Visible(OABool.False);
                    videoWindow.put_Owner(IntPtr.Zero);
                }
    
                // Remove filter graph from the running object table.
                if (rot != null)
                {
                    rot.Dispose();
                    rot = null;
                }
    
                // Release DirectShow interfaces.
                Marshal.ReleaseComObject(this.mediaControl); this.mediaControl = null;
                Marshal.ReleaseComObject(this.videoWindow); this.videoWindow = null;
                Marshal.ReleaseComObject(this.graphBuilder); this.graphBuilder = null;
                Marshal.ReleaseComObject(this.captureGraphBuilder); this.captureGraphBuilder = null;
            }
    
            public void SetupVideoWindow()
            {
                int hr = 0;
    
                // Set the video window to be a child of the PictureBox
                hr = this.videoWindow.put_Owner(pictureBox1.Handle);
                DsError.ThrowExceptionForHR(hr);
    
                hr = this.videoWindow.put_WindowStyle(WindowStyle.Child);
                DsError.ThrowExceptionForHR(hr);
    
                // Make the video window visible, now that it is properly positioned
                hr = this.videoWindow.put_Visible(OABool.True);
                DsError.ThrowExceptionForHR(hr);
    
                // Set the video position
                Rectangle rc = pictureBox1.ClientRectangle;
                hr = videoWindow.SetWindowPosition(0, 0, _previewWidth, _previewHeight);
                DsError.ThrowExceptionForHR(hr);
            }
    
          
    
            private void SetConfigParams(ICaptureGraphBuilder2 capGraph, IBaseFilter capFilter, int iFrameRate, int iWidth, int iHeight)
            {
                int hr;
                object config;
                AMMediaType mediaType;
                // Find the stream config interface
                hr = capGraph.FindInterface(
                    PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID, out config);
    
                IAMStreamConfig videoStreamConfig = config as IAMStreamConfig;
                if (videoStreamConfig == null)
                {
                    throw new Exception("Failed to get IAMStreamConfig");
                }
    
                // Get the existing format block
                hr = videoStreamConfig.GetFormat(out mediaType);
                DsError.ThrowExceptionForHR(hr);
    
                // copy out the videoinfoheader
                VideoInfoHeader videoInfoHeader = new VideoInfoHeader();
                Marshal.PtrToStructure(mediaType.formatPtr, videoInfoHeader);
    
                // if overriding the framerate, set the frame rate
                if (iFrameRate > 0)
                {
                    videoInfoHeader.AvgTimePerFrame = 10000000 / iFrameRate;
                }
    
                // if overriding the width, set the width
                if (iWidth > 0)
                {
                    videoInfoHeader.BmiHeader.Width = iWidth;
                }
    
                // if overriding the Height, set the Height
                if (iHeight > 0)
                {
                    videoInfoHeader.BmiHeader.Height = iHeight;
                }
    
                // Copy the media structure back
                Marshal.StructureToPtr(videoInfoHeader, mediaType.formatPtr, false);
    
                // Set the new format
                hr = videoStreamConfig.SetFormat(mediaType);
                DsError.ThrowExceptionForHR(hr);
    
                DsUtils.FreeAMMediaType(mediaType);
                mediaType = null;
            }
    
            private void SaveSizeInfo(ISampleGrabber sampleGrabber)
            {
                int hr;
    
                // Get the media type from the SampleGrabber
                AMMediaType media = new AMMediaType();
                hr = sampleGrabber.GetConnectedMediaType(media);
                DsError.ThrowExceptionForHR(hr);
    
                if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
                {
                    throw new NotSupportedException("Unknown Grabber Media Format");
                }
    
                // Grab the size info
                VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
                _previewStride = _previewWidth * (videoInfoHeader.BmiHeader.BitCount / 8);
    
                DsUtils.FreeAMMediaType(media);
                media = null;
            }
    
            private void ConfigureSampleGrabber(ISampleGrabber sampleGrabber)
            {
                AMMediaType media;
                int hr;
    
                // Set the media type to Video/RBG24
                media = new AMMediaType();
                media.majorType = MediaType.Video;
                media.subType = MediaSubType.RGB24;
                media.formatType = FormatType.VideoInfo;
    
                hr = sampleGrabber.SetMediaType(media);
                DsError.ThrowExceptionForHR(hr);
    
                DsUtils.FreeAMMediaType(media);
                media = null;
    
                hr = sampleGrabber.SetCallback(this, 1);
                DsError.ThrowExceptionForHR(hr);
            }
    
            public int BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
            {
               
                if (isGrab)
                {
                    Bitmap v = new Bitmap(_previewWidth, _previewHeight, _previewStride,PixelFormat.Format24bppRgb, pBuffer);
                    //v.RotateFlip(RotateFlipType.Rotate180FlipX);
                    v.RotateFlip(RotateFlipType.Rotate90FlipX);
    
                    this.BeginInvoke((MethodInvoker)delegate
                    {                    
                        pictureBox2.BackgroundImage = v;
    
                        isGrab = false;
                    });
                }
                return 0;
            }
    
            public int SampleCB(double SampleTime, IMediaSample pSample)
            {
                //throw new NotImplementedException();            
                return 0;
            }
        }
    }
    
    展开全文
  • C#实现摄像头控制

    千次下载 热门讨论 2020-07-30 23:32:45
    在WIN7操作系统中, 资源管理器里面已经无法打开摄像头了, 这个小工具使用AForge类库实现C# 操作摄像头, 代码超级简捷 , 5行核心代码解决问题所有问题.
  • 之前一直在网上搜索相关资料,总是没找到,后面找到一个相关的例子,但是总是有问题,后面自己研究,现在是可以用了,如果你想调用平板的前摄像头你再改一下拍照界面的源码中一个索引为0,因为我默认是调用后摄像头...
  • C# 用OpenCV打开视频和摄像头

    千次阅读 2019-11-22 08:38:25
    C#可以用OpenCVSharp来打开视频文件和摄像头。关于OpenCVSharp的安装,用Nuget搜OpenCVSharp就会出来一个下载量比较多的library,点击安装后会在解决方案中出现 x64和 x86两个文件,同时在 引用 中会自动加入 OpenCv...
  • webcam(C#调用摄像头)

    热门讨论 2020-07-16 23:35:30
    C#调用摄像头,C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头C#调用摄像头
  • C#使用aforge框架打开摄像头(续)

    千次阅读 2015-10-23 18:01:53
    昨天做了个小测试,把我之前写的用aforge框架打开摄像头的小程序,运行了一晚上,结果今天早上起来发现,程序挂了。调试了好几次,也没找到原因。 --------------------------问题  刚刚 又做了测试,同时打开...
  • c# 访问USB摄像头 拍照 录像

    热门讨论 2020-07-30 23:33:24
    c# USB 摄像头 拍照 录像 两种方法实现
  • OpenCV打开摄像头

    2020-01-21 12:06:09
    OpenCV打开摄像头 话不多说,看代码,用的是C#+Opencv免费库 using OpenCvSharp; using OpenCvSharp.Extensions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data...
  • c# 采集摄像头的流

    2020-07-17 17:51:43
    c# 摄像头编程 可以采集摄像头的流 非常有启发的例子
  • C#调用本地摄像头

    2020-07-29 14:18:33
    C# 调用本地摄像头 拍照
  • 1、工具——NuGet包管理器——管理解决方案的NuGet程序包 ...6、在打开摄像头按钮内编写打开摄像头的代码 7、在计时器内编写刷新图像的代码 8、在关闭摄像头按钮内编写关闭摄像头的代码 9、运行效果 ...
  • const short WM_CAP = 1024; const int WM_CAP_DRIVER_CONNECT = WM_CAP + 10; const int WM_CAP_DRIVER_DISCONNECT = WM_CAP + 11; const int WM_CAP_EDIT_COPY = WM_CAP + 3...
1 2 3 4 5 ... 20
收藏数 2,724
精华内容 1,089
关键字:

c# 无法打开摄像头