使用Aforge 开发的摄像头,有拍照,录像,设置帧率,分辨率等,以及对视频以及相机等的控制-程序员宅基地

技术标签: C#  音视频  AFORGE 摄像头处理  ffmpeg  WPF  windows  

先上图,这是整个功能的界面: (这里就连了两个相机,如果想连接上百个,这里提一句超级优化的方向,大家可以使用双缓冲概念(是不是很懵?),其实说白了,就是多幅位图绘制到一张位图上显示. 以前也是做实时绘制的时候,不知不觉就使用这种方式,直到后来,才听到 双缓冲 这个看似“高大上的”概念,真是倒腾概念.?)

首先声明,里面应该使用线程的方式,大家记得重新封装,代替里面的DispatcherTimer 。好,废话不多说,我们开始.

一: 大家下载Aforge等的 dll ---> 添加到引用里面.(在我的资源里有,这个也是我调试了很多dll版本,才发现这个版本很稳定,其他dll版本,一言难尽)

, 

在后台代码里 ,引入dll所在的命名空间.

using AForge.Video;
using AForge.Video.DirectShow;

using AForge.Video.FFMPEG;

二: 环境搭载完成后,我们来看xaml文件.

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WP_摄像头AFore版本"
        xmlns:Intersoft="http://intersoft.clientui.com/schemas" 
        x:Class="WP_摄像头AFore版本.MainWindow"
        Title="MainWindow" Height="550" Width="900" Loaded="Win_Loaded" Closed="Win_Cloded">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="4*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border Grid.Row="0">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="5*"/>
                    <ColumnDefinition Width="4*"/>
                    <ColumnDefinition Width="5*"/>
                </Grid.ColumnDefinitions>
                <Border Grid.Column="0">
                    <GroupBox>
                        <GroupBox.Header>
                            <TextBlock><Run Text="左相机"/></TextBlock>
                        </GroupBox.Header>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition></RowDefinition>
                                <RowDefinition Height="50"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Image x:Name="VceL">
                            </Image>
                            <Border Grid.Row="1">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="5*"></ColumnDefinition>
                                        <ColumnDefinition Width="3*"></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <Label x:Name="TextBlocL" VerticalContentAlignment="Center" HorizontalContentAlignment="Left"></Label>
                                    <Label Grid.Column="1" x:Name="fps_L" VerticalContentAlignment="Center" HorizontalContentAlignment="Left"></Label>
                                    <Label Grid.Column="2" Content="fps" VerticalContentAlignment="Center"></Label>
                                </Grid>
                            </Border>
                            <!--<Canvas >
                                <wfi:WindowsFormsHost>
                                    <local:UserControl11 x:Name="User1"></local:UserControl11>
                                </wfi:WindowsFormsHost>
                            </Canvas>-->                                                       
                        </Grid>
                    </GroupBox>
                </Border>
                <Border Grid.Column="1" BorderBrush="LightGray" BorderThickness="0.5">
                    <Grid ShowGridLines="False">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>
                        <Border Grid.Row="0">
                            <GroupBox>
                                <GroupBox.Header>
                                    <TextBlock><Run Text="视频设备"/></TextBlock>
                                </GroupBox.Header>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Border Grid.Column="0" Margin="5">
                                        <DockPanel LastChildFill="True">
                                            <Label HorizontalContentAlignment="Center" DockPanel.Dock="Left" Content="L"/>
                                            <ComboBox x:Name="Combox_L" Margin="0,5,0,5" SelectionChanged="Combox_L_SelectionChanged"/>
                                        </DockPanel>
                                    </Border>
                                    <Border Grid.Column="1" Margin="5">
                                        <DockPanel LastChildFill="True" FlowDirection="RightToLeft">
                                            <Label HorizontalContentAlignment="Center" DockPanel.Dock="Left" Content="R"/>
                                            <ComboBox FlowDirection="LeftToRight" x:Name="Combox_R" Margin="0,5,0,5"  SelectionChanged="Combox_R_SelectionChanged"/>
                                        </DockPanel>
                                    </Border>
                                </Grid>
                            </GroupBox>
                        </Border>
                        <Border Grid.Row="1">
                            <GroupBox>
                                <GroupBox.Header>
                                    <TextBlock Text="视频操作"/>
                                </GroupBox.Header>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition Width="25"/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Border Grid.Column="0"  Margin="5">
                                        <Button x:Name="Open_Vedio" Click="Open_VedioClick" Content="打开视频"/>
                                    </Border>
                                    <Border Grid.Column="2"  Margin="5">
                                        <Button x:Name="Close_vedio" Click="Close_vedioClick" Content="关闭视频"/>
                                    </Border>
                                </Grid>
                            </GroupBox>

                        </Border>
                        <Border Grid.Row="2">
                            <GroupBox>
                                <GroupBox.Header>
                                    <TextBlock><Run Text="拍照操作"/></TextBlock>
                                </GroupBox.Header>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Border Grid.Column="0" Margin="5">
                                        <Button Click="photos_Click" Content="拍照"/>
                                    </Border>
                                    <Border Grid.Column="1">
                                        <DockPanel>
                                            <Label Content="图格式" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"/>
                                            <ComboBox x:Name="cmbImageFormat" Margin="0,5,0,5" SelectionChanged="cmbImageFormat_SelectionChanged" VerticalContentAlignment="Center"
                                                      HorizontalContentAlignment="Left">
                                              
                                            </ComboBox>
                                        </DockPanel>
                                    </Border>
                                </Grid>
                            </GroupBox>
                        </Border>
                        <Border Grid.Row="3">
                            <GroupBox>
                                <GroupBox.Header>
                                    <TextBlock Text="录像操作"/>
                                </GroupBox.Header>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <Border Grid.Column="0" Margin="5">
                                        <Button Content="开始录像" Click="Statr_recordClick"/>
                                    </Border>
                                    <Border Grid.Column="1" Margin="5">
                                        <Button Content="停止录像" Click="Stop_recordClick"/>
                                    </Border>
                                </Grid>
                            </GroupBox>

                        </Border>
                        <Border Grid.Row="4">
                            <GroupBox>
                                <GroupBox.Header>
                                    <TextBlock Text="帧率设置"/>
                                </GroupBox.Header>
                                <Grid>
                                    <DockPanel Margin="5">
                                        <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Content="帧率设定"/>
                                        <TextBox x:Name="Set_boxFrame" Text="25" VerticalContentAlignment="Center" HorizontalContentAlignment="Left"/>
                                    </DockPanel>
                                </Grid>
                            </GroupBox>
                        </Border>
                        <Border Grid.Row="5">
                            <GroupBox>
                                <GroupBox.Header>
                                    <TextBlock Text="视频设置"/>
                                </GroupBox.Header>
                                <Grid>
                                    <DockPanel>
                                        <Label VerticalContentAlignment="Center" Content="分辨率"/>
                                        <ComboBox x:Name="resolutionCombox" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" Margin="5" SelectionChanged="resolutionCombox_SelectionChanged"/>
                                    </DockPanel>
                                </Grid>
                            </GroupBox>
                        </Border>
                    </Grid>
                </Border>
                <Border Grid.Column="2">
                    <GroupBox FlowDirection="RightToLeft">
                        <GroupBox.Header>
                            <TextBlock><Run Text="右相机"/></TextBlock>
                        </GroupBox.Header>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition></RowDefinition>
                                <RowDefinition Height="50"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Image x:Name="VceR" >
                                <!--<Image.RenderTransform>
                                    <RotateTransform Angle="90"></RotateTransform>
                                </Image.RenderTransform>-->
                            </Image>
                            <Border Grid.Row="1" FlowDirection="LeftToRight">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="5*"></ColumnDefinition>
                                        <ColumnDefinition Width="3*"></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <Label x:Name="TextBlocR" VerticalContentAlignment="Center" HorizontalContentAlignment="Left"></Label>
                                    <Label Grid.Column="1" x:Name="fps_R" VerticalContentAlignment="Center" HorizontalContentAlignment="Left"></Label>
                                    <Label Grid.Column="2" Content="fps" VerticalContentAlignment="Center"></Label>
                                </Grid>
                            </Border>
                        </Grid>
                    </GroupBox>
                </Border>
            </Grid>
        </Border>
        <Border Grid.Row="1">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="3*"/>
                    <ColumnDefinition Width="2*"/>
                    <ColumnDefinition Width="3*"/>
                </Grid.ColumnDefinitions>
                <Border Grid.Column="0" Margin="3">
                    <DockPanel Margin="30,0,30,0">
                        <Button Width="50" Height="20" DockPanel.Dock="Top" VerticalAlignment="Top" Content="T" Click="Button_Click_5"/>
                        <Button Width="50" Height="20" DockPanel.Dock="Bottom" VerticalAlignment="Bottom" Content="B" Click="Button_Click_7"/>
                        <Button Width="50" Height="20" DockPanel.Dock="Left" HorizontalAlignment="Left" Content="L" Click="Button_Click_4"/>
                        <Button Width="50" Height="20" DockPanel.Dock="Left" HorizontalAlignment="Right" Content="R" Click="Button_Click_6"/>

                    </DockPanel>
                </Border>
                <Border Grid.Column="1">
                    <StackPanel>
                        <Button Margin="2" Content="检测" Click="Check_demoClick"/>
                        <Button x:Name="VideoSourceSet" Content="视频源设置" Margin="2" Click="VideoSourceSet_Click"></Button>
                        <Button Visibility="Collapsed" Content="Demo" Margin="2" />
                        <Button Visibility="Collapsed" Content="Demo2" Margin="2"/>
                        
                    </StackPanel>
                </Border>
                <Border Grid.Column="2" Margin="3">
                    <DockPanel Margin="30,0,30,0">
                        <Button Width="50" Height="20" DockPanel.Dock="Top" VerticalAlignment="Top" Content="T" Click="Button_Click_1"/>
                        <Button Width="50" Height="20" DockPanel.Dock="Bottom" VerticalAlignment="Bottom" Content="B" Click="Button_Click_3"/>
                        <Button Width="50" Height="20" DockPanel.Dock="Left" HorizontalAlignment="Left" Content="L" Click="Button_Click"/>
                        <Button Width="50" Height="20" DockPanel.Dock="Left" HorizontalAlignment="Right" Content="R" Click="Button_Click_2"/>
                    </DockPanel>
                </Border>
            </Grid>
        </Border>
    </Grid>
