Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 10개 있습니다.)
.NET Framework: 707. OpenCV 응용 프로그램을 C#으로 구현 - OpenCvSharp
; https://www.sysnet.pe.kr/2/0/11402

.NET Framework: 708. C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리
; https://www.sysnet.pe.kr/2/0/11403

.NET Framework: 709. C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리 + Direct2D
; https://www.sysnet.pe.kr/2/0/11404

.NET Framework: 710. C# - OpenCvSharp을 이용한 Webcam 영상 처리 + Direct2D
; https://www.sysnet.pe.kr/2/0/11405

.NET Framework: 711. C# - OpenCvSharp의 Mat 데이터 조작 방법
; https://www.sysnet.pe.kr/2/0/11406

.NET Framework: 723. C# - OpenCvSharp 사용 시 C/C++을 이용한 속도 향상 (for 루프 연산)
; https://www.sysnet.pe.kr/2/0/11422

VC++: 123. 내가 만든 코드보다 OpenCV의 속도가 월등히 빠른 이유
; https://www.sysnet.pe.kr/2/0/11423

.NET Framework: 781. C# - OpenCvSharp 사용 시 포인터를 이용한 속도 향상
; https://www.sysnet.pe.kr/2/0/11567

개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
; https://www.sysnet.pe.kr/2/0/11971

Graphics: 38. C# - OpenCvSharp.VideoWriter에 BMP 파일을 1초씩 출력하는 예제
; https://www.sysnet.pe.kr/2/0/12485




C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리 + Direct2D

OpenCvSharp을 이용해 동영상 처리를 해봤는데,

C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리
; https://www.sysnet.pe.kr/2/0/11403

역시나 OpenCvSharp.Window을 이용해야 하는 점이 마음에 들지 않습니다. 결국 Graphics.DrawImage의 속도가 문제이니, 그렇다면 이것을 Direct2D의 힘을 빌려 처리하면 될 듯합니다.

C# - SharpDX + DXGI를 이용한 윈도우 화면 캡처 소스 코드 + Direct2D 출력
; https://www.sysnet.pe.kr/2/0/11401

이에 기반을 둬 "C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리" 글의 예제를 Direct2D를 이용한 처리로 바꿔보겠습니다. 우선 SharpDX를 참조하고,

Install-Package SharpDX.Direct2D1 -Version 4.0.1 
Install-Package SharpDX.Direct3D11 -Version 4.0.1

남은 작업은 OpenCV Mat 타입을 Direct2D가 렌더링할 SharpDX.Direct2D1.Bitmap 타입으로 변환하는 것입니다. 문제는 Direct2D1의 Bitmap이 PixelFormat으로 Alpha 값이 없는 24비트를 지원하지 않는다는 점에 있습니다. 이 때문에 (대부분의 동영상 파일의 형식인) Mat.8UC3 포맷인 경우 Direct2D1의 Bitmap으로 픽셀 단위로 읽어 복사를 해야 합니다. 예를 들어, 다음과 같은 식입니다.

private SharpDX.Direct2D1.Bitmap ToSharpDXBitmap(Mat image)
{
    IntPtr dstPtr = _dataStream.DataPointer;
    IntPtr srcPtr = image.Data;

    int srcPitch = image.Width * image.Channels(); // 동영상의 경우 대부분 Channels == 3 (Alpha 채널이 없음)

    for (int y = 0; y < _renderTarget.Height; y++)
    {
        for (int x = 0; x < _renderTarget.Width; x++)
        {
            IntPtr dstPixel = dstPtr + x * 4;
            IntPtr srcPixel = srcPtr + x * 3;

            Utilities.CopyMemory(dstPixel, srcPixel, 3);
        }

        srcPtr = IntPtr.Add(srcPtr, srcPitch);
        dstPtr = IntPtr.Add(dstPtr, _renderTarget.Width * 4);
    }

    return _renderTarget.CreateBitmap(_dataStream);
}

그래서 "C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리" 글의 예제에 위의 코드를 적용해 Direct2D로 출력하면 Graphics.DrawImage 호출에 있었던 20ms ~ 50ms 부하가 3ms 이하로 줄어듭니다. 따라서 동영상 재생에 끊김 현상도 발생하지 않습니다.




그런데 문제는 저렇게 Pixel 단위의 for 루프를 돌면서 처리하는 것에 대한 부하가 심하다는 것입니다. 실제로 위의 코드를 돌려 보면 1280 * 720 해상도에서 25% 정도의 CPU 부하가 발생합니다. 4 코어이기 때문에 이 정도면 CPU 100% 현상에 가깝습니다.

혹시나 싶어, 코드를 다음과 같이 OpenCV를 사용해 컬러 공간을 바꾸는 코드로 교체해봤습니다.

