opencv 实战 直线检测

                       ```
#include
#include
using namespace cv;
using namespace std;
Mat src, dst;
int max_count = 255;
int threshold_value = 100;
void detectlines(int, void *);int main(int argc, char** argv)
{
 src = imread("1.png", IMREAD_GRAYSCALE);// 读取图片时就将图片转换为灰度图
 if (src.empty())
 {
  printf("could not load image...\n");
 }
 namedWindow("input image", WINDOW_AUTOSIZE);
 imshow("input image", src);
  detectlines(0, 0);
 waitKey(0);
 return 0;
}
void detectlines(int, void *)
{
 /*边缘检测,然后houghlines*/
 Canny(src, dst, threshold_value, threshold_value * 2, 3, false);
 vector lines;
 double theta = 30;
 HoughLinesP(dst, lines, 1, CV_PI / 180.0, theta, 30.0, 0);//使用houghlines 报错,使用houghlinesP,正确
 for (size_t i = 0; i < lines.size(); i++)
 {
  Vec4i ln = lines[i];
  line(dst, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(0, 0, 255), 2, 8, 0);
 }
 imshow("output lines", dst);
 /*结果,字也被显示了*/
}

结果,字体部分的直线也没提取出,干扰大
且,图像边缘的白线也被误检

opencv 实战 直线检测_第1张图片所以:

  1. 把边线去掉
  2. 把字抹去

opencv 实战 直线检测_第2张图片
问题一:除边线,生成新的ROI

Rect roi = Rect(10, 10, src.cols - 20, src.rows - 20);//左顶点坐标,右顶点坐标
 roiimage = src(roi);

问题二: 抹去字: 形态学开运算(先腐蚀后膨胀)

二值化+开运算+膨胀(使线更清晰)+houghlinesP(找线,并画出)

``

Mat src, dst,roiimage;
int max_count = 255;
int threshold_value = 100;
int theta = 30;
const char* output_lines = "Hough Lines";
void detectlines(int, void *);
void morhpologyLines(int, void*);
int main(int argc, char** argv)
{
 src = imread("1.png", IMREAD_GRAYSCALE);// 读取图片时就将图片转换为灰度图
 if (src.empty())
 {
  printf("could not load image...\n");
 }
 namedWindow("input image", WINDOW_AUTOSIZE);
 namedWindow(output_lines, WINDOW_AUTOSIZE);
 //createTrackbar("theta:", output_lines, &theta, 1000, detectlines);
 imshow("input image", src);
 Rect roi = Rect(10, 10, src.cols - 20, src.rows - 20);//左顶点坐标,右顶点坐标
 roiimage = src(roi);
//  detectlines(0, 0);
  morhpologyLines(0, 0);
 waitKey(0);
 return 0;
}
 void morhpologyLines(int, void*)
{
 /*二值化+开运算+houghlinesP*/
 Mat binaryImage, morhpImage;
 threshold(roiimage, binaryImage, 0, 255, THRESH_BINARY_INV| THRESH_OTSU);
 imshow("binary", binaryImage);
 Mat kernel = getStructuringElement(MORPH_RECT, Size(20, 1), Point(-1, -1));
 morphologyEx(binaryImage, morhpImage, MORPH_OPEN, kernel, Point(-1, -1));
 imshow("morphology result", morhpImage);
 /*dialte lines*/
 kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
 dilate(morhpImage, morhpImage, kernel);
 imshow("morphology lines", morhpImage);
//houghlines
 vector lines;
 HoughLinesP(morhpImage, lines, 1, CV_PI / 180.0, 30, 20.0, 0);
 for (size_t t = 0; t < lines.size(); t++) {
  Vec4i ln = lines[t];
  line(roiimage, Point(ln[0], ln[1]), Point(ln[2], ln[3]), Scalar(255, 255, 255), 2, 8, 0);
 }
 imshow(output_lines, roiimage);
 return;
}

你可能感兴趣的:(opencv)