</Window>

因为这个Aforge,貌似只放在winform空间里,为了不使用那个winformhost,我们就创建两个  form 中的自定义控件,来承载AForge上传过来的视频图像.(反正两种方式都可以,就是宿主窗口,这里为了省事.)

上面两个userControl2.cs,都只是一个form控件.

我们来看其后台代码:

namespace WP_摄像头AFore版本
{
    public partial class UserControl2 : UserControl
    {
        public UserControl2()
        {
            InitializeComponent();
        }
        public AForge.Controls.VideoSourcePlayer getvideoSourcePlayer2
        {
            get
            {
                return videoSourcePlayer2;
            }
            set
            {
                videoSourcePlayer2 = value;
            }
        }
    }
}


/这里式usercontrol1() 的后台代码
namespace WP_摄像头AFore版本
{
    public partial class UserControl11 : UserControl
    {
        public UserControl11()
        {
            InitializeComponent();
          //  rotateTransform = new RotateTransform(180, getvideoSourcePlayer1.Width / 2, getvideoSourcePlayer1.Height / 2);//180度
           
        }
        
      //  public RotateTransform rotateTransform;
        public AForge.Controls.VideoSourcePlayer getvideoSourcePlayer1
        {
            get
            {
                return videoSourcePlayer1;
            }
            set
            {
                videoSourcePlayer1 = value;
            }
        }

    }
}


