辛辛苦苦敲出来,觉得有用的留言啊;
//鉴别出图像中还有给定颜色的所有像素;容忍度之内白色,否则黑色
#include<opencv2\core\core.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<iostream>
using namespace std;
using namespace cv;
class ColorDetector
{
public:
ColorDetector():minDist(100)
{
target[0]=target[1]=target[0]=0;
};
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[0]=blue;
target[1]=green;
target[2]=red;
};
void setTargetColor(cv::Vec3b color)
{
target=color;
};
cv::Vec3b getTargetColor() const
{
return target;
};
int getDistance(const cv::Vec3b& color) const
{
return abs(color[0]-target[0])+abs(color[1]-target[1])+abs(color[2]-target[2]);
};
cv::Mat process(const cv::Mat &image);//核心算法,在类外实现
private:
int minDist;
cv::Vec3b target;
cv::Mat result;
};
cv::Mat ColorDetector::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;
}
int main()
{
ColorDetector cdetect;
cv::Mat image=imread("d:/test/opencv/img.jpg");
if(!image.data)
{
cout<<"picture read failure"<<endl;
return 0;
}
cdetect.setTargetColor(130,190,230);
cv::namedWindow("result");
cv::imshow("result",cdetect.process(image));
cv::waitKey();
return 0;
}