算法设计中的策略(strategy)模式

#include <QCoreApplication>
#include <opencv2/opencv.hpp>

class ColorDetector{
public:
    ColorDetector():minDist(100){
        target[0]=target[1] = target[2] = 0;
    }

    cv::Mat process(const cv::Mat &image);

    int getDistance(const cv::Vec3b& color)const{
        //街区距离
        return abs(color[0] - target[0])+
                abs(color[1] - target[1])+
                abs(color[2] - target[2]);
        //欧拉距离


       // return cv::sqrt(abs(color[0]*color[0] - target[0]*target[0]))+
               // cv::sqrt(abs(color[1]*color[1] - target[1]*target[1]))+
               // cv::sqrt(abs(color[2]*color[2] - target[2]*target[2]));


    }

    //设置色彩间阈值
    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[2] = red;
        target[1] = green;
        target[0] = blue;
    }

    //设置需要检测的颜色
    void setTargetColor(cv::Vec3b color){
        target = color;
    }

    // 获取需要监测的颜色
    cv::Vec3b getTargetColor() const{
        return target;
    }





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(int argc, char *argv[])
{
   // QCoreApplication a(argc, argv);
    //cv::Mat blueSky(600,800,CV_8UC3,cv::Scalar(230,190,130));
    //cv::imshow("sky",blueSky);
    ColorDetector cdetect;
    cv::Mat image = cv::imread("E:/image/opencv2/boldt.jpg");
    \
    if(!image.data){
        std::cout<<"no image been loaded"<<std::endl;
        return 0;
    }

    cdetect.setTargetColor(130,190,230);

   //cdetect.setColorDistanceThreshold(220);

    cv::imshow("result",cdetect.process(image));


    cv::waitKey();
    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值