最近在学习C++ 和wxWidgets,摸索了下做了一个小程序。
#include<wx/wx.h>
#include<opencv2/opencv.hpp>
#include<thread>
using namespace cv;
class MyFrame :public wxFrame
{
public:
MyFrame(const wxString&title);
~MyFrame();
private:
void OnCommand(wxCommandEvent& pEvent);
wxImage *Ipl2WxImage(const _IplImage *pImage);
void showImage();
DECLARE_EVENT_TABLE();
wxPanel *imageBox;
wxButton *but;
bool flag = false;
VideoCapture capture;
};
class MyAPP :public wxApp
{
virtual bool OnInit();
};
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_BUTTON(wxID_OPEN,MyFrame::OnCommand)
END_EVENT_TABLE()
MyFrame::MyFrame(const wxString& title)
:wxFrame(NULL, wxID_ANY, title)
{
SetSize(800, 600);
Center();
wxPanel *panel = new wxPanel(this, wxID_ANY);
imageBox = new wxPanel(panel, wxID_ANY, wxPoint(0, 0), wxSize(600, 600));
imageBox->SetBackgroundColour(*wxBLACK);
but = new wxButton(panel, wxID_OPEN, wxT("打开相机"), wxPoint(650, 100), wxSize(100, 50));
capture = VideoCapture(0);
std::thread t(&MyFrame::showImage, this);
t.detach();
}
bool MyAPP::OnInit()
{
wxInitAllImageHandlers();
MyFrame *frame = new MyFrame("MyApp");
frame->Show();
return true;
}
IMPLEMENT_APP(MyAPP);
MyFrame::~MyFrame()
{
capture.release();
}
void MyFrame::showImage()
{
while (1)
{
if (flag==1) //关闭的时候flag会变成其他数..
{
Mat frame;
capture >> frame;
wxClientDC dc(imageBox);
IplImage *img = (IplImage*)&IplImage(frame);
wxImage *wxImg = Ipl2WxImage(img);
wxBitmap bitmap = wxBitmap(*wxImg);
dc.DrawBitmap(bitmap, wxPoint(0, 0));
}
else
{
std::this_thread::sleep_for(std::chrono::microseconds(30));
}
}
}
void MyFrame::OnCommand(wxCommandEvent & pEvent)
{
flag = !flag;
if (flag)
{
but->SetLabel("pause");
}
else
{
but->SetLabel("continue");
}
}
wxImage * MyFrame::Ipl2WxImage(const _IplImage * pImage)
{
wxImage* retImg = new wxImage();
int width = pImage->width;
int height = pImage->height;
retImg->Create(width, height);
if (pImage->nChannels == 3)
{
unsigned char* data = (unsigned char*)malloc(width*height * 3);
int lTargetPitch = width * 3;
for (int y0 = 0; y0 < height; ++y0)
{
uchar* source = cvPtr2D(pImage, y0, 0);
unsigned char* target = data + y0 * lTargetPitch;
for (int x0 = width; x0 > 0; --x0)
{
target[0] = source[2];
target[1] = source[1];
target[2] = source[0];
target += 3;
source += 3;
}
}
retImg->SetData(data);
return retImg;
}
return NULL;
}