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>
效果圖