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;





發佈了52 篇原創文章 · 獲贊 18 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章