(三)OpenCV图像处理
直接
- 直接用霍夫直线检测,效果差;
- 通过图像形态学操作来寻找直线,霍夫获取位置信息与显示。
#include <opencv2/opencv.hpp>#include <iostream>using namespace std;using namespace cv;Mat src,temp_ROI,dst;int threshold_value = 128;void DetectLine(int,void*);//Hough直线检测函数void MorphShapes_Hough(int, void*);//形态学+Hough直线检测int main(int argc, char** argv){src = imread("../path.jpg",
- 直接用霍夫直线检测,效果差;
- 通过图像形态学操作来寻找直线,霍夫获取位置信息与显示。
#include <opencv2/opencv.hpp>#include <iostream>using namespace std;using namespace cv;Mat src,temp_ROI,dst;int threshold_value = 128;void DetectLine(int,void*);//Hough直线检测函数void MorphShapes_Hough(int, void*);//形态学+Hough直线检测int main(int argc, char** argv){src = imread("../path.jpg", IMREAD_GRAYSCALE);if (src.empty()){cout << "could not load image1..." << endl;return -1;}namedWindow("src", WINDOW_AUTOSIZE);imshow("src", src);Rect ROI = Rect(5, 5, src.cols - 5, src.rows -5);//感兴趣区域//去掉边缘temp_ROI = src(ROI);//把src的ROI区域给temp_ROI//namedWindow("ROI_dst", WINDOW_AUTOSIZE);//imshow("ROI_dst", temp_ROI);//createTrackbar("Threshold", "ROI_dst", &threshold_value, 255, DetectLine);//DetectLine(0,0);//霍夫直线检测 效果差//形态学+霍夫检测MorphShapes_Hough(0, 0);waitKey(0);return 0;}void DetectLine(int, void*){Mat Canny_edges;Canny(temp_ROI, Canny_edges, threshold_value, threshold_value * 2, 3, false);vector<Vec4f> plines;HoughLinesP(Canny_edges, plines, 1, CV_PI / 180.0, 30, 30.0, 0);cvtColor(Canny_edges, Canny_edges, COLOR_GRAY2BGR);for (size_t i = 0; i < plines.size(); i++){Vec4i Lines = plines[i];line(Canny_edges, Point(Lines[0], Lines[1]), Point(Lines[2], Lines[3]), Scalar(255, 0, 255), 2, 8);}imshow("ROI_dst", Canny_edges);return;}void MorphShapes_Hough(int, void*){//二值化Mat Threshold_img;threshold(temp_ROI, Threshold_img, 0,255, THRESH_BINARY_INV | THRESH_OTSU);imshow("Threshold_dst", Threshold_img);//自定义核Mat h_kernel = getStructuringElement(MORPH_RECT, Size(src.cols / 16, 1), Point(-1, -1));//水平结构元素//形态学梯度morphologyEx(Threshold_img, dst, MORPH_OPEN/*开操作,先腐蚀再膨胀*/, h_kernel, Point(-1, -1));imshow("Morphology", dst);//膨胀Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));dilate(dst, dst, kernel);imshow("Dilate", dst);//Hough检测vector<Vec4f> plines;HoughLinesP(dst, plines, 1, CV_PI / 180.0, 30, 30.0, 0);//Mat dst_img = temp_ROI.clone();cvtColor(temp_ROI, temp_ROI, COLOR_GRAY2BGR);for (size_t i = 0; i < plines.size(); i++){Vec4i Lines = plines[i];line(temp_ROI, Point(Lines[0], Lines[1]), Point(Lines[2], Lines[3]), Scalar(255, 0, 255), 2, 8);}imshow("ROI_dst", temp_ROI);return;}
src为:
输出结果:
赞 (0)