本文實(shí)例為大家分享了Opencv輪廓外背景顏色改變的具體代碼,供大家參考,具體內(nèi)容如下
自行學(xué)習(xí)弄得簡(jiǎn)單代碼,使用了圖像中的輪廓發(fā)現(xiàn)以及提取,再繪制出來(lái),改變輪廓外的像素
首先,頭文件,寫的比較多,沒(méi)用的可以自己去除
#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;
//圖片數(shù)據(jù)名字,原圖,灰度圖,二值圖,直方圖Mat src,src_gray,dst,src_equ;//聲明一個(gè)函數(shù),建立滑動(dòng)條static void on_trackbar(int, void*);
主函數(shù)
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; } //灰度轉(zhuǎn)換 cvtColor(src,src_gray, CV_BGR2GRAY); //原圖窗口,顯示 namedWindow("原圖", 0); imshow("原圖", src); //二值圖窗口 namedWindow("二值圖", 0); // 滑動(dòng)條 int nThreshold = 120; createTrackbar("graybar", "二值圖", &nThreshold, 255,on_trackbar); on_trackbar(nThreshold, 0); waitKey(0); destroyWindow("原圖"); destroyWindow("二值圖"); destroyWindow("result"); return 0;}回調(diào)函數(shù)
static void on_trackbar(int pos, void*){ //二值化 threshold(src_gray, dst, pos, 255, CV_THRESH_BINARY); imshow("二值圖", dst); //直方均勻化 equalizeHist(dst, src_equ); //識(shí)別輪廓 vector<vector<Point>> contours; vector<Vec4i> hierarchy; findContours(src_equ, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE); //輪廓數(shù)量,可沒(méi)有 //int len=contours.size(); //cout<<len<<endl; //將圖拷貝,進(jìn)行遍歷圖片每個(gè)像素 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++){ //判斷是否在輪廓上或者外面,如果在便將像素變?yōu)?55,即白色,因?yàn)檫@里需要的是最外輪廓,所以為contours[0],如果還需要?jiǎng)e的,contours[i],i 可以取其他值 if (pointPolygonTest(contours[0],Point(i,j),false) != 1) sdata[i]=255; } } } //result窗口以及顯示結(jié)果 namedWindow("result",0); imshow("result",secImg);}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選