03.02 OpenCV代碼-圖像角點檢測

繼續分享OpenCV高級代碼實操系列。


OpenCV代碼-圖像角點檢測


/*

*

* 功能:通過灰度圖做簡單的圖像分割,再使用findContours去掉多餘的輪廓

*

*/

#include <vector>

#include <opencv2>

#include <opencv2>

#include <opencv2>

int main(int argc,char* argv[]){

//--1.讀入圖片

cv::Mat image = cv::imread("horse_hw.jpg");

//--2.轉換灰度圖

cv::Mat gray;

cv::cvtColor(image,gray,CV_RGB2GRAY);

//--3.二值化灰度圖

cv::Mat binary;

cv::threshold(gray,binary,60,255,cv::THRESH_BINARY_INV);

//平滑處理(平滑/高斯平滑兩種)

//cv::blur(dst,dst,cv::Size(3,3));

//cv::GaussianBlur(dst,dst,cv::Size(3,3),0,0); //高斯平滑

//形態學操作(此處效果不好,只用來展示加強理解)

//cv::erode(dst,dst,cv::Mat(),cv::Point(-1,-1),1);

//cv::dilate(dst,dst,cv::Mat(),cv::Point(-1,-1),1);

//--4.尋找輪廓

std::vector<:vector> > contours;

cv::Mat binary_copy; //因為findcontours函數會改變輸入的圖像,所以複製一個圖像作為函數的輸入

binary.copyTo(binary_copy);

cv::findContours(binary_copy,contours,CV_RETR_EXTERNAL/*獲取外輪廓*/,CV_CHAIN_APPROX_NONE/*獲取每個輪廓的每個像素*/);

//遍歷每一個輪廓,把多餘的輪廓去掉

std::vector<:vector> >::const_iterator it=contours.begin();

while(it!=contours.end()){

if(it->size()<500)

it = contours.erase(it);

else

++it;

}

//重新繪製輪廓

cv::Mat dst(image.size(),CV_8U,cv::Scalar(0));

cv::drawContours(dst,contours,-1/*繪製所有輪廓*/,cv::Scalar(255)/*繪製為白色*/,CV_FILLED/*輪廓全部填充*/);

//--4.顯示結果(原圖和結果圖顯示在一起)

const int width = image.cols;

const int height = image.rows;

cv::Mat show_image(cv::Size(3*width,height),CV_8UC3);

//將image拷貝到顯示圖片指定位置

image.copyTo(show_image(cv::Rect(0,0,width,height)));

//將binary,dst轉換為3通道,使得show_image和dst通道數一致,或者使用convertTo()函數做操作

cv::cvtColor(binary,binary,CV_GRAY2RGB);

cv::cvtColor(dst,dst,CV_GRAY2RGB);

//將binary,dst拷貝image指定位置

binary.copyTo(show_image(cv::Rect(width,0,width,height)));

dst.copyTo(show_image(cv::Rect(2*width,0,width,height)));

//顯示

cv::imshow("show",show_image);

cv::waitKey(0);

}

注:喜歡請留言。


分享到:


相關文章: