OpenCV实现彩色图像轮廓 换背景颜色

转摘请注明:https://i.cnblogs.com/EditPosts.aspx?opt=1

有时候我们需要不一样颜色的证件照,下面就用OpenCV来实现证件照的蓝底、红底等换颜色;

代码如下:

 1 #include <opencv2/opencv.hpp>
 2 using namespace cv;
 3 int main()
 4 {
 5     Mat g_srcImage = imread("11.jpg");
 6     imshow("g_srcImage", g_srcImage);
 7     waitKey(0);
 8 
 9     vector<Mat> g_vChannels;
10     split(g_srcImage, g_vChannels);
11 
12     Mat imageBlueChannel = g_vChannels.at(0);
13     Mat imageGreenChannel = g_vChannels.at(1);
14     Mat imageRedChannel = g_vChannels.at(2);
15 
16 
17     Mat img_B = (2 * imageBlueChannel - imageGreenChannel - imageRedChannel);
18     imshow("img_B", img_B);
19     waitKey(0);
20 
21     threshold(img_B, img_B, 0, 255, CV_THRESH_OTSU);
22     imshow("img_B_g", img_B);
23     waitKey(0);
24 
25     //对每个轮廓进行分析
26     vector <Mat> contours;
27     vector <Vec4i> hierarchy;
28     double min_area = 50;//小于50的认为不是数字
29 
30     findContours(img_B, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
31 
32     // fill external contours
33     if (!contours.empty() && !hierarchy.empty())
34     {
35         for (int idx = 0; idx < contours.size(); idx++)
36         {
37             //Mat temp_img(Size(img_B.size()), CV_8U, Scalar(0));
38             drawContours(img_B, contours, idx, Scalar(255), CV_FILLED, 8);//填充 形成区域
39 
40             drawContours(g_srcImage, contours, idx, Scalar(255,255,255), CV_FILLED, 8);//填充 形成区域
41 
42             
43         }
44     }
45     imshow("g_srcImage11", g_srcImage);
46     waitKey(0);
47     imwrite("g_srcImage.bmp", g_srcImage);
48 
49 }

效果图:

 

posted on 2017-03-23 16:30  在某一天老去  阅读(2654)  评论(0编辑  收藏  举报

导航