不規則ROI的提取
轉自:http://www.cnblogs.com/wjy-lulu/p/6759974.html
在網上看到基於opencv3.0之前的API實現不規則ROI的提取,我自己試了一下發現opencv3.0不行,第一想法是我寫的有問題,最后發現是API的改版。原理很簡單。
目標:提取黑線作為ROI

原理:先濾波-->>灰度化-->>二值化-->>邊緣提取-->>尋找圖像輪廓-->>輪廓畫在一張空圖像-->>水漫填充圖像輪廓區域-->>兩個圖像與操作
灰度化:

二值化:

邊緣提取:

空白圖像畫輪廓:

水漫之后的圖像:

與操作之后圖像:

為了效果明顯,我畫邊界的時候用的是粗實線,而程序求解的是最大邊,所以看起來邊緣不是很理想,實際操作可以優化
程序:
1 #include<iostream>
2 #include <opencv2/opencv.hpp>
3 #include <math.h>
4 using namespace cv;
5 using namespace std;
6
7 int Threshold_Value = 50;
8 const int Threshold_Max_value = 255;
9 const int Threshold_type_value = 3;
10 double g_Area = 0;
11
12 RNG rng(12345);
13
14 Mat input_image, threshold_image, output_image, Middle_image;
15
16 void Threshold_Image_Bar(int, void *);
17
18 int main(int argc, char**argv)
19 {
20 input_image = imread("1.jpg");
21 if (input_image.data == NULL) {
22 return -1; cout << "can't open image.../";
23 }
24 imshow("Sourse Image", input_image);
25 blur(input_image, Middle_image, Size(3, 3), Point(-1, -1), 4);
26 imshow("Blur Image", Middle_image);
27 cvtColor(Middle_image, Middle_image, COLOR_RGB2GRAY);
28 imshow("Gray Image", Middle_image);
29 namedWindow("Threshold Image", 1);
30 createTrackbar("閾值調整", "Threshold Image", &Threshold_Value, 255, Threshold_Image_Bar);
31 Threshold_Image_Bar(0, 0);
32 waitKey(0);
33 return 0;
34 }
35
36 void Threshold_Image_Bar(int, void *)
37 {
38 threshold(Middle_image, threshold_image, 90, 255, 3);
39 Canny(threshold_image, threshold_image, Threshold_Value, Threshold_Value * 3);
40 imshow("Threshold Image", threshold_image);
41
42 vector<vector<Point>> contours;
43 vector<Vec4i> hireachy;
44 findContours(threshold_image, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(-1, -1));
45 char flag_count = 0;
46 Mat Show_threImage = Mat::zeros(threshold_image.size(), CV_8UC3);
47 RotatedRect MinRect;
48 for (size_t i = 0; i < contours.size(); i++)
49 {
50 const Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
51 drawContours(Show_threImage, contours, static_cast<int>(i), color, 2, 8, hireachy, 0, Point());
52 //----利用面積進行判斷是否為最大區域------//
53 double area = contourArea(contours[i]);
54 g_Area = g_Area > area ? g_Area : area;
55 flag_count = (area == g_Area) ? static_cast<int>(i) : flag_count;//記錄最大邊界
56 }
57 imshow("Draw_Image_Contours", Show_threImage);
58
59 Mat gray, Change_image = Mat::zeros(input_image.size(), input_image.type());
60 gray.create(input_image.size(), input_image.type());
61 drawContours(gray, contours, flag_count, Scalar(255, 255, 255), 2, 8, hireachy, 0, Point());
62 Rect s = boundingRect(contours[flag_count]);//為了找內部的一個種子點,自己隨便定義也可以
63 floodFill(gray, Point(s.x + s.width / 2, s.y + s.height / 2), Scalar(255, 255, 255));//黑色區域變成白色,遇到白色區域停止
64 imshow("123", gray);
65 bitwise_and(input_image, gray, gray);
66 imshow("wjy", gray);
67
68 }

