#include <QCoreApplication>
#include <opencv2/opencv.hpp>
class ColorDetector{
public:
ColorDetector():minDist(100){
target[0]=target[1] = target[2] = 0;
}
cv::Mat process(const cv::Mat &image);
int getDistance(const cv::Vec3b& color)const{
//街区距离
return abs(color[0] - target[0])+
abs(color[1] - target[1])+
abs(color[2] - target[2]);
//欧拉距离
// return cv::sqrt(abs(color[0]*color[0] - target[0]*target[0]))+
// cv::sqrt(abs(color[1]*color[1] - target[1]*target[1]))+
// cv::sqrt(abs(color[2]*color[2] - target[2]*target[2]));
}
//设置色彩间阈值
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(cv::Vec3b color){
target = color;
}
// 获取需要监测的颜色
cv::Vec3b getTargetColor() const{
return target;
}
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(int argc, char *argv[])
{
// QCoreApplication a(argc, argv);
//cv::Mat blueSky(600,800,CV_8UC3,cv::Scalar(230,190,130));
//cv::imshow("sky",blueSky);
ColorDetector cdetect;
cv::Mat image = cv::imread("E:/image/opencv2/boldt.jpg");
\
if(!image.data){
std::cout<<"no image been loaded"<<std::endl;
return 0;
}
cdetect.setTargetColor(130,190,230);
//cdetect.setColorDistanceThreshold(220);
cv::imshow("result",cdetect.process(image));
cv::waitKey();
return 0;
}
算法设计中的策略(strategy)模式
最新推荐文章于 2022-09-28 21:45:03 发布