当我们提取图像中的直线时,可以使用HoughLinesP函数,但单纯的使用此函数时往往得不到理想的效果,这是我们可以先通过形态学操作处理图像后再通过霍夫直线变换提取图像中的直线
直接通过HoughLinesP()
原图
处理后:
可见效果并不是很明显
形态学+HuoghLinesp
先通过二值变换-形态学开操作(定义kernel数组size(20,1)可以查找出图像中的横向直线)-霍夫直线变换得到结果
效果图:
由于拍摄角度的问题也不是特别理想,但是比上着还是有所提升
代码
# include<opencv2\opencv.hpp>
# include <iostream>
using namespace std;
using namespace cv;
Mat src, dst,roiImage;
const char* output_line = "Hough line";
void detectLine(int, void*);
void morphologLines(int, void*);
int max_count = 255;
int threshold_value = 100;
int main(int argc, char** argv) {
src = imread("E:/tuku/case4.jpg",IMREAD_GRAYSCALE);
if (src.empty()) {
cout << "can't find this picture...";
return -1;
}
imshow("input", src);
Rect roi = Rect(10, 10, src.cols - 20, src.rows - 20); //10,10表示左上角点的坐标
roiImage = src(roi);
imshow("roi Image", roiImage);
namedWindow(output_line, 1);
//createTrackbar("value:", output_line, &threshold_value, max_count, detectLine);
//detectLine(0, 0);
morphologLines(0, 0);
waitKey(0);
return 0;
}
void detectLine(int, void*) {
Canny(roiImage, dst, threshold_value, threshold_value * 2, 3, false);
//threshold(roiImage, dst, 0, 255, THRE | THRESH_OTSU);
vector<Vec4i>lines; //lines中有四个元素,恰好是直线的端点
HoughLinesP(dst, lines, 1, CV_PI / 180.0, 30, 30.0, 0);
Mat resultImage1 = roiImage.clone();
cvtColor(resultImage1, resultImage1, COLOR_GRAY2BGR);
for (size_t i = 0; i < lines.size(); i++) {
Vec4i ln = lines[i];
line(resultImage1, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(0, 0, 255), 2, 8, 0);
}
imshow(output_line, resultImage1);
}
void morphologLines(int, void*) {
//binary image
Mat binaryImage, morphologImage;
threshold(roiImage, binaryImage, threshold_value, max_count,THRESH_BINARY_INV);
threshold(roiImage, binaryImage, 0, 255,THRESH_BINARY_INV|THRESH_OTSU);
imshow("binaryImage", binaryImage);
//morpholog operation
//定义水平直线结构元素,开操作进行水平直线的提取
Mat kernel = getStructuringElement(MORPH_RECT, Size(20, 1), Point(-1, -1));
morphologyEx(binaryImage, morphologImage, MORPH_OPEN, kernel,Point(-1,-1));
imshow("morphologImage", morphologImage);
kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
dilate(morphologImage, morphologImage, kernel);
imshow("morphologImage lines", morphologImage);
//hough lines
vector<Vec4i>lines;
Mat resultImage= roiImage.clone();
HoughLinesP(morphologImage, lines, 1, CV_PI / 180.0, 30, 20.0, 0);//lines中有四个元素,恰好是直线的端点
cvtColor(resultImage, resultImage, COLOR_GRAY2BGR);
for (size_t t = 0; t < lines.size(); t++) {
Vec4i ln = lines[t];
line(resultImage, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(0, 0, 255), 1, 8, 0);
}
imshow("ResultImage", resultImage);
}