准备工作完成之后,我们来看主界面功能的实现:  注意啊:下面代码太长了,我没有整理,大家就对应着前面的xaml界面中的功能, 自己选择 ....


//一些变量.
 public static  string Path_DicPhone = System.AppDomain.CurrentDomain.BaseDirectory + @"Phone";
        public static  string Path_DicPhoneL = System.AppDomain.CurrentDomain.BaseDirectory + @"Phone\Image_L";
        public static string Path_DicPhoneR = System.AppDomain.CurrentDomain.BaseDirectory + @"Phone\Image_R";
        public static string Path_DicVideoL = System.AppDomain.CurrentDomain.BaseDirectory + @"Video\Video_L";
        public static string Path_DicVideoR = System.AppDomain.CurrentDomain.BaseDirectory + @"Video\Video_R";

        public string imageExt;
        public FilterInfoCollection videoDevices;
        private Stopwatch stopWatch = null;

        /// <summary>
        /// 等研究一下这个东西 视频设置分辨率方面
        /// </summary>
         public VideoCapabilities videoCapability;

        public List<string> deviceName = new List<string>();

        public DispatcherTimer dispather = new DispatcherTimer();
        public DispatcherTimer dispather2 = new DispatcherTimer();
        public DispatcherTimer dispather_fps = new DispatcherTimer();

        public UserControl11 User1 = new UserControl11();
        public UserControl2 User2 = new UserControl2();

        public VideoFileWriter videoWriterL = null;
        public VideoFileWriter videoWriterR = null;
        private bool createNewFile = true;
        private bool createNewFile2 = true;


//这里是初始化功能. 在界面加载的时候

private void Win_Loaded(object sender, RoutedEventArgs e)
 {
            initVideo();

            initDirectoryLR();

            dispather.Tick += new EventHandler(despatherTimer_Tick);
            dispather.Interval = new TimeSpan(0);

            dispather2.Tick += new EventHandler(despatherTimer_Tick2);
            dispather2.Interval = new TimeSpan(0);

            dispather_fps.Tick += new EventHandler(despatherTimer_TickFps);
            dispather_fps.Interval = new TimeSpan(0);

          
            
  }


    //初始化摄像头,获取可用设备.
     private void initVideo()
        {

            
            Combox_L.ItemsSource = null;
            Combox_R.ItemsSource = null;
            deviceName.Clear();
            try
            {
                videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if(videoDevices.Count <=0)
                {
                    MessageBox.Show("没有检测到任何摄像头");
                    return;
                }
                else
                {

                    for(int i =0;i<videoDevices.Count;i++)
                    {
                        deviceName.Add(videoDevices[i].Name);
                    }
                     Combox_L.ItemsSource = Combox_R.ItemsSource = deviceName;

                     if(videoDevices.Count>1)
                     {
                         Combox_L.SelectedIndex = 0;
                         Combox_R.SelectedIndex = 1;
                         
                         if(Combox_L.IsEnabled == false)
                         {
                             Combox_L.IsEnabled = true;
                         }
                         if (Combox_R.IsEnabled == false)
                         {
                             Combox_R.IsEnabled = true;
                         }
                        
                     }
                     else
                     {
                         Combox_L.SelectedIndex = 0;
                         if(Combox_R.IsEnabled == true)
                            Combox_R.IsEnabled = false;
                     }      
                }
                

            }
            catch(exception ex)
            {
                throw(ex.message);
            }

           
          

        }

 public void initDirectoryLR()
        {
            //这里初始化的时候,创建文件夹
            if (!Directory.Exists(Path_DicPhone))
            {
                Directory.CreateDirectory(Path_DicPhone);
            }
            if (!Directory.Exists(Path_DicPhoneL))
            {
                Directory.CreateDirectory(Path_DicPhoneL);
            }
            if (!Directory.Exists(Path_DicPhoneR))
            {
                Directory.CreateDirectory(Path_DicPhoneR);
            }

            if (!Directory.Exists(Path_DicVideoL))
            {
                Directory.CreateDirectory(Path_DicVideoL);
            }
            if (!Directory.Exists(Path_DicVideoR))
            {
                Directory.CreateDirectory(Path_DicVideoR);
            }


            //这里给其加载图像格式
            string[] formats = new string[] { "jpg", "png", "bmp", "icon", "emf", "tiff", "wmf", "exif", "gif" };  //, "memorybmp"
            cmbImageFormat.ItemsSource = formats;
            cmbImageFormat.SelectedIndex = 0;
            getimageFormat = ImageFormat.Jpeg;
            imageExt = @".jpg";

            //这里添加视频格式
            videoSource1 = new VideoCaptureDevice(videoDevices[Combox_L.SelectedIndex].MonikerString);
            User1.getvideoSourcePlayer1.VideoSource = videoSource1;
            videoSource1.NewFrame += new NewFrameEventHandler(LmyCaptureDevice_NewFrame);

            foreach (VideoCapabilities videoCap in videoSource1.VideoCapabilities)
            {
                resolutionCombox.Items.Add(videoCap.FrameSize.Width + "x" + videoCap.FrameSize.Height);
            }

            resolutionCombox.SelectedIndex = 0;

            if (videoSource1.VideoCapabilities.Length>0)
            {
                videoCapability = videoSource1.VideoCapabilities[0];
            }
          
         

        }


