经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
Windows Community Toolkit 3.0 - CameraPreview
来源:cnblogs  作者:shaomeng  时间:2018/9/25 20:41:41  对本文有异议

概述

Windows Community Toolkit 3.0 于 2018 年 6 月 2 日 Release,同时正式更名为 Windows Community Toolkit,原名为 UWP Community Toolkit。顾名思义,3.0 版本会更注重整个 Windows 平台的工具实现,而不再只局限于 UWP 应用,这从 Release Note 也可以看出来:https://github.com/Microsoft/WindowsCommunityToolkit/releases

我们从今年 3 月份开始陆续针对 Windows Community Toolkit 2.2 版本的特性和代码实现做了分析,从本篇开始,我们会对 3.0 版本做持续的分享,首先本篇带来的关于 CameraPreview 相关的分享。

CameraPreview 控件允许在 MediaPlayerElement 中简单预览摄像机帧源组的视频,开发者可以在所选摄像机实时获取 Video Frame 和 Bitmap,仅显示支持彩色视频预览或视频记录流。

这是一个非常有用的控件,之前在 Face++ 工作时,我们做的很多事情都是对摄像头传出的视频帧做人脸检测或关键点标注等操作。所以该控件对摄像头的控制,以及对视频帧的传出,就成了我们工作的资源源头,我们对视频帧做规范化,再进行算法处理,再把处理后的视频帧反馈到视频播放控件中,就可以完成检测,人脸美颜处理等很多操作。

Windows Community Toolkit Doc - CameraPreview 

Windows Community Toolkit Source Code - CameraPreview

Namespace: Microsoft.Toolkit.Uwp.UI.Controls; Nuget: Microsoft.Toolkit.Uwp.UI.Controls;

 

开发过程

代码分析

首先来看 CameraPreview 的类结构:

  • CameraPreview.Cpmstants.cs - 定义了 CameraPreview 的两个常量字符串;
  • CameraPreview.Events.cs - 定义了 CameraPreview 的事件处理 PreviewFailed;
  • CameraPreview.Properties.cs - 定义了 CameraPreview 的依赖属性 IsFrameSourceGroupButtonVisible;
  • CameraPreview.cs - CameraPreview 的主要处理逻辑;
  • CameraPreview.xaml - CameraPreview 的样式文件;
  • PreviewFailedEventArgs.cs - 定义了 CameraPreview 的事件处理 PreviewFailed 的参数;

接下来我们主要关注 CameraPreview.xaml 和 CameraPreview.cs 的代码实现:

1. CameraPreview.xaml

CameraPreview 控件的样式文件组成很简单,就是用户播放预览视频帧的 MediaPlayerElement 和 FrameSourceGroup 按钮。

  1. <Style TargetType="local:CameraPreview" >
  2. <Setter Property="Template">
  3. <Setter.Value>
  4. <ControlTemplate TargetType="local:CameraPreview">
  5. <Grid Background="{TemplateBinding Background}">
  6. <MediaPlayerElement x:Name="MediaPlayerElementControl" HorizontalAlignment="Left">
  7. </MediaPlayerElement>
  8. <Button x:Name="FrameSourceGroupButton" Background="{ThemeResource SystemBaseLowColor}"
  9. VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5">
  10. <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE89E;" Foreground="{ThemeResource SystemAltHighColor}" />
  11. </Button>
  12. </Grid>
  13. </ControlTemplate>
  14. </Setter.Value>
  15. </Setter>
  16. </Style>

2. CameraPreview.cs

我们先来看一下 CameraPreview 的类组成:

整体的处理逻辑很清晰:

  1. 通过 OnApplyTemplate(), InitializeAsync(), SetUIControls(), SetMediaPlayerSource() 等方法初始化控件,初始化摄像头视频源组,选择视频源赋值 MediaPleyerElement 做展示;
  2. 通过 StartAsync() 方法开始使用摄像头视频源,开发者用于展示和获取每一帧图像 Bitmap;
  3. 使用完成后,调用 Stop() 来结束并释放摄像头资源;

而 CameraPreview 类中出现了一个很重要的帮助类 CameraHelper,它的作用是对摄像头资源的获取和视频帧的获取/处理,它是 CameraPreview 中的核心部分,下面我们来看 CameraHelper 的实现:

我们看到 CameraHelper 类中包括了获取摄像头视频源组,初始化和开始获取视频帧,接收视频帧进行处理,释放资源等方法,我们来看几个主要方法实现:

1. GetFrameSourceGroupsAsync()

