书中代码如下:
//colordetector.h
#if !define COLORDETECT
#define COLORDETECT
#include <OpenCV245.h>
using namespace cv;
class ColorDetector
{
public:
ColorDetector()
{
minDist = 150;
target[0] = target[1] = target[2] = 0;
}
void setColorDistanceThreshold(int distance)
{
if (distance < 0)
{
distance = 0;
}
minDist = distance;
}
int getColorDistanceThreshold()
{
return minDist;
}
void setTargetColor(unsigned char red, unsigned char green, unsigned char blue)
{
target[2] = red;
target[1] = green;
target[0] = blue;
}
void setTargetColor(Vec3b color)
{
target = color;
}
const Vec3b getTargetColor()
{
return target;
}
Mat process(const Mat &image);
private:
int minDist;
Vec3b target;
Mat result;
int getDistance(const Vec3b &color) const
{
return abs(color[0] - target[0]) + abs(color[1] - target[1]) + abs(color[2] - target[2]);
}
};
#endif
//colordetector.cpp
#include "stdafx.h"
#include "colordetector.h"
Mat ColorDetector::process(const Mat &image)
{
result.create(image.rows, image.cols, CV_8U);
Mat_<Vec3b>::const_iterator it = image.begin<Vec3b>();
Mat_<Vec3b>::const_iterator itend = image.end<Vec3b>();
Mat_<uchar>::iterator itout = result.begin<uchar>();
for (; it != itend; ++it, ++itout)
{
if (getDistance(*it) < minDist)
{
*itout = 255;
}else
{
*itout = 0;
}
}
return result;
}
// a7.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "colordetector.h"
int _tmain(int argc, _TCHAR* argv[])
{
ColorDetector cdetect;
Mat image = imread("C:\\Users\\sony\\Desktop\\111.png");
if (!image.data)
{
return 0;
}
cdetect.setTargetColor(100, 150, 230);
namedWindow("result");
imshow("result", cdetect.process(image));
waitKey(0);
return 0;
}
在process中也可以这样:
int getDistance(const Vec3b &color) const
{
return static_cast<int>(norm<int, 3>(Vec3i(color[0] - target[0],
color[1] - target[1],
color[2] - color[2])));
}