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]

... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11379정성태11/30/201718971오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720454.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719664.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724018VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201718878오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201723901사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201722926오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201725944사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719630오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719489오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721620사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727235.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727256개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201718906오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721157오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201722979사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723025사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719561오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722398오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722159오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721652오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726353사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201726788개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
11356정성태11/15/201728430사물인터넷: 8. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 [4]
11355정성태11/15/201724327사물인터넷: 7. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 [2]파일 다운로드2
11354정성태11/14/201728532사물인터넷: 6. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드로 쓰는 방법 [8]
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...