获取视频源组的方法,使用 DeviceInformation 类获取所有类别为 VideoCapture 的设备,再使用 MediaFrameSourceGroup 类获取所有 mediaFrameSourceGroup,在 groups 中获取彩色视频预览和视频录制的所有 group。

  1. public static async Task<IReadOnlyList<MediaFrameSourceGroup>> GetFrameSourceGroupsAsync()
  2. {
  3. if (_frameSourceGroups == null)
  4. {
  5. var videoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
  6. var groups = await MediaFrameSourceGroup.FindAllAsync();
  7. // Filter out color video preview and video record type sources and remove duplicates video devices.
  8. _frameSourceGroups = groups.Where(g => g.SourceInfos.Any(s => s.SourceKind == MediaFrameSourceKind.Color &&
  9. (s.MediaStreamType == MediaStreamType.VideoPreview || s.MediaStreamType == MediaStreamType.VideoRecord))
  10. && g.SourceInfos.All(sourceInfo => videoDevices.Any(vd => vd.Id == sourceInfo.DeviceInformation.Id))).ToList();
  11. }
  12. return _frameSourceGroups;
  13. }

2. InitializeAndStartCaptureAsync()

使用 GetFrameSourceGroupsAsync() 和 InitializeMediaCaptureAsync() 对视频源组和 MediaCapture 进行初始化;利用 MediaCapture 读取选择的视频源组对应的预览帧源,注册 Reader_FrameArrived 事件,开始读取操作,返回操作结果;

  1. public async Task<CameraHelperResult> InitializeAndStartCaptureAsync()
  2. {
  3. CameraHelperResult result;
  4. try
  5. {
  6. await semaphoreSlim.WaitAsync();
  7. ...
  8. result = await InitializeMediaCaptureAsync();
  9. if (_previewFrameSource != null)
  10. {
  11. _frameReader = await _mediaCapture.CreateFrameReaderAsync(_previewFrameSource);
  12. if (Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent("Windows.Media.Capture.Frames.MediaFrameReader", "AcquisitionMode"))
  13. {
  14. _frameReader.AcquisitionMode = MediaFrameReaderAcquisitionMode.Realtime;
  15. }
  16. _frameReader.FrameArrived += Reader_FrameArrived;
  17. if (_frameReader == null)
  18. {
  19. result = CameraHelperResult.CreateFrameReaderFailed;
  20. }
  21. else
  22. {
  23. MediaFrameReaderStartStatus statusResult = await _frameReader.StartAsync();
  24. if (statusResult != MediaFrameReaderStartStatus.Success)
  25. {
  26. result = CameraHelperResult.StartFrameReaderFailed;
  27. }
  28. }
  29. }
  30. _initialized = result == CameraHelperResult.Success;
  31. return result;
  32. }
  33. ...
  34. }

3. InitializeMediaCaptureAsync()

上面方法中使用的初始化 MediaCapture 的方法,首先获取预览帧源,获取顺序是彩色预览 -> 视频录制;接着判断它支持的格式,包括视频帧率(>= 15 帧),媒体编码格式的支持(Nv12,Bgra8,Yuy2,Rgb32),按照视频宽高进行排序;对支持状态进行判断,如果状态可用,则返回默认最高分辨率;同时该方法会对权限等进行判断,对错误状态返回对应状态;只有状态为 CameraHelperResult.Success 时才是正确状态。

