1. 程式人生 > >opencv影象處理之輪廓外背景顏色改變

opencv影象處理之輪廓外背景顏色改變

自行學習弄得簡單程式碼,使用了影象中的輪廓發現以及提取,再繪製出來,改變輪廓外的畫素

首先,標頭檔案,寫的比較多,沒用的可以自己去除

#include <opencv2/core/core.hpp>  
#include<opencv2/highgui/highgui.hpp>  
#include"opencv2/imgproc/imgproc.hpp"  
#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>  

//名稱空間
using namespace
cv; using namespace std;
//圖片資料名字,原圖,灰度圖,二值圖,直方圖
Mat src,src_gray,dst,src_equ;
//宣告一個函式,建立滑動條
static void on_trackbar(int, void*);

主函式

int main(int argc, char** argv)
{
    //圖片讀入
    src = imread("D:\\PersonWork\\OpenCV\\program\\picture data\\0400.bmp");

    //判斷是否存在
    if (!src.data)
    {
        cout
<< "Image no find,error!" << endl; } //灰度轉換 cvtColor(src,src_gray, CV_BGR2GRAY); //原圖視窗,顯示 namedWindow("原圖", 0); imshow("原圖", src); //二值圖視窗 namedWindow("二值圖", 0); // 滑動條 int nThreshold = 120; createTrackbar("graybar", "二值圖", &nThreshold, 255,on_trackbar); on_trackbar(nThreshold, 0
); waitKey(0); destroyWindow("原圖"); destroyWindow("二值圖"); destroyWindow("result"); return 0; }

回撥函式

static void on_trackbar(int pos, void*)
{

    //二值化
    threshold(src_gray, dst, pos, 255, CV_THRESH_BINARY);
    imshow("二值圖", dst);

    //直方均勻化
    equalizeHist(dst, src_equ); 

    //識別輪廓
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(src_equ, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);        

    //輪廓數量,可沒有
    //int len=contours.size();
    //cout<<len<<endl;

    //將圖拷貝,進行遍歷圖片每個畫素
    Mat secImg = src_gray.clone();
    const int np =secImg.rows * secImg.channels();
    const int nr = secImg.rows;
    for(int j=0;j<nr;j++){
        uchar *sdata = secImg.ptr<uchar>(j);
        for(int i=0;i<np;i++){

            //判斷是否在輪廓上或者外面,如果在便將畫素變為255,即白色,因為這裡需要的是最外輪廓,所以為contours[0],如果還需要別的,contours[i],i 可以取其他值
            if (pointPolygonTest(contours[0],Point(i,j),false) != 1)
                sdata[i]=255;
             }      
        }
    }

    //result視窗以及顯示結果
    namedWindow("result",0);
    imshow("result",secImg);

}

輪廓數量

原圖

二值圖

result

如有不足,敬請諒解!