WPF实现调用本机摄像头的示例代码

 更新时间:2022年08月03日 17:11:23   作者:驚鏵  
这篇文章主要介绍了如何利用WPF实现调用本机摄像头,文中的示例代码讲解详细,对我们学习或工作有一定帮助,需要的可以参考一下

此项目使用了OpenCVSharp加载本地摄像头,多个摄像头支持切换展示,也可以展示rtsp地址。

使用NuGet如下:

代码如下

一、创建MainWindow.xaml代码如下。

 <ws:Window x:Class="OpenCVSharpExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ws="https://github.com/WPFDevelopersOrg.WPFDevelopers.Minimal"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:OpenCVSharpExample"
        Icon="OpenCV_Logo.png"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen"
        Title="OpenCVSharpExample https://github.com/WPFDevelopersOrg" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ComboBox Name="ComboBoxCamera" ItemsSource="{Binding CameraArray,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" 
                  Width="200" SelectedIndex="{Binding CameraIndex,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
                  SelectionChanged="ComboBoxCamera_SelectionChanged"/>
        <Image Grid.Row="1" Name="imgViewport" Margin="0,4"/>
        <StackPanel Orientation="Horizontal"
                    HorizontalAlignment="Center"
                    Grid.Row="2">
            <!--<Button Name="btRecord" Click="btRecord_Click" Content="Record" Style="{StaticResource PrimaryButton}" Width="100" Height="50" Margin="16"/>-->
            <Button Name="btStop" Click="btStop_Click" Content="Stop"  Width="100" Height="50" Margin="16"/>
        </StackPanel>
    </Grid>
</ws:Window>

二、MainWindow.xaml.cs代码如下。

using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Management;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace OpenCVSharpExample
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow
    {
        private VideoCapture capCamera;
        private Mat matImage = new Mat();
        private Thread cameraThread;

        public List<string> CameraArray
        {
            get { return (List<string>)GetValue(CameraArrayProperty); }
            set { SetValue(CameraArrayProperty, value); }
        }

        public static readonly DependencyProperty CameraArrayProperty =
            DependencyProperty.Register("CameraArray", typeof(List<string>), typeof(MainWindow), new PropertyMetadata(null));



        public int CameraIndex
        {
            get { return (int)GetValue(CameraIndexProperty); }
            set { SetValue(CameraIndexProperty, value); }
        }

        public static readonly DependencyProperty CameraIndexProperty =
            DependencyProperty.Register("CameraIndex", typeof(int), typeof(MainWindow), new PropertyMetadata(0));



        

        public MainWindow()
        {
            InitializeComponent();
            Width = SystemParameters.WorkArea.Width / 1.5;
            Height = SystemParameters.WorkArea.Height / 1.5;
            this.Loaded += MainWindow_Loaded;

        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeCamera();
        }
        private void ComboBoxCamera_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CameraArray.Count - 1 < CameraIndex)
                return;

            if (capCamera != null && cameraThread != null)
            {
                cameraThread.Abort();
                StopDispose();
            }

            capCamera = new VideoCapture(CameraIndex);
            capCamera.Fps = 30;
            CreateCamera();
            
        }

        private void InitializeCamera()
        {
            CameraArray = GetAllConnectedCameras();
        }
        List<string> GetAllConnectedCameras()
        {
            var cameraNames = new List<string>();
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
            {
                foreach (var device in searcher.Get())
                {
                    cameraNames.Add(device["Caption"].ToString());
                }
            }

            return cameraNames;
        }

        void CreateCamera()
        {
            cameraThread = new Thread(PlayCamera);
            cameraThread.Start();
        }

        private void PlayCamera()
        {
            while (capCamera != null && !capCamera.IsDisposed)
            {
                capCamera.Read(matImage);
                if (matImage.Empty()) break;
                Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                {
                    var converted = Convert(BitmapConverter.ToBitmap(matImage));
                    imgViewport.Source = converted;
                }));
            }
        }
       
        private void btStop_Click(object sender, RoutedEventArgs e)
        {
            StopDispose();
            btStop.IsEnabled = false;
        }

        void StopDispose()
        {
            if (capCamera != null && capCamera.IsOpened())
            {
                capCamera.Dispose();
                capCamera = null;
            }
        }

        void CreateRecord()
        {
            cameraThread = new Thread(PlayCamera);
            cameraThread.Start();
        }

        BitmapImage Convert(Bitmap src)
        {
            System.Drawing.Image img = src;
            var now = DateTime.Now;
            var g = Graphics.FromImage(img);
            var brush = new SolidBrush(System.Drawing.Color.Red);
            g.DrawString($"北京时间:{ now.ToString("yyyy年MM月dd日 HH:mm:ss")}", new System.Drawing.Font("Arial", 18), brush, new PointF(5, 5));
            brush.Dispose();
            g.Dispose();
            MemoryStream ms = new MemoryStream();
            img.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = ms;
            image.EndInit();
            image.Freeze();
            return image;
        }

        protected override void OnClosed(EventArgs e)
        {
            StopDispose();
        }


    }
}

