一个用OpenCV调用摄像头带界面的C++程序(wxWidgets+OpenCV )

 

 最近在学习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;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值