1. 步骤
- 原图加蒙版
- 转灰度图
- 二值检测
- 高斯模糊
- 边缘检测
- 霍夫直线检测
2. 实现
原图:
’
代码:
#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;
cv::Mat mask_of_image(cv::Mat image)
{
int height = image.rows;//1470, 1106
cv::Mat mask(image.size(), 0);
std::vector<cv::Point> polygons{{0, height}, {2200, height}, {250, 100}};
cv::fillPoly(mask, vector<std::vector<cv::Point>>{polygons}, (255,255,255));
cv::Mat mask_image;
cv::bitwise_and(image, image, mask_image, mask);
return mask_image;
}
int main() {
//读取图片
Mat img = imread("/Users/xialz/Downloads/2.png");
//添加蒙版
cv::Mat gray_img;
gray_img = mask_of_image(img);
//转灰度图
cvtColor(gray_img , gray_img , COLOR_BGR2GRAY);
//二值化
cv::Mat threshold_img;
cv::threshold(gray_img, threshold_img, 200, 255, cv::THRESH_BINARY);
//高斯模糊
cv::Mat gauss_img;
cv::GaussianBlur(threshold_img, gauss_img, Size(5,5), 3);
//边缘检测
cv::Mat canny_img;
cv::Canny(gauss_img, canny_img, 180, 255);
cv::imshow("canny_img", canny_img);
//霍夫直线检测
std::vector<cv::Vec4i> lines;
cv::HoughLinesP(canny_img, lines, 1., CV_PI / 180, 30);
//画线
for (int i = 0; i < lines.size(); ++i) {
cv::Vec4i line_ = lines[i];
cv::line(img, cv::Point(line_[0], line_[1]), cv::Point(line_[2], line_[3]), cv::Scalar(0, 255, 0), 2, LINE_AA);
}
cv::imshow("img", img);
waitKey(0);
return 0;
}
结果图:
=几点说明=
- 为何加蒙版
因为未加蒙版的情况下,会识别出上边的云,如下图:
- 关于霍夫检测函数
可参考链接:链接