效果预览

源码地址如下

Github:https://github.com/WPFDevelopersOrg

https://github.com/WPFDevelopersOrg/OpenCVSharpExample

Gitee:https://gitee.com/WPFDevelopersOrg

到此这篇关于WPF实现调用本机摄像头的示例代码的文章就介绍到这了,更多相关WPF调用摄像头内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 一文详解Unity3D AudioSource组件使用示例

    一文详解Unity3D AudioSource组件使用示例

    这篇文章主要为大家介绍了一文详解Unity3D AudioSource组件使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • WPF实现绘制3D图形的示例代码

    WPF实现绘制3D图形的示例代码

    WPF的3D功能可以在不编写任何c#代码的情况下进行绘制,只需要使用xaml即可完成3D图形的渲染。本文主要讲述了WPF-3D中的关键概念, 以及常用到的命中测试、2d控件如何在3D对象中进行渲染,希望大家有所帮助
    2023-03-03
  • C# 压榨cpu的办法(推荐)

    C# 压榨cpu的办法(推荐)

    这篇文章主要介绍了C# 压榨cpu的办法,通过修改num的值,观察cpu的核数,例如我电脑是8核的,改成8,运行时各个核都能跑满,感兴趣的朋友跟随小编一起看看吧
    2021-12-12
  • C#+MO实现一个道路编辑软件(刚开始)

    C#+MO实现一个道路编辑软件(刚开始)

    C#+MO实现一个道路编辑软件(刚开始)...
    2007-04-04
  • C#在 .NET中使用依赖注入的示例详解

    C#在 .NET中使用依赖注入的示例详解

    这篇文章主要为大家详细介绍了C#如何在 .NET中使用依赖注入,文中的示例代码讲解详细,具有一定的学习价值,感兴趣的小伙伴可以跟随小编一起了解一下
    2024-01-01
  • c# List find()方法返回值的问题说明(返回结果为对象的指针)

    c# List find()方法返回值的问题说明(返回结果为对象的指针)

    本篇文章主要介绍了c#中List find()方法返回值的问题说明(返回结果为对象的指针) 需要的朋友可以过来参考下,希望对大家有所帮助
    2014-01-01
  • C#多线程开发实战记录之线程基础

    C#多线程开发实战记录之线程基础

    线程是一个独立的运行单元,每个进程内部有多个线程,每个线程可以各自同时执行指令,每个线程有自己独立的栈,但是与进程内的其他线程共享内存,这篇文章主要给大家介绍了关于C#多线程开发实战记录之线程基础的相关资料,需要的朋友可以参考下
    2021-09-09
  • C#多线程之线程通讯(AutoResetEvent)

    C#多线程之线程通讯(AutoResetEvent)

    这篇文章介绍了C#多线程之线程通讯(AutoResetEvent)的用法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-04-04
  • 浅谈C#中Action和Func回调的常用方式

    浅谈C#中Action和Func回调的常用方式

    Action和Func泛型委托实际上就是一个.NET Framework预定义的委托,本文主要介绍了C#中Action和Func回调的常用方式,具有一定的参加价值,感兴趣的可以了解一下
    2022-03-03
  • C#如何遍历Dictionary

    C#如何遍历Dictionary

    这篇文章主要为大家详细介绍了C#遍历Dictionary的方法,.NET中的Dictionary是键/值对的集合,使用起来比较方便,Dictionary也可以用KeyValuePair来迭代遍历,感兴趣的小伙伴们可以参考一下
    2016-04-04

最新评论