//注册回调函数

public void  despatherTimer_Tick(object sender, EventArgs e)
        {
            if (getbit != null)
            {
                image_to_where(getbit, sige_Chek.sige_L);
                TextBlocL.Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //这里和上面那个Image都能录制
                //先尝试一下这边这个
             
                #region
                if (StopERC_L)
                {

                    //停止录制
                    createNewFile = true;
                    StopERC_L = true;
                    Set_boxFrame.IsEnabled = true;
                    if (videoWriterL != null)
                    {
                        videoWriterL.Close();
                        videoWriterL.Dispose();
                    } 
                    
                }
                else
                {
                    //开始录制

                    try
                    {
                        _frameRate = int.Parse(Set_boxFrame.Text.ToString());
                    }
                    catch
                    {
                        _frameRate = 25;
                    }
                    Set_boxFrame.IsEnabled = false;

                    if (createNewFile)
                    {
                        videoFileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + @".avi";
                        createNewFile = false;
                        try
                        {
                            videoFilePath_L = Path_DicVideoL + @"\" + videoFileName;
                            if (videoWriterL != null)
                            {
                                videoWriterL.Close();
                                videoWriterL.Dispose();
                            }
                            videoWriterL = new AForge.Video.FFMPEG.VideoFileWriter();
                            videoWriterL.Open(videoFilePath_L, getbit.Width, getbit.Height, _frameRate, AForge.Video.FFMPEG.VideoCodec.MPEG4);
                            videoWriterL.WriteVideoFrame(getbit);
                        }
                        catch
                        {

                        }

                    }
                    videoWriterL.WriteVideoFrame(getbit);
                }
                #endregion
            }
            else
            {
                image_to_where(getbit2, sige_Chek.sige_L);
            }
        }
   public void despatherTimer_Tick2(object sender, EventArgs e)
        {
            if (getbit3 != null)
            {
                image_to_where(getbit3, sige_Chek.sige_R);
                TextBlocR.Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                
               
                #region
                if (StopERC_R)
                {

                    //停止录制
                    createNewFile2 = true;
                    StopERC_R = true;
                   
                    if(Set_boxFrame.IsEnabled == false)
                        Set_boxFrame.IsEnabled = true;
                    
                    if (videoWriterR != null)
                    {
                        videoWriterR.Close();
                        videoWriterR.Dispose();
                    }

                }
                else
                {
                    //开始录制

                    try
                    {
                        _frameRate = int.Parse(Set_boxFrame.Text.ToString());
                    }
                    catch
                    {
                        _frameRate = 25;
                    }
                    if (Set_boxFrame.IsEnabled == true)
                         Set_boxFrame.IsEnabled = false;

                    if (createNewFile2)
                    {
                        createNewFile2 = false;
                        try
                        {
                            videoFilePath_R = Path_DicVideoR + @"\" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + @".avi";
                            if (videoWriterR != null)
                            {
                                videoWriterR.Close();
                                videoWriterR.Dispose();
                            }
                            videoWriterR = new AForge.Video.FFMPEG.VideoFileWriter();
                            videoWriterR.Open(videoFilePath_R, getbit3.Width, getbit3.Height, _frameRate, AForge.Video.FFMPEG.VideoCodec.MPEG4);
                            videoWriterR.WriteVideoFrame(getbit3);
                        }
                        catch
                        {

                        }

                    }
                    videoWriterR.WriteVideoFrame(getbit3);
                }
                #endregion
            }
            else
            {
                image_to_where(getbit4, sige_Chek.sige_R);
            }
        }

 /// <summary>
        /// fps
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void despatherTimer_TickFps(object sender, EventArgs e)
        {
            //这里是左面相机的帧率
            int framesReceived = videoSource1.FramesReceived;
            int framesReceived2 = videoSource2.FramesReceived;
            if (stopWatch == null)
            {
                stopWatch = new Stopwatch();
                stopWatch.Start();
            }
            else
            {
               
                stopWatch.Stop();
                float fps = 1000f * framesReceived / stopWatch.ElapsedMilliseconds;
                fps_L.Content = (fps).ToString();

                float fps2 = 1000f * framesReceived2 / stopWatch.ElapsedMilliseconds;
                fps_R.Content = (fps2).ToString();

                stopWatch.Reset();
                stopWatch.Start();
            }
        }



 /// <summary>
        /// 获取所有摄像头设备
        /// </summary>
        /// <returns></returns>
        public FilterInfoCollection GetDevices()
        {
            try
            {
                //枚举所有视频输入设备
                FilterInfoCollection videoDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if (videoDevice.Count != 0)
                {
                    return videoDevice;
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


 private void Open_VedioClick(object sender, RoutedEventArgs e)
        {
            StartCameras();
        }

public VideoCaptureDevice myCaptureDevice = null;
        public VideoCaptureDevice videoSource1;
        public VideoCaptureDevice videoSource2;
        public void StartCameras()
        {
            //左相机

            if (Combox_L.IsEnabled == true)
            {
                //videoSource1 = new VideoCaptureDevice(videoDevices[Combox_L.SelectedIndex].MonikerString);
                //User1.getvideoSourcePlayer1.VideoSource = videoSource1;
                //videoSource1.NewFrame += new NewFrameEventHandler(LmyCaptureDevice_NewFrame);
                videoSource1.VideoResolution = videoCapability;
                User1.getvideoSourcePlayer1.Start();
                dispather.Start();
                
                fps_L.Content = videoSource1.FramesReceived.ToString();
               
               
            }
            
            //右面相机
            if (Combox_R.IsEnabled == true)
            {
                videoSource2 = new VideoCaptureDevice(videoDevices[Combox_R.SelectedIndex].MonikerString);
                User2.getvideoSourcePlayer2.VideoSource = videoSource2;
                videoSource2.NewFrame += new NewFrameEventHandler(RmyCaptureDevice_NewFrame);
                videoSource2.VideoResolution = videoCapability;
                User2.getvideoSourcePlayer2.Start();
                dispather2.Start();
                fps_R.Content = videoSource2.FramesReceived.ToString(); //最后,这连个东西落在定时器里面
            }

           // dispather_fps.Start();
            //分辨率的选择框框灰色
            if(resolutionCombox.IsEnabled == true)
                resolutionCombox.IsEnabled = false;

        }


    public long bbb = 0;
        public Bitmap getbit;
        public Bitmap getbit2;

        public Bitmap getbit3;
        public Bitmap getbit4;
       
        public Graphics g;
        public Graphics g2;
      
        public System.Drawing.Bitmap bitmap;
        public System.Drawing.Bitmap bitmap2;

        private string drawDate = string.Empty;
        public bool StopERC_L = true;
        public bool StopERC_R = true;

        /// <summary>
        /// 这个是录制的文件的时间名字
        /// </summary>
        public string videoFileName = string.Empty;

        public string videoFilePath_L = string.Empty;
        public string videoFilePath_R = string.Empty;

      
        private int _frameRate = 25;  //默认帧率
        /// <summary>
        /// 这东西能获取图像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        public void LmyCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
              bitmap = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
              //getbit = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
              getbit2 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();

               


                #region  这里是对视频上添加一些自己想要的东西 添加水印
                g = Graphics.FromImage(bitmap);
              // g.RotateTransform(180);
              //g.DrawImage(bitmap, 0, 0);


                SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Red);
                Font drawFont = new Font("Arial", 6, System.Drawing.FontStyle.Bold, GraphicsUnit.Millimeter);
                int xPos = bitmap.Width - (bitmap.Width - 15);
                int yPos = 10;
                drawDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                g.DrawString(drawDate, drawFont, drawBrush, xPos, yPos);
                getbit = bitmap;
                Console.WriteLine("NO " + (bbb++).ToString());
               // g.Dispose();
                #endregion
            }
            catch
            {
                return;
            }
        }

 public void RmyCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            try
            {
                bitmap2 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
                getbit3 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
                getbit4 = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
              
              //  g2 = Graphics.FromImage(bitmap2);
               // g2.RotateTransform(180);
               // g2.DrawImage(bitmap2, 0, 0);
                // image_to_where(bitmap, VceR);
              //  g2.Clear(System.Drawing.Color.Black);
              //g2.Dispose();
            }
            catch
            {
                return;
            }
        }
 /// 开始录像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Statr_recordClick(object sender, RoutedEventArgs e)
        {
            StopERC_L = false;
            StopERC_R = false;
        }

        /// <summary>
        /// 停止录像
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Stop_recordClick(object sender, RoutedEventArgs e)
        {
            StopERC_L =true;
            StopERC_R = true;
        }

