WPF实现调用本机摄像头的示例代码
作者:驚鏵 发布时间:2023-03-15 15:40:24
标签: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
来源:https://mp.weixin.qq.com/s/j-B_lq7Vap2w6eY7g2sozg


猜你喜欢
- 引言一个复杂的分布式系统,用户发起一个请求,这个请求可能调用几十到几百个服务,经过很多业务层,而每个业务又是多个机器集群,一个请求具体被随机
- 1、首先,找到 Android SDK 在本机中的位置,如果不知道,可以通过在 Android Studio 找到,如下:2、其次,通过 c
- 前言:在 Spring 中, IOC 是很重要的概念,其本质就是 map 结构,存储容器和业务 Be
- java 归并排序的实例详解归并排序 归并排序,指的是将两个已经排序
- 1.使用WINDOWS API/// <summary> /// 判断一个磁盘驱动器的类型 /// </summary&g
- thymeleaf介绍简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP
- 前提在日常使用SpringMVC进行开发的时候,有可能遇到前端各种类型的请求参数,这里做一次相对全面的总结。SpringMVC中处理控制器参
- 原理UI设计的时候一般会按照一个固定的尺寸进行设计,如 360 x 690 ,实际设备分辨率可能是 Google Pixel: 1080 x
- 一、前期准备提示:如果友友你没有看过系列一的文章点击这个链接:王者荣耀中一个英雄是怎么被产生的?(一)我们现在功能比较多,所有为了让程序运行
- 下面的题目都是楼主在android交流群大家面试时遇到的,如果大家有好的题目或者好的见解欢迎分享,楼主将长期维护此帖。某公司高级面试题(20
- 简介石头剪刀布游戏,进入游戏后,玩家需要输入玩家姓名。系统界面之后弹出欢迎界面,玩家可以选择出拳或者退出游戏。玩家选择出拳后同电脑出拳比较,
- 本文实例为大家分享了Android实现底部滚轮式选择弹跳框的具体代码,供大家参考,具体内容如下先看效果:调用方法:SlideDialog s
- 这篇文章主要介绍了Springboot整合MybatisPlus的实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定
- 1. 概述:将一个具体类的实例化交给一个静态工厂方法来执行,它不属于GOF的23种设计模式,但现实中却经常会用到2. 模式中的角色2.1 工
- 一、前言Unity3D不仅仅可以开发游戏,还有非常多的开发方向,秉承着兴趣为先,将可以使用Unity制作的各种应用案例,分享如何进行开发,如
- 1、取得控制台应用程序的根目录方法方法1、Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径方法
- 对于某些程序,我们只允许它使用某些特定端口、网络类型或者特定IP类型等信息。这时候,需要使用到防火墙里面的“高级设置”,创建某些特定的入站或
- 本文实例讲述了C#获取字符串后几位数的方法。分享给大家供大家参考。具体实现方法如下:#region 获取后几位数 public string
- 为什么要有线程池?在实际使用中,服务器在创建和销毁线程上花费的时间和消耗的系统资源都相当大,所以要尽可能减少创建和销毁线程的次数。由于没有线
- 定义Java修饰符:修饰符用来定义类、方法或者变量,通常放在语句的最前端。分类主要分为2类:访问控制修饰符非访问控制修饰符访问控制修饰符可以