Using the Strategy pattern in algorithm design

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

class ColorDetector {
	private:
		// minimum acceptable distance
		int minDist;
		// target color
		cv::Vec3b target;
		// image containing resulting binary map
		cv::Mat result;

	public:
		// empty constructor
		ColorDetector() : minDist(100) {
			// default parameter initialization here
			target[0]= target[1]= target[2]= 0;
		}
		
		// Sets the color distance threshold.
		// Threshold must be positive,
		// otherwise distance threshold is set to 0.
		void setColorDistanceThreshold(int distance) {
			if (distance<0)
				distance=0;
			minDist= distance;
		}
		// Get the color distance threshold
		int getColorDistanceThreshold() const {
			return minDist;
		}

		// Sets the color to be detected
		void setTargetColor(unsigned char red,
							unsigned char green,
							unsigned char blue) {
			// BGR order
			target[2]= red;
			target[1]= green;
			target[0]= blue;
		}

		// Sets the color to be detected
		void setTargetColor(cv::Vec3b color) {
			target= color;
		}

		// Gets the color to be detected
		cv::Vec3b getTargetColor() const {
			return target;
		}

		int 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) {
			// re-allocate binary map if necessary
			// same size as input image, but 1-channel
			result.create(image.rows,image.cols,CV_8U);

			// get the iterators
			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 each pixel
			for ( ; it!= itend; ++it, ++itout) {
				// process each pixel -----------------------
				// compute distance from target color
				if (getDistance(*it)<minDist) {
					*itout= 255;
				} else {
					*itout= 0;
				}
				// end of pixel processiong -----------------
			}
			return result;
		}
};

int main() 
{
	// 1. Create image processor object
	ColorDetector cdetect; 
	// 2. Read input image
	cv::Mat image=cv::imread("G:\\opencv\\images\\boldt.jpg");
	if (!image.data)
		return 0;
	// 3. Set input parameters
	cdetect.setTargetColor(130,190,230);//here blue sky
	cv::namedWindow("result");
	// 4. Process the image and display the result
	cv::imshow("result",cdetect.process(image));
	cv::waitKey();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值