在這個例子中,我們開始選定一種顏色,並設置一個阈值
然後把圖片中和所選顏色的差別在阈值中的點標定出來
在這個例子中,主要要注意這兩點:
1. OpenCV與QT的結合,包括Mat 與 QImage 的轉換
2. 我們使用了類來實現此功能,創建了一個單例模式的類
首先我們創建一個簡單的圖形界面,使用的是QT
創建處理圖像用的類
#ifndef COLORDETECTOR_H_
#define COLORDETECTOR_H_
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <string>
class ColorDetector{
private:
int minDist;
cv::Vec3b target;
cv::Mat result;
cv::Mat image;
ColorDetector();
static ColorDetector *singleton;
public:
static ColorDetector * getInstance();
static void destory();
void setColorDistanceThreshold(int);
int getColorDistanceThreshold() const;
void setTargetColor(unsigned char, unsigned char, unsigned char);
void setTargetColor(cv::Vec3b);
cv::Vec3b getTargetColor() const;
void process();
int getDistance(const cv::Vec3b&) const;
cv::Mat getResult() const;
bool setInputImage(std::string);
cv::Mat getInputImage() const;
};
#endif /* COLORDETECTOR_H_ */
將其構造函數聲明為private,提供靜態的接口來獲得ColorDetector對象
void setColorDistanceThreshold(int) 用於設置阈值
void setTargetColor(unsigned char, unsigned char, unsigned char)
void setTargetColor(cv::Vec3b) 用於設置顏色
bool setInputImage(std::string) 用於載入待處理圖像
cv::Mat getResult() const 用於返回處理結果,結果用一副圖像表示
其具體實現如下#include "ColorDetector.h"
ColorDetector* ColorDetector::singleton = 0;
ColorDetector::ColorDetector():minDist(100){
target[0] = target[1] = target[2] = 0;
}
ColorDetector* ColorDetector::getInstance(){
if(singleton == 0){
singleton = new ColorDetector;
}
return singleton;
}
void ColorDetector::destory(){
if(singleton!=0){
delete singleton;
}
singleton = 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]);
}
void ColorDetector::process(){
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;
}
}
}
cv::Mat ColorDetector::getResult() const{
return result;
}
bool ColorDetector::setInputImage(std::string filename){
image = cv::imread(filename);
if(!image.data){
return false;
}
return true;
}
cv::Mat ColorDetector::getInputImage() const{
return image;
}