ColorDetector类的定义
头文件:colordetector.h
<span style="font-size:14px;color:#009900;">#ifndef COLORDETECTOR
#define COLORDETECTOR
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
class ColorDetector{
private:
// 最小可接受距离
int minDist;
// 目标色
cv::Vec3b target;
// 结果图
cv::Mat result;
cv::Mat image;
public:
ColorDetector();//构造函数
void setColorDistanceThreshold(int);
int getColorDistanceThreshold() const;
void setTargetColor(unsigned char, unsigned char, unsigned char);
void setTargetColor(cv::Vec3b);
cv::Vec3b getTargetColor() const;
cv::Mat process(const cv::Mat &image);
int getDistance(const cv::Vec3b&) const;
};
#endif // COLORDETECTOR</span>
ColorDetector类的实现:
colordetector.cpp
#include "colordetector.h"
//用初始化列表初始化最小距离(默认值为100)
ColorDetector::ColorDetector():minDist(100){
target[0] = target[1] = target[2] = 0;
}
//设置最小距离
void ColorDetector::setColorDistanceThreshold(int distance){
if(distance < 0){
distance = 0;
}
minDist = distance;
}
//返回最小距离
int ColorDetector::getColorDistanceThreshold() const{
return minDist;
}
//设置需要检查的颜色(三通道版)
void ColorDetector::setTargetColor(unsigned char red,
unsigned char green, unsigned char blue){
target[2] = red;
target[1] = green;
target[0] = blue;
}
//设置需要检测的颜色(单通道版)
void ColorDetector::setTargetColor(cv::Vec3b color){
target = color;
}
//获取需要检测的颜色
cv::Vec3b ColorDetector::getTargetColor() const{
return target;
}
//计算与目标颜色的距离(三个通道)
int ColorDetector::getDistance(const cv::Vec3b& color) const{
return abs(color[0]-target[0])+abs(color[1]-target[1])+abs(color[2]-target[2]);
}
//处理每个像素
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;
}
main.cpp
<pre name="code" class="cpp"><span style="color:#009900;">#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include "colordetector.h"
</span>
<span style="color:#009900;">int main(){
ColorDetector cdetect;
cv::Mat image = cv::imread("D:\\software\\opencv2CV_shou_ce\\images\\boldt.jpg");
//设置最小距离
cdetect.setColorDistanceThreshold(100);
std::cout << cdetect.getColorDistanceThreshold() << std::endl;
if(!image.data)
return 0;
cdetect.setTargetColor(130,190,230); //该BGR对应的是蓝色
cv::namedWindow("result");
cv::imshow("result",cdetect.process(image));
cv::waitKey();
return 0;
}</span>
效果图