不规则ROI的提取
在网上看到基于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 }
作者:影醉阏轩窗
-------------------------------------------
个性签名:衣带渐宽终不悔,为伊消得人憔悴!
如果觉得这篇文章对你有小小的帮助的话,记得关注再下的公众号,同时在右下角点个“推荐”哦,博主在此感谢!