質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
UWP

UWPは、Universal Windows Platformの略。様々なデバイス向けに提供されているアプリケーションを共通のフレームワーク上で動作可能にする仕組みで、Windows10で導入されました。

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Q&A

解決済

1回答

2080閲覧

UWP(C#)で動画に文字を埋め込みたい

Gallen

総合スコア6

UWP

UWPは、Universal Windows Platformの略。様々なデバイス向けに提供されているアプリケーションを共通のフレームワーク上で動作可能にする仕組みで、Windows10で導入されました。

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

0グッド

0クリップ

投稿2018/06/05 02:57

前提・実現したいこと

前提:
現在、UWP(C#)でカメラを使用したWindowsストアアプリの開発を行っています。
※カメラ制御には、MediaCaptureクラスを使用してます。

-MediaCapture を使った基本的な写真、ビデオ、およびオーディオのキャプチャ-
https://docs.microsoft.com/ja-jp/windows/uwp/audio-video-camera/basic-photo-video-and-audio-capture-with-mediacapture

実現したいこと:
Webカメラで撮影した動画に文字を埋め込んで、その動画を保存できるようにしたいです。

動画に文字を埋め込むにはフレーム単位の編集が必要だと思い、下記URLのドキュメントを参考に
フレーム単位で特殊効果を付与するランタイムコンポーネントを作成しました。

-カスタムのビデオ特殊効果-
https://docs.microsoft.com/ja-jp/windows/uwp/audio-video-camera/custom-video-effects

上記ドキュメントのサンプルでは、指定の値に基づいて各ビデオ フレームのピクセルを暗くしています。
※該当のソースコードにサンプルソースを記載しています。

ビデオ特殊効果用の Windows ランタイム コンポーネント 58~60行目当たりの
/* using (BitmapBuffer buffer = context.InputFrame.SoftwareBitmap.LockBuffer(BitmapBufferAccessMode.Read)) */
前にcontext.InputFrame.SoftwareBitmapに対して画像編集(文字埋め込み)を行おうと考えています。

色々と試してみましたが、解決することができませんでした。
解決する手段をご教示ください。
※ここに書いてある方法(フレーム単位の編集)以外でも何かあれば、ご教示いただけると幸いです。

該当のソースコード

C#

1//ビデオ特殊効果用の Windows ランタイム コンポーネント 2 3using System; 4using System.Collections.Generic; 5using System.Linq; 6using System.Text; 7using System.Threading.Tasks; 8using Windows.Media.Effects; 9using Windows.Media.MediaProperties; 10using Windows.Foundation.Collections; 11using Windows.Graphics.DirectX.Direct3D11; 12using Windows.Graphics.Imaging; 13using System.Runtime.InteropServices; 14using Windows.UI.Xaml.Media.Imaging; 15using Windows.Foundation; 16using Windows.UI.Xaml; 17using Windows.UI.Xaml.Controls; 18using Windows.UI; 19using Windows.UI.Core; 20 21namespace VideoEffectComponent 22{ 23 public sealed class ExampleVideoEffect : IBasicVideoEffect 24 { 25 26 public ExampleVideoEffect() 27 { 28 // Dispose of effect resources 29 } 30 31 private VideoEncodingProperties encodingProperties; 32 public void SetEncodingProperties(VideoEncodingProperties encodingProperties, IDirect3DDevice device) 33 { 34 this.encodingProperties = encodingProperties; 35 } 36 37 public double FadeValue 38 { 39 get 40 { 41 object val; 42 if (configuration != null && configuration.TryGetValue("FadeValue", out val)) 43 { 44 return (double)val; 45 } 46 return .5; 47 } 48 } 49 50 [ComImport] 51 [Guid("5B0D3235-4DBA-4D44-865E-8F1D0E4FD04D")] 52 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 53 private unsafe interface IMemoryBufferByteAccess 54 { 55 void GetBuffer(out byte* buffer, out uint capacity); 56 } 57 58 public unsafe void ProcessFrame(ProcessVideoFrameContext context) 59 { 60       61      //****************************************************** 62      // このメソッド内で、動画フレーム単位に文字を埋め込みたいです。 63      //****************************************************** 64        65 using (BitmapBuffer buffer = context.InputFrame.SoftwareBitmap.LockBuffer(BitmapBufferAccessMode.Read)) 66 using (BitmapBuffer targetBuffer = context.OutputFrame.SoftwareBitmap.LockBuffer(BitmapBufferAccessMode.Write)) 67 { 68 using (var reference = buffer.CreateReference()) 69 using (var targetReference = targetBuffer.CreateReference()) 70 { 71 byte* dataInBytes; 72 uint capacity; 73 ((IMemoryBufferByteAccess)reference).GetBuffer(out dataInBytes, out capacity); 74 75 byte* targetDataInBytes; 76 uint targetCapacity; 77 ((IMemoryBufferByteAccess)targetReference).GetBuffer(out targetDataInBytes, out targetCapacity); 78 79 var fadeValue = FadeValue; 80 81 // Fill-in the BGRA plane 82 BitmapPlaneDescription bufferLayout = buffer.GetPlaneDescription(0); 83 for (int i = 0; i < bufferLayout.Height; i++) 84 { 85 for (int j = 0; j < bufferLayout.Width; j++) 86 { 87 88 byte value = (byte)((float)j / bufferLayout.Width * 255); 89 90 int bytesPerPixel = 4; 91 if (encodingProperties.Subtype != "ARGB32") 92 { 93 // If you support other encodings, adjust index into the buffer accordingly 94 } 95 96 97 int idx = bufferLayout.StartIndex + bufferLayout.Stride * i + bytesPerPixel * j; 98 99 targetDataInBytes[idx + 0] = (byte)(fadeValue * (float)dataInBytes[idx + 0]); 100 targetDataInBytes[idx + 1] = (byte)(fadeValue * (float)dataInBytes[idx + 1]); 101 targetDataInBytes[idx + 2] = (byte)(fadeValue * (float)dataInBytes[idx + 2]); 102 targetDataInBytes[idx + 3] = dataInBytes[idx + 3]; 103 } 104 } 105 } 106 } 107 } 108 109 public void Close(MediaEffectClosedReason reason) 110 { 111 // Dispose of effect resources 112 } 113 114 private int frameCount; 115 public void DiscardQueuedFrames() 116 { 117 frameCount = 0; 118 } 119 120 public bool IsReadOnly { get { return false; } } 121 122 public IReadOnlyList<VideoEncodingProperties> SupportedEncodingProperties 123 { 124 get 125 { 126 var encodingProperties = new VideoEncodingProperties(); 127 encodingProperties.Subtype = "ARGB32"; 128 return new List<VideoEncodingProperties>() { encodingProperties }; 129 130 // If the list is empty, the encoding type will be ARGB32. 131 // return new List<VideoEncodingProperties>(); 132 } 133 } 134 135 public MediaMemoryTypes SupportedMemoryTypes { get { return MediaMemoryTypes.Cpu; } } 136 137 public bool TimeIndependent { get { return true; } } 138 139 private IPropertySet configuration; 140 public void SetProperties(IPropertySet configuration) 141 { 142 this.configuration = configuration; 143 } 144 } 145} 146

C#

1//ビデオ特殊効果用の Windows ランタイム コンポーネント 呼び出し部分 抜粋 2//MediaCapture初期化 3m_mediacapture = new MediaCapture(); 4var setting = new MediaCaptureInitializationSettings 5{ 6 StreamingCaptureMode = StreamingCaptureMode.AudioAndVideo, 7 VideoDeviceId = cameraInfo.Id 8}; 9 10//カメラのビデオ ストリームへのカスタム効果の追加 11var videoEffectDefinition = new VideoEffectDefinition("VideoEffectComponent.ExampleVideoEffect"); 12IMediaExtension videoEffect = await m_mediacapture.AddVideoEffectAsync(videoEffectDefinition, MediaStreamType.VideoPreview); 13videoEffect.SetProperties(new PropertySet() { { "FadeValue", .25 } }); 14 15Preview.Source = m_mediacapture; 16await m_mediacapture.StartPreviewAsync();

XAML

1<!--プレビュー部分抜粋--> 2<CaptureElement x:Name="Preview" Grid.Row="0" HorizontalAlignment="Center" Margin="0,0,0,0" VerticalAlignment="Center" />

試したこと

・Win2Dを使ってフレーム編集 → 内部例外:アプリケーションは、別のスレッドにマーシャリングされたインターフェイスを呼び出しました。 (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)))