public enum sige_Chek
        {
            sige_L,
            sige_R
        }
       public void image_to_where(Bitmap bb,sige_Chek sige)
        {
       
            //if(bb == null) return;

            try
            {              
                System.Drawing.Image b_demo2 = bb;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                b_demo2.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray());
            bi.EndInit();

           
            this.Dispatcher.Invoke(new Action(delegate
            {
              //SetValue(RenderOptions.BitmapScalingModeProperty, BitmapScalingMode.HighQuality);
                if (sige == sige_Chek.sige_R)
                {                  
                    rotateTransform2 = new RotateTransform(setAngel, VceL.ActualWidth / 2, VceL.ActualHeight / 2);//180度
                    VceR.RenderTransform = rotateTransform2;
                    VceR.Source = bi;
                }
                if(sige == sige_Chek.sige_L)
                {
                                    
                    rotateTransform2 = new RotateTransform(setAngel2, VceL.ActualWidth / 2, VceL.ActualHeight / 2);//180度
                    VceL.RenderTransform = rotateTransform2;
                    VceL.Source = bi;
                }
               
                                
            }));
            }
            catch
            {

            }
        }
       public RotateTransform rotateTransform;
       public RotateTransform rotateTransform2;

 public static int setAngel = 270;
       public static int setAngel2 = 90;
       public void myCaptureDevice_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            
            System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
            
          
            System.Drawing.Image b_demo = bitmap.Clone(
            new RectangleF((bitmap.Size.Width - 295) / 2, (bitmap.Size.Height - 413) / 2, 100,100), //显示图像的宽度为295像素,高度为413像素
              System.Drawing.Imaging.PixelFormat.Format32bppRgb);
            
            
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            b_demo.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

          

            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray());
            bi.EndInit();
            RotateTransform rotateTransform;

            this.Dispatcher.Invoke(new Action(delegate
            {
                //SetValue(RenderOptions.BitmapScalingModeProperty, BitmapScalingMode.HighQuality);

                this.VceR.Source = bi;
               // rotateTransform = new RotateTransform(0, VceR.ActualWidth / 2, VceR.ActualHeight / 2);//180度
              //  VceR.RenderTransform = rotateTransform;//图片控件旋转


            }));
          // this.VceR.Dispatcher.Invoke(new Action(() => { this.VceR.Source = bi; }));
            
            ms.Close();

        }

 private void Close_vedioClick(object sender, RoutedEventArgs e)
        {
            User1.getvideoSourcePlayer1.SignalToStop();
            User1.getvideoSourcePlayer1.WaitForStop();
            dispather.Stop();
            if(g!=null)
             g.Dispose();

            User2.getvideoSourcePlayer2.SignalToStop();
            User2.getvideoSourcePlayer2.WaitForStop();
            dispather2.Stop();
            if(g2!=null)
             g2.Dispose();

            //fps 帧率的获取

          //  dispather_fps.Stop();
         
            if (resolutionCombox.IsEnabled == false)
                resolutionCombox.IsEnabled = true;

        }
        private void photos_Click(object sender, RoutedEventArgs e)
        {

            //两种都可以,随意取舍
            PhotoImage(VceL,sige_Chek.sige_L);
            ClipSaveBmp(VceL, sige_Chek.sige_L);

            PhotoImage(VceR,sige_Chek.sige_R);
            ClipSaveBmp(VceR,sige_Chek.sige_R);
        }
        private string fileName = "";
        public RenderTargetBitmap bmp;
        public void PhotoImage(FrameworkElement vce,sige_Chek sign)
        {
            try
            {
                bmp = new RenderTargetBitmap((int)vce.ActualWidth, (int)vce.ActualHeight, 96, 96, PixelFormats.Default);
            }
            catch
            {
                return;
            }
            vce.Measure(vce.RenderSize);
           // vce.Arrange(new Rect(vce.RenderSize));
            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();
                if (sign == sige_Chek.sige_L)
                {
                    fileName = Path_DicPhoneL +@"\L"+ DateTime.Now.ToString("yyyyMMddHHmmss") + @".jpg";
                }
                if(sign == sige_Chek.sige_R)
                {
                    fileName = Path_DicPhoneR + @"\R" + DateTime.Now.ToString("yyyyMMddHHmmss") + @".jpg";
                }

                File.WriteAllBytes(fileName, captureData);
            }
        }
        public ImageFormat getimageFormat;

  public void ClipSaveBmp(FrameworkElement vce, sige_Chek sign)
        {
            try
            {
                if (sign == sige_Chek.sige_L)
                {
                    fileName = Path_DicPhoneL + @"\L" + DateTime.Now.ToString("yyyyMMddHHmmss") + imageExt;
                    getbit.Save(fileName, getimageFormat);
                }
                else
                {
                    fileName = Path_DicPhoneR + @"\R" + DateTime.Now.ToString("yyyyMMddHHmmss") + imageExt;
                    getbit3.Save(fileName, getimageFormat);
                }
            }
            catch
            {
                MessageBox.Show("请打开摄像头");
                return;
            }
        }

   private void Combox_L_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Combox_R_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Check_demoClick(object sender, RoutedEventArgs e)
        {
            initVideo();
        }

        private void Wnd_Cloded(object sender, EventArgs e)
        {
           if(myCaptureDevice!=null)
           {
               if(myCaptureDevice.IsRunning)
               {
                   myCaptureDevice.SignalToStop();
               }

               myCaptureDevice = null;
           }


           User1.getvideoSourcePlayer1.Stop();
           dispather.Stop();
           g.Dispose();

           User2.getvideoSourcePlayer2.Stop();
           dispather2.Stop();
           g2.Dispose();

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            setAngel = 0;
            rotateTransform = new RotateTransform(setAngel, VceR.ActualWidth / 2, VceR.ActualHeight / 2);//180度
            VceR.RenderTransform = rotateTransform;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            setAngel = 270;
            rotateTransform = new RotateTransform(setAngel, VceR.ActualWidth / 2, VceR.ActualHeight / 2);//180度
            VceR.RenderTransform = rotateTransform;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            setAngel = 180;
            rotateTransform = new RotateTransform(setAngel, VceR.ActualWidth / 2, VceR.ActualHeight / 2);//180度
            VceR.RenderTransform = rotateTransform;
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            setAngel = 90;
            rotateTransform = new RotateTransform(setAngel, VceR.ActualWidth / 2, VceR.ActualHeight / 2);//180度
            VceR.RenderTransform = rotateTransform;
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            setAngel2 = 0;
            rotateTransform2 = new RotateTransform(setAngel2, VceL.ActualWidth / 2, VceL.ActualHeight / 2);//180度
            VceL.RenderTransform = rotateTransform2;
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            setAngel2 = 90;
            rotateTransform2 = new RotateTransform(setAngel2, VceL.ActualWidth / 2, VceL.ActualHeight / 2);//180度
            VceL.RenderTransform = rotateTransform2;
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            setAngel2 = 180;
            rotateTransform2 = new RotateTransform(setAngel2, VceL.ActualWidth / 2, VceL.ActualHeight / 2);//180度
            VceL.RenderTransform = rotateTransform2;
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            setAngel2 = 270;
            rotateTransform2 = new RotateTransform(setAngel2, VceL.ActualWidth / 2, VceL.ActualHeight / 2);//180度
            VceL.RenderTransform = rotateTransform2;
        }

        private void Win_Cloded(object sender, EventArgs e)
        {
            User1.getvideoSourcePlayer1.SignalToStop();
            User1.getvideoSourcePlayer1.WaitForStop();
            dispather.Stop();
            if(g!=null)
                g.Dispose();


            User2.getvideoSourcePlayer2.SignalToStop();
            User2.getvideoSourcePlayer2.WaitForStop();
            dispather2.Stop();
            if (g2 != null)
             g2.Dispose();
        }

        private void cmbImageFormat_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbImageFormat.Items.Count <= 0)
                return;

            string formatType = cmbImageFormat.SelectedItem.ToString();
            SelectedImageFormat(formatType);
        }
        private void SelectedImageFormat(string formatType)
        {
            switch (formatType)
            {
                case "jpg":
                    getimageFormat = ImageFormat.Jpeg;
                    imageExt = ".jpg";
                    break;
                case "bmp":
                    getimageFormat = ImageFormat.Bmp;
                    imageExt = ".bmp";
                    break;
                case "gif":
                    getimageFormat = ImageFormat.Gif;
                    imageExt = ".gif";
                    break;
                case "png":
                    getimageFormat = ImageFormat.Png;
                    imageExt = ".png";
                    break;
                case "tiff":
                    getimageFormat = ImageFormat.Tiff;
                    imageExt = ".tiff";
                    break;
                case "icon":
                    getimageFormat = ImageFormat.Icon;
                    imageExt = ".ico";
                    break;
                case "emf":
                    getimageFormat = ImageFormat.Emf;
                    imageExt = ".emf";
                    break;
                case "wmf":
                    getimageFormat = ImageFormat.Wmf;
                    imageExt = ".wmf";
                    break;
                case "exif":
                    getimageFormat = ImageFormat.Exif;
                    imageExt = ".exif";
                    break;
                default:
                    getimageFormat = ImageFormat.Jpeg;
                    imageExt = ".jpg";
                    break;

            }
        }

        /// <summary>
        /// 视频分辨率的设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resolutionCombox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (resolutionCombox.Items.Count <= 0)
                return;

            videoCapability = videoSource1.VideoCapabilities[resolutionCombox.SelectedIndex];
        }


        /// <summary>
        /// 视频源设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VideoSourceSet_Click(object sender, RoutedEventArgs e)
        {
           
            try
            {
                videoSource1.DisplayPropertyPage(User1.getvideoSourcePlayer1.Handle);
                videoSource2.DisplayPropertyPage(User2.getvideoSourcePlayer2.Handle);
              //  videoSource1.DisplayCrossbarPropertyPage(User1.getvideoSourcePlayer1.Handle);
              //  videoSource2.DisplayCrossbarPropertyPage(User2.getvideoSourcePlayer2.Handle);
            }
            catch (Exception ex)
            {
                //视频源必须按顺序运行显示横梁属性页?
                MessageBox.Show(ex.ToString()+"  "+videoSource1.CheckIfCrossbarAvailable());

                Console.WriteLine(ex.ToString());
               
            }
        }
  
      
       
    }




// 上面代码太多,见谅,大家从里面   选择一些自己需要的功能,自己调试.

//这是拍照功能.

//这是录像

以上就是这个摄像头的操作,里面可优化的空间很大,这个就是摄像头涉及到的基本功能显示,很原始。

对了,提一句:你可以对这个摄像头采集到的图像,使用AForge做各种图像上的处理,比如高斯模糊,提取边缘,什么膨胀,腐蚀,提取交点啊等等(里面对图像的处理接口,我也已经写好了哈,大伙儿直接处理那个bitmap就行了),反正opencv里面可以做的,你在这里都可以处理,  这样就实现了我们视频 上各种特效...我这里只是提了个引子,之前这些图像都处理过,一口气写了几十个,有机会,给大家分享这些

如果大家优化了更好的,可以@我,我也学习一下.?

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_36564005/article/details/97489138

智能推荐

Labview队列使用方法----一文读懂队列底层原理及用法-程序员宅基地

文章浏览阅读2.3k次,点赞35次,收藏41次。题主非常详细的介绍了队列的原理及使用方法,帮助读者在原理上深刻理解队列的底层逻辑,并介绍了队列使用时的注意事项。后续将更新更多相关文章记得点赞加关注,谢谢~_labview队列

教你用Python爬取哔哩哔哩全站视频信息_b站访问权限不足爬虫-程序员宅基地

