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)
1730정성태8/11/201422164개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
1729정성태8/11/201418223오류 유형: 236. SqlConnection - The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
1728정성태8/8/201430279.NET Framework: 453. C# - 오피스 파워포인트(Powerpoint) 파일을 WinForm에서 보는 방법파일 다운로드1
1727정성태8/6/201420509오류 유형: 235. SignalR 오류 메시지 - Counter 'Messages Bus Messages Published Total' does not exist in the specified Category. [2]
1726정성태8/6/201419397오류 유형: 234. IIS Express에서 COM+ 사용 시 SecurityException - "Requested registry access is not allowed" 발생
1725정성태8/6/201421348오류 유형: 233. Visual Studio 2013 Update3 적용 후 Microsoft.VisualStudio.Web.PageInspector.Runtime 모듈에 대한 FileNotFoundException 예외 발생
1724정성태8/5/201426102.NET Framework: 452. .NET System.Threading.Thread 개체에서 Native Thread Id를 구하는 방법 - 두 번째 이야기 [1]파일 다운로드1
1723정성태7/29/201458358개발 환경 구성: 233. DirectX 9 예제 프로젝트 빌드하는 방법 [3]파일 다운로드1
1722정성태7/25/201421055오류 유형: 232. IIS 500 Internal Server Error - NTFS 암호화된 폴더에 웹 애플리케이션이 위치한 경우
1721정성태7/24/201424063.NET Framework: 451. 함수형 프로그래밍 개념 - 리스트 해석(List Comprehension)과 순수 함수 [2]
1720정성태7/23/201422079개발 환경 구성: 232. C:\WINDOWS\system32\LogFiles\HTTPERR 폴더에 로그 파일을 남기지 않는 설정
1719정성태7/22/201426035Math: 13. 동전을 여러 더미로 나누는 경우의 수 세기(Partition Number) - 두 번째 이야기파일 다운로드1
1718정성태7/19/201435295Math: 12. HTML에서 수학 관련 기호/수식을 표현하기 위한 방법 - MathJax.js [4]
1716정성태7/17/201435005개발 환경 구성: 231. PC 용 무료 안드로이드 에뮬레이터 - genymotion
1715정성태7/13/201430603기타: 47. 운영체제 종료 후에도 USB 외장 하드의 전원이 꺼지지 않는 경우 [3]
1714정성태7/11/201420891VS.NET IDE: 92. Visual Studio 2013을 지원하는 IL Support 확장 도구
1713정성태7/11/201444604Windows: 98. 윈도우 시스템 디스크 용량 확보를 위한 "Package Cache" 폴더 이동 [1]
1712정성태7/10/201432860.NET Framework: 450. 영문 윈도우에서 C# 콘솔 프로그램의 유니코드 출력 방법 [3]
1711정성태7/10/201438050Windows: 97. cmd.exe 창에서 사용할 폰트를 추가하는 방법 [1]
1710정성태7/8/201430582개발 환경 구성: 230. 유니코드의 Surrogate Pair, Supplementary Characters가 뭘까요?파일 다운로드2
1709정성태7/8/201427381VS.NET IDE: 91. Visual Studio에서 32/64비트 IIS Express 실행하는 방법
1708정성태7/7/201424755VS.NET IDE: 90. Visual Studio - 사용자 정의 정적 분석 규칙 만드는 방법 [3]파일 다운로드1
1707정성태7/4/201423019.NET Framework: 449. C#에서 C++로 VARIANT 넘겨주는 방법파일 다운로드1
1706정성태7/3/201421427.NET Framework: 448. .NET SmartClient 컨트롤을 윈도우 8/2012에서 활성화하는 방법파일 다운로드1
1705정성태7/2/201435056VC++: 78. 보이어-무어(Boyer-Moore) 알고리즘이 정말 빠를까? [6]파일 다운로드1
1704정성태7/2/201421646.NET Framework: 447. w3wp.exe AppPool 재생(recycle)하는 방법 정리
... 121  122  123  124  125  126  127  128  129  130  131  132  [133]  134  135  ...