图像处理算法opencv实现的通用框架,很实用,总结如下。
将要处理的图片当做参数传递给算法类,每个算法都定义一个类
算法类的定义
1.必要的参数,参数的set,get函数;
2.必要的辅助函数,尽量拆分开来,功能独立,短小;
3. 输出图像作为成员变量,处理结果通过其返回
class GetColor
{
private:
int minDist; //最小距离
cv::Vec3b target;//目标颜色
cv::Mat result; //返回结果
public:
GetColor();
void setColorDistanceThreshold(int distance);
int getColorDistanceThreshold();
int getDistance(const cv::Vec3b&color )const;
void setTargetColor( unsigned char red,unsigned char green,unsigned char blue);
void setTargetColor(cv::Vec3b color);
cv::Vec3b getTargetColor()const;
cv::Mat process(const cv::Mat &image);
};
类实现:
重点是process函数的实现,依据所要用的算法来实现。
#include "getcolor.h"
GetColor::GetColor():minDist(100)
{
target[0]=target[1]=target[2]=0;//初始化目标颜色;
}
//返回某一像素点处颜色与目标颜色的距离
int GetColor:: getDistance(const cv::Vec3b&color )const
{
return abs(color[0]-target[0])+
abs(color[1]-target[1])+
abs(color[2]-target[2]);
}
//设置容忍距离
void GetColor::setColorDistanceThreshold(int distance)
{
if(distance<0)
{
distance=0;
}
minDist=distance;
}
//得到距离
int GetColor::getColorDistanceThreshold()
{
return minDist;
}
//设定目标颜色值三通道法。
void GetColor::setTargetColor( unsigned char red,unsigned char green,unsigned char blue)
{
//opencv 默认是BGR
target[2]=red;
target[1]=green;
target[0]=blue;
}
//重载设定目标颜色值向量法
void GetColor::setTargetColor(cv::Vec3b color)
{
target =color;
}
//得到被检测的颜色
cv::Vec3b GetColor:: getTargetColor()const
{
return target;
}
cv::Mat GetColor:: process(const cv::Mat &image)
{
//尺寸和原始图像一样,分配空间通道按照实际需要分配,
result.create(image.rows,image.cols,CV_8U);
//定义迭代器
cv::Mat_<cv::Vec3b>::const_iterator it= image.begin<cv::Vec3b>();
cv::Mat_<cv::Vec3b>::const_iterator itend= image.end<cv::Vec3b>();
cv::Mat_<uchar>::iterator itout=result.begin<uchar>();
for(;it!=itend;++it,++itout)
{
if(getDistance(*it)<minDist)
{
*itout=255;
}
else
{
*itout=0;
}
}
return result;
}
简洁明了且不易出错。
//步骤一1.创建要处理的对象Create Image processor object;
GetColor cdetect;
//步骤二2.读入图片Read input image
cv::Mat image =imread("D:/Lena.jpg");
if(!image.data)
return 0;
//步骤三3.设置输入参数 set input parameters
cdetect.setTargetColor(221,190,230);
cvNamedWindow("result");
//步骤四4.处理图像显示结果
imshow("result",cdetect.process(image));
cv::waitKey();
return 0;