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]

... 121  122  123  124  125  126  127  128  129  130  131  [132]  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1789정성태10/22/201422496오류 유형: 253. 이벤트 로그 - The client-side extension could not remove user policy settings for '...'
1788정성태10/22/201424335VC++: 82. COM 프로그래밍에서 HRESULT 타입의 S_FALSE는 실패일까요? 성공일까요? [2]
1787정성태10/22/201432589오류 유형: 252. COM 개체 등록시 0x8002801C 오류가 발생한다면?
1786정성태10/22/201434070디버깅 기술: 65. 프로세스 비정상 종료 시 "Debug Diagnostic Tool"를 이용해 덤프를 남기는 방법 [3]파일 다운로드1
1785정성태10/22/201423151오류 유형: 251. 이벤트 로그 - Load control template file /_controltemplates/TaxonomyPicker.ascx failed [1]
1784정성태10/22/201430740.NET Framework: 472. C/C++과 C# 사이의 메모리 할당/해제 방법파일 다운로드1
1783정성태10/21/201424589VC++: 81. 프로그래밍에서 borrowing의 개념
1782정성태10/21/201421380오류 유형: 250. 이벤트 로그 - Application Server job failed for service instance Microsoft.Office.Server.Search.Administration.SearchServiceInstance
1781정성태10/21/201422108디버깅 기술: 64. new/delete의 짝이 맞는 경우에도 메모리 누수가 발생한다면?
1780정성태10/15/201425930오류 유형: 249. The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
1779정성태10/15/201421123오류 유형: 248. Active Directory에서 OU가 지워지지 않는 경우
1778정성태10/10/201419524오류 유형: 247. The Netlogon service could not create server share C:\Windows\SYSVOL\sysvol\[도메인명]\SCRIPTS.
1777정성태10/10/201422550오류 유형: 246. The processing of Group Policy failed. Windows attempted to read the file \\[도메인]\sysvol\[도메인]\Policies\{...GUID...}\gpt.ini
1776정성태10/10/201419611오류 유형: 245. 이벤트 로그 - Name resolution for the name _ldap._tcp.dc._msdcs.[도메인명]. timed out after none of the configured DNS servers responded.
1775정성태10/9/201420851오류 유형: 244. Visual Studio 디버깅 (2) - Unable to break execution. This process is not currently executing the type of code that you selected to debug.
1774정성태10/9/201427769개발 환경 구성: 246. IIS 작업자 프로세스의 20분 자동 재생(Recycle)을 끄는 방법
1773정성태10/8/201431051.NET Framework: 471. 웹 브라우저로 다운로드가 되는 파일을 왜 C# 코드로 하면 안되는 걸까요? [1]
1772정성태10/3/201419841.NET Framework: 470. C# 3.0의 기본 인자(default parameter)가 .NET 1.1/2.0에서도 실행될까? [3]
1771정성태10/2/201428955개발 환경 구성: 245. 실행된 프로세스(EXE)의 명령행 인자를 확인하고 싶다면 - Sysmon [4]
1770정성태10/2/201422814개발 환경 구성: 244. 매크로 정의를 이용해 파일 하나로 C++과 C#에서 공유하는 방법 [1]파일 다운로드1
1769정성태10/1/201425588개발 환경 구성: 243. Scala 개발 환경 구성(JVM, 닷넷) [1]
1768정성태10/1/201420364개발 환경 구성: 242. 배치 파일에서 Thread.Sleep 효과를 주는 방법 [5]
1767정성태10/1/201425750VS.NET IDE: 94. Visual Studio 2012/2013에서의 매크로 구현 - Visual Commander [2]
1766정성태10/1/201423879개발 환경 구성: 241. 책 "프로그래밍 클로저: Lisp"을 읽고 나서. [1]
1765정성태9/30/201427562.NET Framework: 469. Unity3d에서 transform을 변수에 할당해 사용하는 특별한 이유가 있을까요?
1764정성태9/30/201423759오류 유형: 243. 파일 삭제가 안 되는 경우 - The action can't be comleted because the file is open in System
... 121  122  123  124  125  126  127  128  129  130  131  [132]  133  134  135  ...