・WriteableBitmapExを使ってフレーム編集 → 上記と同じ例外が出ました。

上記二つとも、各サンプル(Webで"画像に文字を描画する C# UWP"で調べた結果)を参考に実装しました。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

自己解決しました。

-カスタムのビデオ特殊効果-
https://docs.microsoft.com/ja-jp/windows/uwp/audio-video-camera/custom-video-effects

上記のドキュメントをよく見ると、Win2Dの使用例がありました。

ドキュメントを参考にして、Windowsランタイムコンポーネント内で
Win2D使用時のプロパティ、メソッドを実装した後、ProcessFrameメソッド内で、
以下の記述に書き換えました。

C#

1//ビデオ特殊効果用の Windows ランタイム コンポーネント 2using (CanvasBitmap inputBitmap =CanvasBitmap.CreateFromDirect3D11Surface(canvasDevice, context.InputFrame.Direct3DSurface)) 3using (CanvasRenderTarget renderTarget = CanvasRenderTarget.CreateFromDirect3D11Surface(canvasDevice, context.OutputFrame.Direct3DSurface)) 4using (CanvasDrawingSession ds = renderTarget.CreateDrawingSession()) 5{ 6 //こっから 7 var gaussianBlurEffect = new GaussianBlurEffect 8 { 9 Source = inputBitmap, 10 BlurAmount = (float)BlurAmount, //←ここは不要 11 Optimization = EffectOptimization.Quality 12 }; 13 //ここは、任意に書き換える。 14 15 //画像描画 16 ds.DrawImage(gaussianBlurEffect); 17 //文字描画 18 ds.DrawText("ここに文字を入れる。", new System.Numerics.Vector2(100, 100, Colors.Red); 19} 20

ドキュメントのサンプルをそのまま流用したので、BlurAmountプロパティ(ぼかし効果)を適用後、
文字を描画している形になります。※BlurAmountプロパティの値は、0にしています。

投稿2018/06/05 05:52

Gallen

総合スコア6

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問