WPF 实现调用本机摄像头~

WPF开发者QQ群:340500857

       由于微信群人数太多入群请添加小编微信号

 yanjinhuawechatW_Feng_aiQ 邀请入群

 需备注WPF开发者 

  PS:有更好的方式欢迎推荐。

  接着很久前的上一篇

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

使用NuGet如下:

598b92607d5c93be872d2a9e324db540.png

01

代码如下

一、创建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();}}
}

02


效果预览

鸣谢素材提供者屈越

333d4ab56bdc9a727bb47a7096c124f6.png

源码地址如下

Github:https://github.com/WPFDevelopersOrg

https://github.com/WPFDevelopersOrg/OpenCVSharpExample

Gitee:https://gitee.com/WPFDevelopersOrg

WPF开发者QQ群: 340500857 

Github:https://github.com/WPFDevelopersOrg

出处:https://www.cnblogs.com/yanjinhua

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

转载请著名作者 出处 https://github.com/WPFDevelopersOrg

6569578fbd0e288213d91390ad2cb822.png

扫一扫关注我们,

0fcf54755fb0f1329140aa522d4edd25.gif

更多知识早知道!

68fbda848a1baf3a3fa48fe0e0662f0b.gif

点击阅读原文可跳转至源代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/291460.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python process 函数_Python Process创建进程的2种方法详解

前面介绍了使用 os.fork() 函数实现多进程编程&#xff0c;该方法最明显的缺陷就是不适用于 Windows 系统。本节将介绍一种支持 Python 在 Windows 平台上创建新进程的方法。Python multiprocessing 模块提供了 Process 类&#xff0c;该类可用来在 Windows 平台上创建新进程。…

全球增长最快域名解析商Top10:中国占据四席

IDC评述网&#xff08;idcps.com&#xff09;04月29日报道&#xff1a;根据国外域名统计机构DailyChanges最新实时数据显示&#xff0c;4月27日&#xff0c;在全球增长最快的十家域名解析服务商榜单中&#xff0c;中国占据四个席位。上榜的中国域名解析商分别是&#xff1a;51D…

webpake-node-sass 报错

问题描述&#xff1a; npm run dev 就报错&#xff0c;在安装node-sass错误 解决方法 &#xff1a; 找到node_modules下的node-sass文件&#xff0c;进入&#xff0c;如果没有vendor文件夹&#xff0c;就创建一个空文件夹&#xff0c;命名为vendor。 1:下载 对于版本的 binding…

C++之‘nullptr’ was not declared in this scope

在vim里面写了一个简单cpp文件,为了避免野指针,需要指针初始化 char *p2 = nullptr 1、编译时报错如下 2、解决办法 编译加上 g++ -std=gnu++0x int.cpp -o int 3、C里面的null和C++里面的nullptr、NULL介绍 NULL在C++中的定义 /* Define NULL pointer value */ #ifndef …

IOS原生地图与高德地图

原生地图 1、什么是LBS LBS: 基于位置的服务 Location Based Service 实际应用:大众点评&#xff0c;陌陌&#xff0c;微信&#xff0c;美团等需要用到地图或定位的App 2、定位方式 1.GPS定位 2.基站定位 3.WIFI定位 3、框架 MapKit:地图框架&#xff0c;显示地图 …

想说爱你不容易 | 使用最小 WEB API 实现文件上传

前言在 .NET 6 之前&#xff0c;实现文件上传功能十分简单&#xff1a;[HttpPost("upload")] public async Task<IActionResult> Upload(IFormFile file) {//对file执行操作return Ok(file.FileName); }但是&#xff0c;当使用 .NET 6 的最小 WEB API 来实现相…

python商用_python实现sm2和sm4国密(国家商用密码)算法的示例

GMSSL模块介绍GmSSL是一个开源的加密包的python实现&#xff0c;支持SM2/SM3/SM4等国密(国家商用密码)算法、项目采用对商业应用友好的类BSD开源许可证&#xff0c;开源且可以用于闭源的商业应用。安装模块pip install gmsslSM2算法RSA算法的危机在于其存在亚指数算法&#xff…

Android下载文件

2019独角兽企业重金招聘Python工程师标准>>> package com.test;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;import android.app.Activity;import android.content.Intent…

C++之operator关键字(重载操作符) 使用总结

