代码下载地址:http://download.csdn.net/detail/u010525655/6012575
注:由于VCE不能创建MFC工程,所以需要使用VS,另本人OpenCV目录为:D:\OpenCV,你们根据自己的目录更改include,lib等
当在一个程序中需要许多的算法时,那么最好将它们集中起来好控制。那么这时候就需要一个集中的控制器,以便于集中管理这些类。这就是管理器。在应用中起着一个重要的作用。
下面就让我们利用上一节的ColorDetecort类来说明Controller的使用。先创建一个界面程序,至于界面的创建,可以用QT也可以用MFC,由于我对于QT不熟悉,所以选择MFC。
控制器首先要创建类的对象和其它的一些成员变量,在本例中我们只有一个类,另外再添加两个变量,一个是输入图像,一个输出图像。
class ColorDetectController {
private:
// the algorithm class
ColorDetector *cdetect;
cv::Mat image; // The image to be processed
cv::Mat result; // The image result
public:
ColorDetectController() {
//setting up the application
cdetect= new ColorDetector();
}
下面就要写各个属性的set和get方法:
// Sets the color distance threshold
void setColorDistanceThreshold(int distance) {
cdetect->setColorDistanceThreshold(distance);
}
// Gets the color distance threshold
int getColorDistanceThreshold() const {
return cdetect->getColorDistanceThreshold();
}
// Sets the color to be detected
void setTargetColor(unsigned char red,
unsigned char green, unsigned char blue) {
cdetect->setTargetColor(red,green,blue);
}
// Gets the color to be detected
void getTargetColor(unsigned char &red,
unsigned char &green, unsigned char &blue) const {
cv::Vec3b color= cdetect->getTargetColor();
red= color[2];
green= color[1];
blue= color[0];
}
// Sets the input image. Reads it from file.
bool setInputImage(std::string filename) {
image= cv::imread(filename);
if (!image.data)
return false;
else
return true;
}
// Returns the current input image.
const cv::Mat getInputImage() const {
return image;
}
然后就是处理方法和返回最终值的方法:
/ Returns the image result from the latest processing.
const cv::Mat getLastResult() const {
return result;
}
最后,需要一个销毁方法,释放内存:
// Deletes processor objects created by thecontroller.
~ColorDetectController() {
delete cdetect;
}
使用Controller很容易为程序创建一个算法接口,使程序条理清晰。我们没有必要去知道类是怎么联系在一起的,或者应该执行哪个类的哪个方法。因为可以从控制器中获得这些信息,只要创建一个控制器实例,就可以使用。 控制器实际上是将用户的请求传达给适当的类,它自己充当一个简化的接口。例如拿setTargetColor和getTargetColor来说。使用uchar去赋值时,程序员就没有必要知道cv::Vec3b的任何信息也可以轻松赋值。
有时候Controller要保存输入的信息,我们的setInputImage就执行这个功能,当然程序中也应该加入一些异常捕捉。最终process方法执行了我们的算法,但是它不返回任何值,还要使用一个方法去获得最终的值。
先在CControllerTestDlg中添加一个ColorDetectController colordetect。下面就是处理按钮的动作:
oid CControllerTestDlg::OnBnClickedOpenImage()
{
CFileDialog dlg(
TRUE, _T("*.bmp"), NULL,
OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY,
_T("image files (*.bmp; *.jpg; *.jpeg) |*.bmp; *.jpg; *.jpeg | All Files (*.*) |*.*||"), NULL
);
dlg.m_ofn.lpstrTitle = _T("Open Image");
if( dlg.DoModal() != IDOK )
return;
// CString mPath = dlg.GetPathName();
std::string mPath = dlg.GetPathName();
// std::string path = mPath.GetBuffer();
colordetect.setInputImage(mPath);
cv::imshow("Input Image", colordetect.getInputImage());
// TODO: 在此添加控件通知处理程序代码
}
void CControllerTestDlg::OnBnClickedProcess()
{
// TODO: 在此添加控件通知处理程序代码
colordetect.setTargetColor(130,190,130);
colordetect.process();
cv::imshow("Output Result",colordetect.getLastResult());
}