/**
检测填空题中的直线: 采用形态学方式
*/
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat src,result;
int threshold_value=95;
int max_count=255;
void detectline(int,void*);
int main(){
string path = "/home/kaijun/Documents/resource/opencv/engline.jpg";
src = imread(path,IMREAD_COLOR);
imshow("src0",src);
detectline();
createTrackbar("threshold1","src",&threshold_value,max_count,detectline);
waitKey(0);
return 0;
}
void detectline(int ,void*){
// 将彩色图转成灰度图
Mat gray;
cvtColor(src,gray,COLOR_BGR2GRAY);
// 1. 将图像进行二值化处理
Mat binary;
threshold(gray,binary,0,255,THRESH_BINARY_INV|THRESH_OTSU);
imshow("binary",binary);
// 2. 形态学操作
Mat morph;
Mat kernel = getStructuringElement(MORPH_RECT, Size(20, 1));
morphologyEx(binary,morph,MORPH_OPEN,kernel);
imshow("morphology",morph);
// 3. 膨胀一下
Mat kernel2 = getStructuringElement(MORPH_RECT,Size(3,3));
dilate(morph,morph,kernel2);
imshow("morphology2",morph);
// 4. 寻找霍夫直线
vector<Vec4i> lines;
HoughLinesP(morph,lines,1,CV_PI/180,30,20,0);
for(int i=0; i < lines.size();i++){
Vec4i ln = lines[i];
line(src,Point(ln[0],ln[1]),Point(ln[2],ln[3]),Scalar(0,0,255),1);
}
imshow("src",src);
}