CameraHelperResult 中对应的错误状态有:CreateFrameReaderFailed,StartFrameReaderFailed,NoFrameSourceGroupAvailable,NoFrameSourceAvailable,CameraAccessDenied,InitializationFailed_UnknownError,NoCompatibleFrameFormatAvailable。

  1. private async Task<CameraHelperResult> InitializeMediaCaptureAsync()
  2. {
  3. ...
  4. try
  5. {
  6. await _mediaCapture.InitializeAsync(settings);
  7. // Find the first video preview or record stream available
  8. _previewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoPreview
  9. && source.Value.Info.SourceKind == MediaFrameSourceKind.Color).Value;
  10. if (_previewFrameSource == null)
  11. {
  12. _previewFrameSource = _mediaCapture.FrameSources.FirstOrDefault(source => source.Value.Info.MediaStreamType == MediaStreamType.VideoRecord
  13. && source.Value.Info.SourceKind == MediaFrameSourceKind.Color).Value;
  14. }
  15. if (_previewFrameSource == null)
  16. {
  17. return CameraHelperResult.NoFrameSourceAvailable;
  18. }
  19. // get only formats of a certain framerate and compatible subtype for previewing, order them by resolution
  20. _frameFormatsAvailable = _previewFrameSource.SupportedFormats.Where(format =>
  21. format.FrameRate.Numerator / format.FrameRate.Denominator >= 15 // fps
  22. && (string.Compare(format.Subtype, MediaEncodingSubtypes.Nv12, true) == 0
  23. || string.Compare(format.Subtype, MediaEncodingSubtypes.Bgra8, true) == 0
  24. || string.Compare(format.Subtype, MediaEncodingSubtypes.Yuy2, true) == 0
  25. || string.Compare(format.Subtype, MediaEncodingSubtypes.Rgb32, true) == 0))?.OrderBy(format => format.VideoFormat.Width * format.VideoFormat.Height).ToList();
  26. if (_frameFormatsAvailable == null || !_frameFormatsAvailable.Any())
  27. {
  28. return CameraHelperResult.NoCompatibleFrameFormatAvailable;
  29. }
  30. // set the format with the higest resolution available by default
  31. var defaultFormat = _frameFormatsAvailable.Last();
  32. await _previewFrameSource.SetFormatAsync(defaultFormat);
  33. }
  34. catch (UnauthorizedAccessException)
  35. { ... }
  36. catch (Exception)
  37. { ... }
  38. return CameraHelperResult.Success;
  39. }

4. Reader_FrameArrived(sender, args)

获取到视频帧的处理,触发 FrameArrived 事件,传入 VideoFrame,开发者可以对 frame 做自己的处理。

  1. private void Reader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
  2. {
  3. // TryAcquireLatestFrame will return the latest frame that has not yet been acquired.
  4. // This can return null if there is no such frame, or if the reader is not in the
  5. // "Started" state. The latter can occur if a FrameArrived event was in flight
  6. // when the reader was stopped.
  7. var frame = sender.TryAcquireLatestFrame();
  8. if (frame != null)
  9. {
  10. var vmf = frame.VideoMediaFrame;
  11. EventHandler<FrameEventArgs> handler = FrameArrived;
  12. var frameArgs = new FrameEventArgs() { VideoFrame = vmf.GetVideoFrame() };
  13. handler?.Invoke(sender, frameArgs);
  14. }
  15. }

 

调用示例

  1. <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  3. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  4. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  5. xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
  6. mc:Ignorable="d">
  7.  
  8. <StackPanel Orientation="Vertical" Margin="20">
  9. <controls:CameraPreview x:Name="CameraPreviewControl">
  10. </controls:CameraPreview>
  11. <Image x:Name="CurrentFrameImage" MinWidth="300" Width="400" HorizontalAlignment="Left"></Image>
  12. </StackPanel>
  13. </Page>
  1. // Initialize the CameraPreview control and subscribe to the events
  2. CameraPreviewControl.PreviewFailed += CameraPreviewControl_PreviewFailed;
  3. await CameraPreviewControl.StartAsync();
  4. CameraPreviewControl.CameraHelper.FrameArrived += CameraPreviewControl_FrameArrived;
  5. // Create a software bitmap source and set it to the Xaml Image control source.
  6. var softwareBitmapSource = new SoftwareBitmapSource();
  7. CurrentFrameImage.Source = softwareBitmapSource;
  8. private void CameraPreviewControl_FrameArrived(object sender, FrameEventArgs e)
  9. {
  10. var videoFrame = e.VideoFrame;
  11. var softwareBitmap = e.VideoFrame.SoftwareBitmap;
  12. var targetSoftwareBitmap = softwareBitmap;
  13. if (softwareBitmap != null)
  14. {
  15. if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
  16. {
  17. targetSoftwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
  18. }
  19. await softwareBitmapSource.SetBitmapAsync(targetSoftwareBitmap);
  20. }
  21. }

 

总结

到这里我们就把 Windows Community Toolkit 3.0 中的 CameraPreview 的源代码实现过程讲解完成了,希望能对大家更好的理解和使用这个扩展有所帮助。

相信大家在做到很多跟摄像头有关的功能,比如人脸检测,视频直播的美颜处理,贴纸操作等操作时都会用到这个控件。如果大家有好玩的应用场景,欢迎多多交流,谢谢!

最后,再跟大家安利一下 WindowsCommunityToolkit 的官方微博:https://weibo.com/u/6506046490大家可以通过微博关注最新动态。

衷心感谢 WindowsCommunityToolkit 的作者们杰出的工作,感谢每一位贡献者,Thank you so much, ALL WindowsCommunityToolkit AUTHORS !!!

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号