当前位置:网站首页>WPF implementation calls local camera~
WPF implementation calls local camera~
2022-06-28 23:57:00 【Dotnet cross platform】
WPF developer QQ Group :340500857
Because there are too many people in wechat group, please add a small wechat signal
yanjinhuawechat or W_Feng_aiQ Invite in
Note required WPF developer
PS: There are better ways to recommend .
And then a long time ago Last one
This project uses OpenCVSharp Load local camera , Multiple cameras support switching display , You can also show rtsp Address .
Use NuGet as follows :

01
—
The code is as follows
One 、 establish MainWindow.xaml The code is as follows .
<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>Two 、MainWindow.xaml.cs The code is as follows .
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 Interaction logic of
/// </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($" Beijing time. :{ now.ToString("yyyy year MM month dd Japan 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
—
Results the preview
Thank the material provider - Qu Yue

The source address is as follows
Github:https://github.com/WPFDevelopersOrg
https://github.com/WPFDevelopersOrg/OpenCVSharpExample
Gitee:https://gitee.com/WPFDevelopersOrg
WPF developer QQ Group : 340500857
Github:https://github.com/WPFDevelopersOrg
Source :https://www.cnblogs.com/yanjinhua
Copyright : This work adopts 「 A signature - Noncommercial use - Share in the same way 4.0 The international 」 License agreement to license .
Please reprint the famous author Source https://github.com/WPFDevelopersOrg

Scan and pay attention to us ,

More knowledge would have known !

Click to read the original text to jump to the source code
边栏推荐
- Phoenix installation tutorial
- Stm32f407------- external interrupt
- Quartz explanation and use
- 6.28 学习内容
- 解决ConfigParser解析中文问题
- 炒股开户万一免五是靠谱么,安全么
- Machine learning 6-decision tree
- Is it safe to open a stock account on the Internet?
- How to make two objects or arrays equal
- urllib. Parse parses the parameters in the URL connection
猜你喜欢
![[software analysis] iterative explanation of software analysis, design and modeling](/img/37/1163fec464aed365d1ea04e63a0c90.png)
[software analysis] iterative explanation of software analysis, design and modeling

Easy to use free ppt template

stm32F407-------LCD

Implementation of dynamic timer for quartz

剑指 Offer 12. 矩阵中的路径

Auto encoder

Windows10 phpstudy installing redis extension

What pitfalls should be avoided in the job interview for the operation post in 2022?

MSYQL is abnormal. Don't worry. Mr. Allen will point out the puzzle

The secondary market is full of bad news. How should the market go next? One article will show you the general trend
随机推荐
stm32F407-------IO引脚复用映射
Picture 64base transcoding and decoding
"Five considerations" for safe use of the Internet
What will be done after digital IC Verification?
Learn binary tree like this
What is the lifecycle of automated testing?
Common mistakes in software testing
MapReduce案例
[opencv] - linear filtering: box filtering, mean filtering, Gaussian filtering
Technology sharing | software development process that you must understand if you want to get started with testing
What are some tips to improve your interview success rate?
With notes: insert sort --from WCC
Mobile heterogeneous computing technology - GPU OpenCL programming (basic)
Scrapy使用xlwt实现将数据以Excel格式导出的Exporter
Hesitating root sound
stm32F407-------GPIO输入实验
PHP函数file_get_contents与操作系统的内存映射
【LeetCode】21. 合并两个有序链表 - Go 语言题解
Test experience: how testers evolve from 0 to 1
Stm32f407----- register address name mapping analysis