Strategy pattern in algorithm design

本文介绍了一个使用OpenCV实现的彩色检测算法,包括设置颜色距离阈值、目标颜色设定以及处理图像以检测特定颜色的过程。通过实例代码演示了如何在C++中应用此算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书中代码如下:

//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])));
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值