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; }
相关文章推荐
- 策略设计模式
- C语言和设计模式(策略模式)
- 2010/7/30 初学设计模式、责任链实现filter、面向接口编程、策略模式修改排序算法
- Java设计模式十: 策略模式(Strategy)
- 设计模式(13)-策略模式(Strategy)
- 从头认识设计模式-策略模式-05-引入设计原则:面向接口编程
- 设计模式-行为型- 策略模式(Strategy)
- 设计模式—策略模式
- java 设计模式 学习笔记(4) 策略模式
- 策略设计模式
- Java设计模式------策略模式
- 设计模式初体验---策略模式Strategy
- Android 中设计模式 ----策略模式
- Java设计模式透析--策略模式(一)
- 设计模式一:java设计模式之策略模式(一)
- 设计模式之策略模式
- 设计模式C++实现(2)——策略模式
- 设计模式12:策略模式
- 第一章:设计模式:策略模式(四)
- Android设计模式—策略模式