2
* @file Morphology_3(Extract_Lines).cpp
3
* @brief Use morphology transformations for extracting horizontal and vertical lines sample code
8
#include <opencv2/opencv.hpp>
13
int main(int, char** argv)
17
Mat src = imread(argv[1]);
19
// Check if image is loaded fine
21
cerr << "Problem loading image!!!" << endl;
28
// Transform source image to gray if it is not
31
if (src.channels() == 3)
33
cvtColor(src, gray, CV_BGR2GRAY);
45
// Apply adaptiveThreshold at the bitwise_not of gray, notice the ~ symbol
47
adaptiveThreshold(~gray, bw, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);
54
// Create the images that will use to extract the horizontal and vertical lines
55
Mat horizontal = bw.clone();
56
Mat vertical = bw.clone();
60
// Specify size on horizontal axis
61
int horizontalsize = horizontal.cols / 30;
63
// Create structure element for extracting horizontal lines through morphology operations
64
Mat horizontalStructure = getStructuringElement(MORPH_RECT, Size(horizontalsize,1));
66
// Apply morphology operations
67
erode(horizontal, horizontal, horizontalStructure, Point(-1, -1));
68
dilate(horizontal, horizontal, horizontalStructure, Point(-1, -1));
70
// Show extracted horizontal lines
71
imshow("horizontal", horizontal);
75
// Specify size on vertical axis
76
int verticalsize = vertical.rows / 30;
78
// Create structure element for extracting vertical lines through morphology operations
79
Mat verticalStructure = getStructuringElement(MORPH_RECT, Size( 1,verticalsize));
81
// Apply morphology operations
82
erode(vertical, vertical, verticalStructure, Point(-1, -1));
83
dilate(vertical, vertical, verticalStructure, Point(-1, -1));
85
// Show extracted vertical lines
86
imshow("vertical", vertical);
90
// Inverse vertical image
91
bitwise_not(vertical, vertical);
92
imshow("vertical_bit", vertical);
94
// Extract edges and smooth image according to the logic
97
// 3. src.copyTo(smooth)
99
// 5. smooth.copyTo(src, edges)
103
adaptiveThreshold(vertical, edges, 255, CV_ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 3, -2);
104
imshow("edges", edges);
107
Mat kernel = Mat::ones(2, 2, CV_8UC1);
108
dilate(edges, edges, kernel);
109
imshow("dilate", edges);
113
vertical.copyTo(smooth);
116
blur(smooth, smooth, Size(2, 2));
119
smooth.copyTo(vertical, edges);
122
imshow("smooth", vertical);
b'\\ No newline at end of file'