opencv 中图像处理的一般流程——面向对象

图像处理算法opencv实现的通用框架,很实用,总结如下。


将要处理的图片当做参数传递给算法类,每个算法都定义一个类

算法类的定义

            1.必要的参数,参数的set,get函数;

            2.必要的辅助函数,尽量拆分开来,功能独立,短小;

            3. 输出图像作为成员变量,处理结果通过其返回

    

class GetColor
{
private:
    int minDist;     //最小距离
    cv::Vec3b target;//目标颜色
    cv::Mat result;  //返回结果
public:
    GetColor();
    void setColorDistanceThreshold(int distance);
    int getColorDistanceThreshold();
    int getDistance(const cv::Vec3b&color )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);
};
类实现:

重点是process函数的实现,依据所要用的算法来实现。

#include "getcolor.h"

GetColor::GetColor():minDist(100)
{
    target[0]=target[1]=target[2]=0;//初始化目标颜色;
}

//返回某一像素点处颜色与目标颜色的距离
int GetColor:: getDistance(const cv::Vec3b&color )const
{
    return abs(color[0]-target[0])+
           abs(color[1]-target[1])+
           abs(color[2]-target[2]);

}
//设置容忍距离
void GetColor::setColorDistanceThreshold(int distance)
{
    if(distance<0)
    {
        distance=0;
    }
    minDist=distance;
}

//得到距离
int GetColor::getColorDistanceThreshold()
{
    return minDist;
}

//设定目标颜色值三通道法。
void GetColor::setTargetColor( unsigned char red,unsigned char green,unsigned char blue)
{
   //opencv 默认是BGR
    target[2]=red;
    target[1]=green;
    target[0]=blue;
}
//重载设定目标颜色值向量法
void GetColor::setTargetColor(cv::Vec3b color)
{
    target =color;
}
//得到被检测的颜色
cv::Vec3b GetColor:: getTargetColor()const
{
    return target;
}

cv::Mat GetColor:: 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;
}


处理过程在主函数中完成,按照步骤来进行

简洁明了且不易出错。

   //步骤一1.创建要处理的对象Create Image processor object;
    GetColor cdetect;

    //步骤二2.读入图片Read input image
    cv::Mat image =imread("D:/Lena.jpg");
    if(!image.data)
        return 0;
    //步骤三3.设置输入参数 set input parameters

    cdetect.setTargetColor(221,190,230);
    cvNamedWindow("result");
    //步骤四4.处理图像显示结果
    imshow("result",cdetect.process(image));
    cv::waitKey();
     return 0;





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值