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调用摄像头内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C# 将透明图片的非透明区域转换成Region的实例代码

    C# 将透明图片的非透明区域转换成Region的实例代码

    以下代码实现将一张带透明度的png图片的非透明部分转换成Region输出的方法,有需要的朋友可以参考一下
    2013-10-10
  • C# 实现Scoket心跳机制的方法

    C# 实现Scoket心跳机制的方法

    这篇文章主要介绍了C# 实现Scoket心跳机制的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • C#使用Lazy<T>实现对客户订单的延迟加载

    C#使用Lazy<T>实现对客户订单的延迟加载

    这篇文章介绍了C#使用Lazy<T>实现对客户订单延迟加载的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-08-08
  • C#使用OpenCvSharp实现透视变换功能

    C#使用OpenCvSharp实现透视变换功能

    这篇文章主要为大家详细介绍了C#如何使用OpenCvSharp实现透视变换的功能,文中的示例代码简洁易懂,具有一定的学习价值,需要的小伙伴可以参考下
    2023-11-11
  • WMI获取硬件信息封装函数方法(联想台式机出厂编号 CPUID BIOS序列号 硬盘信息 显卡信息 MAC地址)

    WMI获取硬件信息封装函数方法(联想台式机出厂编号 CPUID BIOS序列号 硬盘信息 显卡信息 MAC地址)

    这篇文章主要介绍了WMI获取硬件信息的方法,硬件信息有:联想台式机出厂编号 CPUID BIOS序列号 硬盘信息 显卡信息 MAC地址
    2013-11-11
  • c#中@的3种作用

    c#中@的3种作用

    本文主要介绍了c#中@的3种作用。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-02-02
  • TortoiseSVN使用教程

    TortoiseSVN使用教程

    TortoiseSVN 是 Subversion 版本控制系统的一个免费开源客户端,可以超越时间的管理文件和目录。本文给大家介绍TortoiseSVN使用教程,对tortoisesvn使用相关知识感兴趣的朋友一起学习吧
    2015-12-12
  • 关于C#中yield关键字的深入解析

    关于C#中yield关键字的深入解析

    这篇文章主要给大家介绍了关于C#中yield关键字的深入解析,文中通过示例代码介绍的非常详细,对大家的学习或者使用C#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-11-11
  • c#使用UTF-8编码实现处理多语言文本

    c#使用UTF-8编码实现处理多语言文本

    UTF-8编码是现代应用中处理多语言文本的首选,所以本文为大家详细介绍了C#如何使用UTF-8编码实现处理多语言文本,感兴趣的小伙伴可以了解下
    2024-01-01
  • vs代码段快捷键设置(图文)

    vs代码段快捷键设置(图文)

    学习代码快捷键是程序员必学知识点,会使用代码快捷在程序开发过程中会提高开发效率,下面小编给大家整理些有关vs代码段快捷键设置的技巧,需要的朋友可以参考下
    2015-08-08

最新评论