分享

(三)OpenCV图像处理

 猎狐肥 2021-05-27
直接
  1. 直接用霍夫直线检测,效果差;
  2. 通过图像形态学操作来寻找直线,霍夫获取位置信息与显示。
#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", 
  1. 直接用霍夫直线检测,效果差;
  2. 通过图像形态学操作来寻找直线,霍夫获取位置信息与显示。
#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

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多