文章浏览阅读1.8k次。哔哩哔哩全站视频信息爬虫(可能会漏爬)B 站感觉最近几年发展得太快了,不由得想知道有多少视频,翻阅了一大半网络找了很多爬虫感觉都不是特别的复合自己的胃口(挑食~),于是自己写一个(才学习爬虫没多久写得垃圾代码大佬别喷我啊….)很多人学习python,不知道从何学起。很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。很多已经做案例的人,却不知道如何去学习更加高深的知识。那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!??¤QQ群_b站访问权限不足爬虫

(新版)SJTU-OJ-1003. 在麦当劳配数据-程序员宅基地

文章浏览阅读431次,点赞4次,收藏2次。题目描述注意:本题可以使用的头文件仅限于cstdioiostreamcstring梦回高三,小艾想起了几个月前背诵高考古诗文篇目的时光……已经是晚上了。第二天有小测,可是小艾还有篇古诗文没有背。这篇古诗文都有一个对应的瞌睡值,也就是说,选择背诵篇目会让小艾的瞌睡程度增加​。小艾目前的瞌睡程度已经是,而当小艾的瞌睡程度时,小艾会直接睡到明早,那可就没有更多的时间背了!注意,因为背了一半的文章也是没背出来的文章,所以恰好让小艾瞌睡程度的那篇也视作没背的。好在小测考到每个篇目的概率是一..._在麦当劳配数据