operator是C++的关键字,它和运算符一起使用,表示一个运算符函数, 一、为什么使用操作符重载 简单的说我们基本数据比如int float 都可以比较大小 有>、<、=,但是对象需要比较大小怎么办,我们也可以用>、<、=,只不过我们需要一个通用的规范比较对象的属性…

#HTTP协议学习# (七)cookie

本文转自&#xff1a;http://www.cnblogs.com/TankXiao/archive/2012/12/12/2794160.html Cookie是HTTP协议中非常重要的东西&#xff0c; 之前拜读了Fish Li 写的【细说Cookie】&#xff0c; 让我学到了很多东西。Fish的这篇文章写得太经典了。 所以我这篇文章就没有太多内容了…

C#中的类型~存储~变量

欢迎您成为我的读者&#xff0c;希望这篇文章能给你一些帮助。前言今天在群里看到朋友讨论把粉丝称为读者&#xff0c;这让我内心特别激动。以前我还是比较关注自己的文章阅读量&#xff0c;有没有人转发&#xff0c;今天新增多少个关注。而现在&#xff0c;我的关注点变了&…

sql-逻辑循环while if

--计算1-100的和declare int int1;declare total int0;while(int<100)beginset totaltotalint;set intint 1;endselect total--计算1-100偶数的和declare index int;declare sum int;set index1;set sum0;while(index<100)beginif(index%20)beginset sumsumindexendset i…

mysql常用cmd指令_Mysql cmd 常用命令

连接&#xff1a;mysql -h主机地址 -u用户名 &#xff0d;p用户密码 (注:u与root可以不用加空格&#xff0c;其它也一样)断开&#xff1a;exit (回车)创建授权&#xff1a;grant select on 数据库.* to 用户名登录主机 identified by \"密码\"修改密码&#xff1a;my…

C++之typename

1、typename和class 在模板前,typename和class没有区别 template<typename T> class A; template<class T> class A;typename和class对编译器而言却是不同的东西 2、声明一个类型 看下面的代码 我们编译下结果如下 编译器不知道T::const_iterator是个类型。如果…

ubuntu 的QT4的qmake失败的处理方法

安装qt4以后使用命令行编译时出现一下错误&#xff1a;administratorubuntu:~/qt/qt-book/chap01/hello$ qmake hello.pro程序 qmake 已包含在以下软件包中&#xff1a;* qt3-dev-tools* qt4-qmake试试&#xff1a;sudo apt-get install <选定的软件包>bash: qmake&#…

gulp与webpack的区别

常有人拿gulp与webpack来比较&#xff0c;知道这两个构建工具功能上有重叠的地方&#xff0c;可单用&#xff0c;也可一起用&#xff0c;但本质的区别就没有那么清晰。 gulp gulp强调的是前端开发的工作流程&#xff0c;我们可以通过配置一系列的task&#xff0c;定义task处理的…

mooc数据结构与算法python版期末考试_数据结构与算法Python版-中国大学mooc-试题题目及答案...

数据结构与算法Python版-中国大学mooc-试题题目及答案更多相关问题婴儿出生一两天后就有笑的反应&#xff0c;这种笑的反应属于()。【判断题】填制原始凭证&#xff0c;汉字大写金额数字一律用正楷或草书书写&#xff0c;汉字大写金额数字到元位或角位为止的&#xff0c;后面必…

使用 NetCoreBeauty 优化 .NET CORE 独立部署目录结构

在将一个 .NET CORE \ .NET 5.0 \ .NET 6.0 程序进行独立部署发布时&#xff0c;会在发布目录产生很多系统类库&#xff0c;导致目录非常不简洁。这给寻找入口程序造成了困难&#xff0c;特别是路遥工具箱这种绿色软件&#xff0c;不会在开始菜单、系统桌面创建快捷方式&#x…

关于注释

在编写程序时&#xff0c;应当给程序添加一些注释&#xff0c;用于说明某段代码的作用&#xff0c;或者说明某个类的用途&#xff0c;某个方法的功能&#xff0c;以及该方法的参数和返回值类型和意义等。 很多初学者开始学习编程语言时&#xff0c;会很努力写程序&#xff0c;但…

从此不再惧怕URI编码:JavaScript及C# URI编码详解

混乱的URI编码 JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent C#中编码主要方法&#xff1a;HttpUtility.UrlEncode、Server.UrlEncode、Uri.EscapeUriString、Uri.EscapeDataString JavaScript中的还好&#xff0c;只提供了三个&#xff0c;C#中主要用的…