Win10 + VS2017 + WPF 捕获摄像头并实时显示画面

系统状态:

1, Windows10 1909(内部版本 18363.778)

2,Visual Studio Community 2017 (Version 15.9.16)

3,已安装Windows 10 SDK

4,.Net Framework 4.8

网上介绍有几个方法:Nuget的WPFMediaKit、MediaCaptureWPF以及.Net自带的MediaCapture、CameraCaptureUI
WPFMediaKit好像默认只能将camera的画面保存成为image file不能直接读取当前帧的数据;MediaCaptureWPF无法build成为any cpu platform;CameraCaptureUI会使用默认的UWP UI。。。


所以我们只能用MediaCapture,官方教程:https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/basic-photo-video-and-audio-capture-with-mediacapture

因为我们的是WPF App,所以无法直接调用UWP API。

有三个方法可以让WPF程序,调用UWP API:

1,NuGet下载UwpDesktop(强烈不建议!它支持的API太久没更新,实际使用的时候经常有各种问题)

2,在安装Windows10 SDK之后,手动在project references里添加以下两个文件的引用:
C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

3,.Net 4.6+或者.Net Core3.0+,并且Windows10是1803版本之后,可以NuGet下载Microsoft.Windows.SDK.Contracts

以上方式,最好都自动将 NuGet 包的引用方式从 packages.config 升级为 PackageReference。否则运行时可能会出错。

准备好让WPF调用WinRT API之后,为了让WPF显示摄像头画面,我们还需要在NuGet下载MMaitre.MediaCaptureWPF。
但是这玩意不能编译成为any CPU,所以只能将项目转为x64。

准备妥当,代码就很容易了:

using MediaCaptureWPF;
using System;
using System.Windows;
using Windows.Media.Capture;

------------------------------------

private MediaCapture captureManager;

private async void Window_Loaded(object sender, RoutedEventArgs e)
{
            captureManager = new MediaCapture();
            await captureManager.InitializeAsync();

            var preview = new CapturePreview(captureManager);
            this.webCamImage.Source = preview; //XAML页面的一个Image控件
            await preview.StartAsync();
}

这样,当程序跑起来,就能在UI界面看到摄像头的实时画面了。

如果想获取摄像头某一时刻的byte data,就有点麻烦:


var lowLagCapture = await captureManager.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));

var capturedPhoto = await lowLagCapture.CaptureAsync();
using (var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap)
{
    Task<byte[]> bytes =  await GetPixelBytesFromSoftwareBitmapAsync(softwareBitmap));
}

await lowLagCapture.FinishAsync();

------------------------------------------------------

public static async Task<byte[]> GetPixelBytesFromSoftwareBitmapAsync(SoftwareBitmap softwareBitmap)
{
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                Windows.Graphics.Imaging.BitmapEncoder encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, stream);
                encoder.SetSoftwareBitmap(softwareBitmap);
                await encoder.FlushAsync();

                // Read the pixel bytes from the memory stream
                using (var reader = new DataReader(stream.GetInputStreamAt(0)))
                {
                    var bytes = new byte[stream.Size];
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(bytes);
                    return bytes;
                }
            }
}

 

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实时显示摄像头视频可以使用WPF中的MediaElement控件来实现。具体步骤如下: 1.在XAML文件中添加MediaElement控件,并设置其Source属性为摄像头视频的地址: ```xml <MediaElement x:Name="videoPlayer" Source="摄像头视频地址" /> ``` 2.在代码中使用DirectShowLib库来获取摄像头视频流,并将其绑定到MediaElement控件上: ```csharp using DirectShowLib; private void StartCamera() { // 获取摄像头设备 DsDevice[] devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice); // 初始化视频捕获设备 IFilterGraph2 filterGraph = new FilterGraph() as IFilterGraph2; ICaptureGraphBuilder2 captureGraphBuilder = new CaptureGraphBuilder2() as ICaptureGraphBuilder2; captureGraphBuilder.SetFiltergraph(filterGraph); IBaseFilter sourceFilter = null; captureGraphBuilder.FindInterface(PinCategory.Capture, MediaType.Video, devices[0], typeof(IBaseFilter).GUID, out sourceFilter); // 添加视频捕获设备到FilterGraph中 IBaseFilter nullRenderer = new NullRenderer() as IBaseFilter; filterGraph.AddFilter(sourceFilter, "source"); filterGraph.AddFilter(nullRenderer, "null"); // 获取视频捕获设备的输出端口 IPin sourceOutputPin = DsFindPin.ByDirection(sourceFilter, PinDirection.Output, 0); IPin nullInputPin = DsFindPin.ByDirection(nullRenderer, PinDirection.Input, 0); // 连接视频捕获设备和nullRenderer filterGraph.Connect(sourceOutputPin, nullInputPin); // 将视频流绑定到MediaElement控件 IMediaControl mediaControl = filterGraph as IMediaControl; mediaControl.Run(); videoPlayer.Source = MediaCoreFactory.CreateMediaStreamSource(new MediaUriSource(new Uri("http://localhost:8080"))); } ``` 需要注意的是,如果摄像头设备有多个,需要根据实际情况选择需要使用的设备。 3.启动应用程序后,摄像头视频就会实时显示在MediaElement控件中了。 以上就是使用WPF中的MediaElement控件来实现实时显示摄像头视频的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值