第三章介绍在opencv中使用设计模式,首先讲的是把图像处理过程抽象为一个类(利用策略模式),其次讲了利用MFC介绍了设计模式中的MVC,最后介绍了颜色转换
下面是第一部分的例子,MFC的不太熟悉,就没做了,颜色转换就是cv::cvtColor(image,invertimage,CV_BGR2Lab);
#include "stdafx.h"
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
#include <highgui.h>
#include <cv.h>
using namespace std;
using namespace cv;
class ColorDetector
{
private:
int minDist;
Vec3b target;
Mat result;
public:
//void setColorDistanceThreshold(int distance)
//{
// if(distance<0)
// distance=0;
// minDist=distance;
//}
//int getColorDistanceThreshold() const
//{
// return minDist;
//}
void setTargetColor(unsigned char red,unsigned char green,unsigned char blue)
{
target[2]=red;
target[1]=green;
target[0]=blue;
}
//void setTargetColor(Vec3b color)
//{
// target=color;
//}
//
//Vec3b getTargetColor()const
//{
// return target;
//}
//
int getDistance(const Vec3b &color)
{
return abs(color[0]-target[0])+
abs(color[0]-target[0])+
abs(color[0]-target[0]);
}
Mat process(const Mat &image)
{
result.create(image.rows,image.cols,CV_8U);
Mat_<Vec3b>::const_iterator it= image.begin<Vec3b>();
Mat_<Vec3b>::const_iterator itend=image.end<Vec3b>();
Mat_<uchar>::iterator itout=result.begin<uchar>();
for(;it!=itend;++it,++itout)
{
if(getDistance(*it)<minDist)
{
*itout=255;
}
else
{
*itout=0;
}
}
return result;
}
ColorDetector() : minDist(200)
{
target[0]=target[1]=target[2]=0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ColorDetector cdetect;
Mat image=imread("lena.tiff");
Mat invertimage;
cv::cvtColor(image,invertimage,CV_BGR2GRAY);
namedWindow("lena");
imshow("lena",invertimage);
cdetect.setTargetColor(0,0,255);
namedWindow("result");
imshow("result",cdetect.process(image));
waitKey();
return 0;
}