opencv02-策略模式设计

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值