성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Roll A Lisp In C - Reading ; https...
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - OpenCvSharp을 이용한 Webcam 영상 처리 + Direct2D</h1> <p> OpenCV로 Webcam 영상 처리하는 것은 동영상 파일 처리 때와 거의 동일합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리 + Direct2D ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11404'>http://www.sysnet.pe.kr/2/0/11404</a> </pre> <br /> 그 소스 코드에서 바뀌는 거라고는 VideoCapture 생성자에 전달하는 인자가 동영상 파일이 아닌, PC에 장착된 카메라를 식별하는 번호라는 점입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > VideoCapture capture = new VideoCapture("c:\\temp\\test.avi"); ==> VideoCapture capture = new VideoCapture(0); </pre> <br /> 단지, 0번으로 다소 애매하게 지정한다는 것이 좀 아쉽다면 UWP 라이브러리를 이용해 비디오 장치를 열람해 이름을 알아내는 것도 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 데스크톱 윈도우 응용 프로그램에서 UWP 라이브러리를 이용한 비디오 장치 열람하는 방법 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11284'>http://www.sysnet.pe.kr/2/0/11284</a> </pre> <br /> 그런데 문제가 하나 있다면, Webcam의 FPS 수치를 알 길이 없다는 것입니다. 동영상 파일과는 달리 capture.Fps 값이 0으로 나오기 때문인데, 검색해 보면 다음과 같이 직접 capture.Read를 일정 수만큼 반복해 대략 측정하는 방법이 나옵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > How to find frame rate or frames per second (fps) in OpenCV ( Python / C++ ) ? ; <a target='tab' href='https://www.learnopencv.com/how-to-find-frame-rate-or-frames-per-second-fps-in-opencv-python-cpp/'>https://www.learnopencv.com/how-to-find-frame-rate-or-frames-per-second-fps-in-opencv-python-cpp/</a> </pre> <br /> 참고로 위의 덧글에 보면 OpenCV 3.2부터 webcam에도 FPS가 동작한다고 하는데 OpenCvSharp 현재 버전이 OpenCV 3.2를 기반으로 하고 있는데도 동작하지 않는 거 보면 그다지 신뢰가 가지 않습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 아래의 코드는 지난번 "<a target='tab' href='http://www.sysnet.pe.kr/2/0/11404'>C# - OpenCvSharp을 이용한 동영상(avi, mp4, ...) 처리 + Direct2D</a>" 글에서 VideoCapture(0)으로 바꾼 것과 함께 Direct2D Bitmap 하나에 2개의 Mat 영상을 함께 출력하는 변화를 포함합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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; Thread camera; BlockingCollection<SharpDX.Direct2D1.Bitmap> _q = new BlockingCollection<SharpDX.Direct2D1.Bitmap>(); DataStream _bitmapData; 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) => { this.Text = _q.Count.ToString(); renderer.DrawBitmap(item, 1.0f, BitmapInterpolationMode.Linear); }); item.Dispose(); } else { break; } } } private void CaptureCameraCallback() { VideoCapture capture = new VideoCapture(0); if (capture.IsOpened() == false) { return; } this.Invoke((Action)(() => { this.Width = capture.FrameWidth; this.Height = capture.FrameHeight * 2; _renderTarget.Initialize(this.Handle, capture.FrameWidth, capture.FrameHeight * 2); } )); _bitmapData = new DataStream(capture.FrameWidth * capture.FrameHeight * 4 * 2, false, false); int expectedProcessTimePerFrame = 1000 / 30; // 30 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; } using (Mat canny = image.Canny(50, 100)) { SharpDX.Direct2D1.Bitmap bitmap = ToSharpDXBitmap(image, canny); _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 org, Mat canny) { using (Mat orgData = org.CvtColor(ColorConversionCodes.BGR2BGRA)) using (Mat cannyData = canny.CvtColor(ColorConversionCodes.GRAY2RGBA)) { IntPtr dstPtr = _bitmapData.DataPointer; Utilities.CopyMemory(dstPtr, orgData.Data, (int)orgData.Total() * orgData.ElemSize()); dstPtr = IntPtr.Add(dstPtr, (int)orgData.Total() * orgData.ElemSize()); Utilities.CopyMemory(dstPtr, cannyData.Data, (int)cannyData.Total() * cannyData.ElemSize()); return _renderTarget.CreateBitmap(_bitmapData); } } private void Form1_Load(object sender, EventArgs e) { camera = new Thread(new ThreadStart(CaptureCameraCallback)); camera.IsBackground = true; camera.Start(); } } } </pre> <br /> 따라서 실행해 보면 다음과 같이 화면의 높이를 이등분해서 위에는 원본 이미지, 아래에는 Canny 이미지가 나옵니다. (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1200&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> <img alt='opencv_webcam_1.PNG' src='/SysWebRes/bbs/opencv_webcam_1.PNG' /><br /> <br /> <hr style='width: 50%' /><br /> <br /> 그러고 보니 webcam 관련해서 몇 번 다룬 적이 있군요. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# - AForge.NET을 이용한 웹캠 영상 출력 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11085'>http://www.sysnet.pe.kr/2/0/11085</a> Visual Studio 2013/2015 - Ceemple OpenCV 확장을 이용한 웹캠 영상 출력 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11094'>http://www.sysnet.pe.kr/2/0/11094</a> </pre> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
2033
(왼쪽의 숫자를 입력해야 합니다.)