private SharpDX.Direct2D1.Bitmap ToSharpDXBitmap(Mat mat)
{
    using (Mat image = mat.CvtColor(ColorConversionCodes.BGR2BGRA))
    {
        DataPointer dataPointer = new DataPointer(image.Data, (int)image.Total() * image.ElemSize());
        return _renderTarget.CreateBitmap(dataPointer);
    }
}

그 결과 CPU 사용량이 5 ~ 10%로 뚝 떨어졌습니다. 빨라도 너무 빠릅니다. ^^ 처음엔 이것이 C# 언어의 부하라고 생각했는데 해당 코드를 C++ DLL로 교체해서 수행해도 마찬가지여서 적잖이 당황했습니다. 그러다 이에 대해 검색해 보니 다음과 같은 좋은 글이 나옵니다.

OpenCV - 속도 분석 (1)
; https://laonple.blog.me/220861902363

Intel의 최적화 코드가 그만큼 대단하다는 것입니다. 따라서, 앵간한 반복 코드는 직접 루프를 돌면서 만드는 것보다 가능한 OpenCV에서 제공하는 기능이 있다면 그것을 쓰는 것이 더 낫습니다.

다음은 이에 대한 최종 소스 코드로 첨부 파일에 완전한 csproj 파일로 포함되어 있습니다.

using OpenCvSharp;
using SharpDX;
using SharpDX.Direct2D1;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        RenderTarget2D _renderTarget;

        public Form1()
        {
            InitializeComponent();

            _renderTarget = new RenderTarget2D();
        }
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _renderTarget.Dispose();
            base.OnFormClosing(e);
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            while (true)
            {
                if (_q.TryTake(out SharpDX.Direct2D1.Bitmap item) == true)
                {
                    _renderTarget.Render(
                        (renderer) =>
                        {
                            renderer.DrawBitmap(item, 1.0f, BitmapInterpolationMode.Linear);
                        });
                    item.Dispose();
                }
                else
                {
                    break;
                }
            }
        }

        BlockingCollection<SharpDX.Direct2D1.Bitmap> _q = new BlockingCollection<SharpDX.Direct2D1.Bitmap>();

        private Thread camera;

        private void CaptureCameraCallback()
        {
            VideoCapture capture = new VideoCapture("c:\\temp\\test.avi");

            this.Invoke((Action)(() =>
                {
                this.Width = capture.FrameWidth;
                this.Height = capture.FrameHeight;
                _renderTarget.Initialize(this.Handle, capture.FrameWidth, capture.FrameHeight);
                }
            ));

            if (capture.IsOpened() == false)
            {
                return;
            }

            int fps = (int)capture.Fps;

            int expectedProcessTimePerFrame = 1000 / fps;
            Stopwatch st = new Stopwatch();
            st.Start();

            using (Mat image = new Mat())
            {
                while (true)
                {
                    long started = st.ElapsedMilliseconds;
                    capture.Read(image);

                    if (image.Empty() == true)
                    {
                        break;
                    }

                    SharpDX.Direct2D1.Bitmap bitmap = ToSharpDXBitmap(image);
                    _q.Add(bitmap);

                    try
                    {
                        this.Invoke((Action)(() => this.Invalidate()));
                    }
                    catch (ObjectDisposedException) { }
                    catch (InvalidOperationException) { }

                    int elapsed = (int)(st.ElapsedMilliseconds - started);
                    int delay = expectedProcessTimePerFrame - elapsed;

                    if (delay > 0)
                    {
                        Thread.Sleep(delay);
                    }
                }
            }
        }

        private SharpDX.Direct2D1.Bitmap ToSharpDXBitmap(Mat mat)
        {
            using (Mat image = mat.CvtColor(ColorConversionCodes.BGR2BGRA))
            {
                DataPointer dataPointer = new DataPointer(image.Data, (int)image.Total() * image.ElemSize());
                return _renderTarget.CreateBitmap(dataPointer);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            camera = new Thread(CaptureCameraCallback);
            camera.IsBackground = true;
            camera.Start();
        }
    }
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/26/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-07-02 01시13분
[윤태형] 안녕하세요
[guest]
2020-07-02 01시17분
[윤태형] 좋은 글 감사합니다.
혹시 저는 ffmpeg.autogen 을 사용해서 rtsp 영상을 수신하고 있는데.. ffmpeg 의 avframe 을 SharpDX.Direct2D1.Bitmap 으로 변환하는 방법이 있을까요?
아니면 avframe 을 opencv mat 으로 변환하는 방법.

아래는 avframe 을 opencv mat 으로 변환하는 c++ 코드를 c# 에서 사용하려고 작성한 코드인데.. 마지막 sws_scale 함수의 cvImage.Data 인자가 적용안되네요..

Mat cvImage = new Mat(height, width, MatType.CV_8UC3);
// Allocate the opencv mat and store its stride in a 1-element array
int[] cvLinesizes = new int[1];
cvLinesizes[0] = (int)cvImage.Step1();

