opencv再学习之路(九)---制作对焦图像

利用opencv 产生对焦效果

 1 //  制作对焦图像
 2   
 3 #include "stdafx.h"  
 4 #include <opencv2corecore.hpp>
 5 #include <opencv2imgprocimgproc.hpp>
 6 #include <opencv2highguihighgui.hpp>
 7 #include <iostream>
 8 #include <map>
 9 #include <string>
10 #include<stdio.h>
11 
12 using namespace std;
13 using namespace cv;
14 
15 
16 void main()
17 {
18 
19     Mat image = imread("horse_hw.jpg");
20 
21     Mat gray;
22     cvtColor( image, gray, CV_BGR2GRAY);
23 
24     Mat binary;
25     threshold( gray, binary, 120, 255, CV_THRESH_BINARY);
26 
27     vector<vector<Point>> contours;
28     Mat binary_copy;
29     binary.copyTo(binary_copy);
30     findContours( binary_copy, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);      //  CV_RETR_EXTERNAL 获取外轮廓 CV_CHAIN_APPROX_NONE 获取每个轮廓的像素
31 
32     // 遍历每一个轮廓,把多余的轮廓去掉
33     vector<vector<Point>>::iterator it = contours.begin();
34     while (it != contours.end())
35     {
36         if (it->size() < 500 || boundingRect(*it).width > image.cols)
37         {
38             it = contours.erase(it);
39         }
40         else
41             it++;
42     }
43 
44     // 通过绘制轮廓,制作掩码
45     Mat mask(image.size(), CV_8U, Scalar(0));
46     drawContours( mask, contours, -1, Scalar(255), CV_FILLED);
47 
48     Mat dst;
49 
50     // 对图像进行模糊处理
51     blur(image, dst, Size(9,9));
52 
53     // 对目标部分进行锐化处理
54     Mat horse;
55     image.copyTo(horse);
56     Mat kernel = (Mat_<float>(3,3) << 0,-1,0,-1,5,-1,0,-1,0);
57     filter2D( horse, horse, -1, kernel);
58 
59     // 合成画面,把锐化后的目标部分复制到dst对应的位置
60     horse.copyTo(dst, mask);
61 
62     // 显示结果(原图和结果图显示在一起)
63     const int width = image.cols;
64     const int height = image.rows;
65     Mat show_image(Size(width * 2,height), CV_8UC3);
66     // 将image拷贝到指定位置上
67     image.copyTo(show_image(Rect( 0, 0, width, height)));
68     // dst拷贝到指定位置上
69     image.copyTo(show_image(Rect(width, 0, width,height)));
70 
71     // 显示
72     imshow("show", show_image);
73 
74     waitKey(0);
75 }
原文地址:https://www.cnblogs.com/zhp218/p/8646215.html