ubuntu16安装colmap的问题及解决方案_cudasetupargument 未定义的引用-程序员宅基地

文章浏览阅读2.3k次,点赞14次,收藏28次。最近想入门一下三维重建,看了一些三维重建的论文,还是想从SFM入手。先了解一下SFM里面经典的colmap(论文:[Structure-from-Motion Revisited](https://demuc.de/papers/schoenberger2016sfm.pdf)),看论文难以深入理解,所以打算看看源码,也是为了完成一个小小礼物。_cudasetupargument 未定义的引用

windows使用libvlc进行网络串流遇到的一些问题及解决方法_libvlc网络-程序员宅基地

文章浏览阅读857次。windows使用libvlc进行网络串流遇到的一些问题及解决方法_libvlc网络

ffmpeg--libswscale(图像缩放、颜色空间和像素格式转换操作)-程序员宅基地

文章浏览阅读1k次。主要函数:(1) sws_getContext():使用参数初始化SwsContext结构体。 可以用另一个接口函数sws_getCachedContext()取代。(2) sws_scale():转换一帧图像。(3) sws_freeContext():释放SwsContext结构体。初始化方式2种:①sws_getContext②sws_al..._libswscale

随便推点

CyclicBarrier和CountDownLatch的区别_countdownlatch是一次性的,cyclicbarrier可以重用。-程序员宅基地

文章浏览阅读90次。CountDownLatch减计数,CyclicBarrier加计数。 CountDownLatch是一次性的,CyclicBarrier可以重用。 CountDownLatch强调一个线程或者多个线程等待其他线程执行完毕后执行、CyclicBarrier强调的是多个线程相互等待执行完毕..._countdownlatch是一次性的,cyclicbarrier可以重用。

coco2017数据集百度网盘链接_coco百度网盘-程序员宅基地

文章浏览阅读8.1k次,点赞28次,收藏22次。coco2017数据集百度网盘链接链接:https://pan.baidu.com/s/1NTdU1-h2b5r2Hwc9DiwPig提取码:fwou_coco百度网盘

IDEA配置tomcat时出现的问题及解决(HTTP状态404-未找到)_运行ideahttp状态 404 - 未找到-程序员宅基地

文章浏览阅读2.1w次,点赞8次,收藏75次。IDEA配置tomcat出现的问题及解决问题1:没有新建环境变量解决:在系统环境变量中添加变量CATALINA_BASE和CATALINA_BASE,两个变量的值都是tomcat的安装路径(如下图所示)问题2:tomcat设置depolyment有误解决:添加的Artifact是“项目名:war_exploded”而不是“项目名:war”。特别注意的是:Application context中要改成“/”(如下图所示)一开始的样子:成功后:..._运行ideahttp状态 404 - 未找到

J2EE快速开发平台-程序员宅基地

文章浏览阅读48次。2019独角兽企业重金招聘Python工程师标准>>> ..._j2ee开放平台

Docker快速搭建Jaeger开发环境(Docker 部署Jaeger all-in-one)_docker 部署jaeger 部署-程序员宅基地

文章浏览阅读6.4k次。通过Docker 快速搭建Jaeger 本地测试、开发联调环境。_docker 部署jaeger 部署

推荐文章

热门文章

相关标签