// Convert the colour format and write directly to the opencv matrix
SwsContext* conversion = ffmpeg.sws_getContext(width, height, (AVPixelFormat)sourceFrame.format, width, height, AVPixelFormat.AV_PIX_FMT_BGR24, ffmpeg.SWS_FAST_BILINEAR, null, null, null);
//ffmpeg.sws_scale(conversion, targetFrame.data, targetFrame.linesize, 0, height, &cvImage.Data, cvLinesizes);

ffmpeg.sws_scale(conversion, sourceFrame.data, sourceFrame.linesize, 0, height, cvImage.Data, cvLinesizes);
ffmpeg.sws_freeContext(conversion);
[guest]
2020-07-02 02시41분
제가 ffmpeg 라이브러리는 한 번도 사용해 본 적이 없어서 딱히 정답을 제시할 수 없지만, 아무래도 sws_scale 함수를 잘못 사용한 듯합니다. cvImage.Data 인자 자리에 일반 버퍼를 넣어두고 sws_scale 후 확인을 해보시면 마찬가지 결과가 나올 듯한데 그 변환을 위한 인자를 제대로 넣었는지부터 확인할 필요가 있어 보입니다.
정성태
2020-07-03 10시13분
[윤태형] 네..
이 글을 참조해서 영상플레이어 변경했더니.. fhd 4개를 동시에 플레이도 버벅이던게 9개 동시에 가능해지네요 ^^
제가 여러가지 변경하면서 테스트 해보니.. 하나의 프로세스에서 여러개의 쓰레드로 동시(5개 이상) 플레이를 시키다 보니까 메모리 누수가 생기는거 같습니다.
정확한 위치는 모르겠지만 일부 수정하고 나니까 잘됩니다.

감사합니다.
[guest]
2021-04-12 06시13분
[guest] 좋은 글 감사합니다.
저는 RenderTarget2D 이게 없다고 뜨는데, 혹시 뭘 추가를 덜했을까요?
[guest]
2021-04-12 10시46분
첨부 파일을 빌드했는데 RenderTarget2D가 없다는 건가요?
정성태
2021-04-14 11시34분
[guest] 아! 예제에 보내 RenderTarget2D.cs 가 있네요 ^^;;

그냥 nuget에서 sharpdx 이거 항목만 추가해서 .. 저게 안나와서 뭔가 했네요. 감사합니다!
[guest]

... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11150정성태2/21/201719341.NET Framework: 645. Visual Studio Fakes 기능에서 Shim... 클래스가 생성되지 않는 경우 [5]
11149정성태2/21/201723033오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201721966.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201721204오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201719888오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201721345.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201724722.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201722101.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201730117.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201724398.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201720152.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201722853.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201721130VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
11137정성태1/20/201719831Windows: 135. AD에 참여한 컴퓨터로 RDP 연결 시 배경 화면을 못 바꾸는 정책
11136정성태1/20/201719017오류 유형: 375. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 - 두 번째 이야기
11135정성태1/20/201720007Windows: 134. Windows Server 2016의 작업 표시줄에 있는 시계가 사라졌다면? [1]
11134정성태1/20/201727418.NET Framework: 636. System.Threading.Timer를 이용해 타이머 작업을 할 때 유의할 점 [5]파일 다운로드1
11133정성태1/20/201723536.NET Framework: 635. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (2) - x86 환경의 __fastcall [1]파일 다운로드1
11132정성태1/19/201735039.NET Framework: 634. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (1) - x86 환경에서의 __cdecl, __stdcall에 대한 Name mangling [1]파일 다운로드1
11131정성태1/13/201723986.NET Framework: 633. C# - IL 코드 분석을 위한 팁 [2]
11130정성태1/11/201724485.NET Framework: 632. x86 실행 환경에서 SECURITY_ATTRIBUTES 구조체를 CreateEvent에 전달할 때 예외 발생파일 다운로드1
11129정성태1/11/201728871.NET Framework: 631. async/await에 대한 "There Is No Thread" 글의 부가 설명 [9]파일 다운로드1
11128정성태1/9/201723293.NET Framework: 630. C# - Interlocked.CompareExchange 사용 예제 [3]파일 다운로드1
11127정성태1/8/201722837기타: 63. (개발자를 위한) Visual Studio의 "with MSDN" 라이선스 설명
11126정성태1/7/201727571기타: 62. Edge 웹 브라우저의 즐겨찾기(Favorites)를 편집/백업/복원하는 방법 [1]파일 다운로드1
11125정성태1/7/201724413개발 환경 구성: 310. IIS - appcmd.exe를 이용해 특정 페이지에 클라이언트 측 인증서를 제출하도록 설정하는 방법
... 106  107  108  109  110  [111]  112  113  114  115  116  117  118  119  120  ...