Windows dialog-based OpenCV program 윈도우 대화상자 OpenCV 프로그램 만들기
OpenCV 2019. 10. 26. 18:32 |반응형
Build a Windows dialog-based OpenCV program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include <Windows.h> #include <gdiplus.h> #include <opencv2/opencv.hpp> #include "resource.h" #pragma comment(lib, "gdiplus") using namespace cv; using namespace Gdiplus; INT_PTR MainDlgProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam); HWND hDlgMain; VideoCapture cap; Mat frame; RECT invalidateRect; |
Prepare necessities.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow) { ULONG_PTR gpToken; GdiplusStartupInput gpsi; if (GdiplusStartup(&gpToken, &gpsi, NULL) != Ok) { MessageBox(NULL, TEXT("GDI+ start-up error."), TEXT("GDI+ Error"), MB_OK); } DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), HWND_DESKTOP, MainDlgProc); GdiplusShutdown(gpToken); return 0; } |
Start GDI+ and create a modal dialog box from a dialog template resource.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | bool initCamera() { cap.open(0); if (cap.isOpened()) { invalidateRect = { 0, 0, cvRound(cap.get(CAP_PROP_FRAME_WIDTH)), cvRound(cap.get(CAP_PROP_FRAME_HEIGHT)) }; return true; } else { MessageBox(NULL, TEXT("Camera open failed."), TEXT("Camera Error"), MB_OK); return false; } } |
Initiate a camera and set the windows update region.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | void OnPaint(HDC hdc) { Graphics G(hdc); cap >> frame; if (frame.empty()) { TextOut(hdc, 300, 240, "No frame to show", 8); return; } if (IsDlgButtonChecked(hDlgMain, IDC_CHECK1) == BST_CHECKED) { cvtColor(frame, frame, COLOR_BGR2GRAY); Canny(frame, frame, 50, 100); cvtColor(frame, frame, COLOR_GRAY2BGRA); } else { cvtColor(frame, frame, COLOR_BGR2BGRA); } Bitmap bitmap(frame.size().width, frame.size().height, frame.step1(), PixelFormat32bppARGB, frame.data); G.DrawImage(&bitmap, 0, 0, bitmap.GetWidth(), bitmap.GetHeight()); } |
Process each frame and draw it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | INT_PTR MainDlgProc(HWND hDlg, UINT iMessage, WPARAM wParam, LPARAM lParam) { HDC hdc; PAINTSTRUCT ps; static HANDLE hTimer; switch (iMessage) { case WM_INITDIALOG: hDlgMain = hDlg; if (initCamera()) { hTimer = (HANDLE)SetTimer(hDlg, 1, 10, NULL); } else { hTimer = NULL; } return TRUE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: return TRUE; case IDCANCEL: if (hTimer != NULL) { KillTimer(hDlg, 1); } EndDialog(hDlg, IDCANCEL); return TRUE; } case WM_PAINT: hdc = BeginPaint(hDlg, &ps); OnPaint(hdc); EndPaint(hDlg, &ps); return TRUE; case WM_TIMER: InvalidateRect(hDlg, &invalidateRect, FALSE); return 0; } return FALSE; } |
Create a timer and define the necessary variables and handle window messages.
Run the program.
Check 'Canny Edge Detection'.
반응형