在算法设计中使用策略模式

辛辛苦苦敲出来,觉得有用的留言啊;

//鉴别出图像中还有给定颜色的所有像素;容忍度之内白色,否则黑色

#include<opencv2\core\core.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<iostream>

using namespace std;
using namespace cv;


class ColorDetector
{
public:
	ColorDetector():minDist(100)
	{
		target[0]=target[1]=target[0]=0;
	};
	void setColorDistanceThreshold(int distance)
	{
		if(distance<0)
			distance=0;
		minDist=distance;
	};
	int getColorDistanceThreshold() const
	{
	return minDist;
	};
	void setTargetColor(unsigned char red,
	                    unsigned char green,
						unsigned char blue)
	{
		target[0]=blue;
		target[1]=green;
		target[2]=red;
	};
	void setTargetColor(cv::Vec3b color)
	{
		target=color;
	};
	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 process(const cv::Mat &image);//核心算法,在类外实现
private:
	int minDist;
	cv::Vec3b target;
	cv::Mat result;
};
cv::Mat ColorDetector::process(const cv::Mat &image)
{
	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;
		}
	}
	return result;
}
int main()
{
	ColorDetector cdetect;
	cv::Mat image=imread("d:/test/opencv/img.jpg");
	if(!image.data)
	{
		cout<<"picture read failure"<<endl;
		return 0;
	}
	cdetect.setTargetColor(130,190,230);
	cv::namedWindow("result");
	cv::imshow("result",cdetect.process(image));
	cv::waitKey();
	return 0;
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值