鉴别图像中含有给定颜色的所有像素

#include<opencv2/opencv.hpp>
using namespace cv;

class ColorDetector{
private:
    //最小可接受的距离
    int minDist;
    //目标颜色
    cv::Vec3b target;
    //结果图像
    cv::Mat result;
    int getDistance(cv::Vec3b color)
    {
        return abs(color[0]-target[0])+
                abs(color[1]-target[1])+
                abs(color[2]-target[2]);
    }
public:
    ColorDetector():minDist(100){
        //初始化默认参数
        target[0]=target[1]=target[2]=0;
    }
    void setColorDistanceThreshold(int distance);
    int getColorDistanceThreshold() const;
    void setTargetColor(unsigned char red,
                        unsigned char green,
                        unsigned char blue);
    void setTargetColor(cv::Vec3b color);
    cv::Vec3b getTargetColor() const;

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


};
void ColorDetector::setColorDistanceThreshold(int distance){
    if(distance<0)
        distance=0;
    minDist=distance;
}
int ColorDetector::getColorDistanceThreshold()const
{
    return minDist;
}
void ColorDetector::setTargetColor(unsigned char red,
                                   unsigned char green,
                                   unsigned char blue){
    //BGR顺序
    target[2]=red;
    target[1]=green;
    target[0]=blue;
}

void ColorDetector::setTargetColor(cv::Vec3b color)
{
    target=color;
}
cv::Vec3b ColorDetector::getTargetColor() const{
    return target;
}
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()
{
    //1创建图像处理的对象
    ColorDetector cdetect;
    //2读取输入图像
    cv::Mat image=cv::imread("C:/Users/samsung/Desktop/3241_Code/3241OS_images/images/boldt.jpg",1);
    if(!image.data)
        return 0;
    //设置输入参数
    cdetect.setTargetColor(130,190,230);
    cv::namedWindow("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、付费专栏及课程。

余额充值