2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[WPF]OpenCvSharpを使ってRenderTargetBitmapをプレビューする

Posted at

以前に、OpenCvSharp 4.5.2.20210404 を使って、Viewの外観をBitmap化する時などによく使うRenderTargetBitmapクラスのオブジェクトをプレビューするコードを考えましたので、Qiitaで共有したいと思います。

コード

コードは以下の通りです。


    static class OpenCvSharpHelper
    {
        [Conditional("DEBUG")]
        public static void ImShow(string windowTitle, RenderTargetBitmap rtb)
        {
            FormatConvertedBitmap newFormatedBitmapSource = new FormatConvertedBitmap();
            newFormatedBitmapSource.BeginInit();
            newFormatedBitmapSource.Source = rtb;
            newFormatedBitmapSource.DestinationFormat = PixelFormats.Bgr24;
            newFormatedBitmapSource.EndInit();

            var mat = OpenCvSharp.WpfExtensions.BitmapSourceConverter.ToMat(newFormatedBitmapSource);
            OpenCvSharp.Cv2.ImShow(windowTitle, mat);
        }
    }

工夫した点

RenderTargetBitmapはPixelFormats.Pbgra32しかサポートしていないので、OpenCvSharp.ImShow()のMatパラメータの要件であるBGR24で初期化できません。なので、RenderTargetBitmapはPbgra32で作って、その後、FormatConvertedBitmapによりBgr24に変換したビットマップをOpenCvSharp.Matに変換してImShow()しています。

Pbgra32(RenderTargetBitmap)→Bgr24(FormatConvertedBitmap)→Bgr24(Mat)

[Conditional("DEBUG")]は付けなくてもいいです。まあ、あまりRenderTargetBitmapをプレビューする機能をリリースビルドに含めることは少ないと思いますが、これは個人または組織の自由です。

私はこのコードを主にデバッグする時によく使います。

用例

Visualオブジェクトとwidthとheightがあればビットマップ化してウィンドウに表示できます。

        private void Render(Visual target, double width, double height)
        {
            var rtb = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32); //Pbgra32である必要がある!!!

            DrawingVisual visual = new DrawingVisual();
            using (DrawingContext context = visual.RenderOpen())
            {
                //ビットマップにFrameworkElementの外観をまるごと描写する例
                VisualBrush brush = new VisualBrush(target);
            context.DrawRectangle(brush, null, new Rect(new Point(), new Size(width, height)));
            }

            rtb.Render(visual);

            //testウィンドウにRenderTargetBitmapを表示する
            OpenCvSharpHelper.ImShow("test", rtb);
        }

ネタ元

このコードのネタ元はベクターグラフィックスドローイングツール "boiler's Graphics"です。
https://github.com/dhq-boiler/boiler-s-Graphics.git

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?