您的位置:首页 > 运维架构

opencv02-策略模式设计

2017-09-03 13:43 267 查看

opencv02-策略模式设计

先来看看我们的代码效果,输入一张图片:



我们算上图中的像素点与RGB(20, 220, 20)的距离,也就是与一个偏绿色像素点的距离。如果距离小于一定的值,就将这个像素值置为255,否则置为0。

则,我们得到的输出图片是:



想要实现上述效果实际并不难,我们这里打算用一种设计模式来实现这个过程。我们将一些算法封装在头文件里,比如计算距离,设置最小距离等等。而在类里就实现一个函数,用来遍历所有像素点,判断距离并且二值化。

下面是这个头文件的代码:

#ifndef COLORDETECT_H_
#define COLORDETECT_H_

#include<opencv2/core/core.hpp>
using namespace cv;

class ColorDetect{

private:
int minDist;

Vec3b target;

Mat result;

int getDistance(const Vec3b &color) const{
return abs(color[0] - target[0] + color[1] - target[1] + color[2] - target[2]);
}

public:

ColorDetect(){
minDist = 90;

target[2] = target[1] = target[0] = 0;
}

void setDistanceThreshold(int dis){
if (dis < 0){
dis = 0;
}

minDist = dis;
}

const int getDistanceThreshold(){
return minDist;
}

void setTargetColor(uchar R, uchar G, uchar B){
target[0] = B;
target[1] = G;
target[2] = R;
}

void setTargetColor(Vec3b t){
target = t;
}

const Vec3b getTargetColor(){
return target;
}

Mat process(Mat& img);
};

#endif


头文件里除了对私有变量的定义外,还实现了一些set,get以及构造函数。

cpp文件仅仅需要实现process函数即可。

#include"colordetect.h"

Mat ColorDetect::process(Mat& img){
result.create(img.size(), CV_8U);

for (int i = 0; i < img.rows; i++){
Vec3b* data = img.ptr<Vec3b>(i);

for (int j = 0; j < img.cols; j++){
if (getDistance( *(data+j) ) < minDist){
*(data + j) = Vec3b(255,255,255);
}
else{
*(data + j) = Vec3b(0, 0, 0);
}
}
}

return img;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opencv