剛剛嘗試下面的步驟
創建模板圖片: -首先,你需要爲葉創建蒙版圖像,你需要做的閾值,找到輪廓(最大),畫出輪廓(用實心)等...爲了消除邊緣效應,你需要侵蝕你的面具,這會產生更好的效果。
下面的代碼片段會做上述
Mat thr;
Mat src=imread("image2.png",1); //Your processed image
cvtColor(src,thr,CV_BGR2GRAY);
threshold(thr,thr,180,255,THRESH_BINARY_INV);
vector< vector <Point> > contours; // Vector for storing contour
vector<Vec4i> hierarchy;
int largest_contour_index=0;
int largest_area=0;
Mat mask(src.rows,src.cols,CV_8UC1,Scalar::all(0)); //create destination image
findContours(thr.clone(), contours, hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image
for(int i = 0; i< contours.size(); i++) // iterate through each contour.
{
double a=contourArea(contours[i],false); // Find the area of contour
if(a>largest_area){
largest_area=a;
largest_contour_index=i; //Store the index of largest contour
}
}
drawContours(mask,contours, largest_contour_index, Scalar(255,255,255),CV_FILLED, 8, hierarchy); // Draw the largest contour using previously stored index.
int dilation_size = 2;
Mat element = getStructuringElement(MORPH_RECT,
Size(2*dilation_size + 1, 2*dilation_size+1),
Point(dilation_size, dilation_size));
erode(mask, mask, element);
提取綠色區域: -這裏你應該用HSV色彩空間,INRANGE等。正如你的問題中提到的那樣。
Mat HSV,hsv_thr,dst;
cvtColor(src,HSV,CV_BGR2HSV);
inRange(HSV,Scalar(20,10,10),Scalar(90,255,255),hsv_thr);
以上圖片bitwise_not: -這裏你應該用上面創建的面具。
bitwise_not(hsv_thr, dst, mask);
繪製發病面積: - 再次在這裏,您需要做的找到輪廓畫出輪廓等...
findContours(dst.clone(), contours, hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); // Find the contours in the image
for(int i = 0; i< contours.size(); i++) // iterate through each contour.
drawContours(src,contours, i, Scalar(0,0,255),1, 8, hierarchy);
你可以通過適當的濾波,閾值提高結果使用適當的hsv範圍等等......另外上面的算法認爲你的背景總是白色的,對於其他背景你需要改變創建遮罩圖像的步驟。
希望這些有幫助...
這是我真正需要的。這確實是非常有用的。 我只想問一下,有沒有其他可用於感興趣區域(非綠色)區域的格式?我想要一個roi(不是二進制)的灰度或彩色圖像版本進行進一步處理。 – user3339658
在這裏使用這個答案[link](http://stackoverflow.com/questions/10176184/with-opencv-try-to-extract-a-region-of-a-picture-described-by-arrayofarrays#),I試圖讓輪廓內的區域(其中只有roi是可見的,其他人是黑色的),但我只能在圖像的第一輪廓內獲得該區域,而不是所有輪廓。你能給我一些關於如何獲得所有輪廓內容的指針嗎?非常感謝你提前。 :) – user3339658
只需使用[Mat :: copyTo()](http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-copyto)和輪廓作爲蒙版。 – Haris