开发者

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

开发者 https://www.devze.com 2022-12-01 12:56 出处:网络 作者: 驚鏵
此项目使用了OpenCVSharp加载本地摄像头,多个摄像头支持切换展示,也可以展示rtsp地址。使用NuGet如下:代码如下一、创建MainWindow.xaml代码如下。ws:Windowx:...

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

使用NuGet如下:

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

代码如下

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

<ws:Windowx: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="OpenCVSharpExamplehttps://github.com/WPFDevelopersOrg"Height="450"Width="800">
<Grid>
<Grid.RowDefi编程客栈nitions>
<RowDefinitionHeight="Auto"/>
<RowDefinition/>
<RowDefinitionHeight="Auto"/>
</Grid.RowDefinitions>
<ComboBoxName="ComboBoxCamera"ItemsSource="{BindingCameraArray,RelativeSource={RelativeSourceAncestorType=local:MainWindow}}"
Width="200"SelectedIndex="{BindingCameraIndex,RelativeSource={RelativeSourceAncestorType=local:MainWindow}}"
SelectionChanged="ComboBoxCamera_SelectionChanged"/>
<ImageGrid.Row="1"Name="imgViewport"Margin="0,4"/>
<StackPanelOrientation="Horizontal"
HorizontalAlignment="Center"
Grid.Row="2">
<!--<ButtonName="btRecord"Click="btRecord_Click"Content="Record"Style="{StaticResourcePrimaryButton}"Width="100"Height="50"Margin="16"/>-->
<ButtonName="btStop"Click="btStop_Click"Content="Stop"Width="100"Height="50"Margin="16"/>
</StackPanel>
</Grid>
</ws:Window>

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

usingOpenCvSharp;
usingOpenCvSharp.Extensions;
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Drawing;
usingSystem.Drawing.Imaging;
usingSystem.IO;
usingSystem.Management;
usingSystem.Threading;
usingSystemjavascript.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Media.Imaging;
usingSystem.Windows.Threading;

namespaceOpenCVSharpExample
{
///<summary>
///MainWindow.xaml的交互逻辑
///</summary>
publicpartialclassMainWindow
{
privateVideoCapturecapCamera;
privateMatmatImage=newMat();
privateThreadcameraThread;

publicList<string>CameraArray
{
get{return(List<string>)GetValue(CameraArrayProperty);}
se编程客栈t{SetValue(CameraArrayProperty,value);}
}

publicstaticreadonlyDependencyPropertyCameraArrayProperty=
DependencyProperty.Register("CameraArray",typeof(List<string>),typeof(MainWindow),newPropertyMetadata(null));



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

publicstaticreadonlyDependencyPropertyCameraIndexProperty=
DependencyProperty.Register("CameraIndex",typeof(int),typeof(MainWindow),newPropertyMetadata(0));





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

}

privatevoidMainWindow_Loaded(objectsender,RoutedEventArgse)
{
InitializeCamera();
}
privatevoidComboBoxCamera_SelectionChanged(objectsender,SelectionChangedEventArgse)
{
if(CameraArray.Count-1<CameraIndex)
return;

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

capCamera=newVideoCapture(CameraIndex);
capCamera.Fps=30;
CreateCamera();

}

privatevoidInitializeCamera()
{
CameraArray=GetAllConnectedCameras();
}
List<string>GetAllConnectedCameras()
{
varcameraNames=newList<string>();
uhttp://www.devze.comsing(varsearcher=newManagementObjectSearcher("SELECT*FROMWin32_PnPEntityWHERE(PNPClass='Image'ORPNPClass='Camera')"))
{
foreach(vardeviceinsearcher.Get())
{
cameraNames.Add(device["Caption"].ToString());
}
}

returncameraNames;
}

voidCreateCamera()
{
cameraThread=newThread(PlayCamera);
cameraThread.Start();
}

privatevoidPlayCamera()
{
while(capCamera!=null&&!capCamera.IsDisposed)
{
capCamera.Read(matImage);
if(matImage.Empty())break;
Dispatcher.BeginInvoke(DispatcherPriority.Normal,newAction(()=>
{
varconverted=Convert(BitmapConverter.开发者_开发入门ToBitmap(matImage));
imgViewport.Source=converted;
}));
}
}

privatevoidbfVmWQJMtStop_Click(objectsender,RoutedEventArgse)
{
StopDispose();
btStop.IsEnabled=false;
}

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

voidCreateRecord()
{
cameraThread=newThread(PlayCamera);
cameraThread.Start();
}

BitmapImageConvert(Bitmapsrc)
{
System.Drawing.Imageimg=src;
varnow=DateTime.Now;
varg=Graphics.FromImage(img);
varbrush=newSolidBrush(System.Drawing.Color.Red);
g.DrawString($"北京时间:{now.ToString("yyyy年MM月dd日HH:mm:ss")}",newSystem.Drawing.Font("Arial",18),brush,newPointF(5,5));
brush.Dispose();
g.Dispose();
MemoryStreamms=newMemoryStream();
img.Save(ms,ImageFormat.Bmp);
ms.Seek(0,SeekOrigin.Begin);
BitmapImageimage=newBitmapImage();
image.BeginInit();
image.StreamSource=ms;
image.EndInit();
image.Freeze();
returnimage;
}

protectedoverridevoidOnClosed(EventArgse)
{
StopDispose();
}


}
}

效果预览

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

源码地址如下

Github:https://github.com/WPFDevelopersOrg

https://github.com/WPFDevelopersOrg/OpenCVSharpExample

Gitee:https://gitee.com/WPFDevelopersOrg

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号