如何使用opencv或javacv识别多边形?

我正在做一个使用图像处理技术来识别不同对象及其长度的项目。 我在javaCV以及OpenCV中经历了很多例子。 但不幸的是我无法识别多边形的T形。

我尝试使用以下矩形识别方法,但我失败了。

public static CvSeq findSquares( final IplImage src, CvMemStorage storage) { CvSeq squares = new CvContour(); squares = cvCreateSeq(0, sizeof(CvContour.class), sizeof(CvSeq.class), storage); IplImage pyr = null, timg = null, gray = null, tgray; timg = cvCloneImage(src); CvSize sz = cvSize(src.width() & -2, src.height() & -2); tgray = cvCreateImage(sz, src.depth(), 1); gray = cvCreateImage(sz, src.depth(), 1); pyr = cvCreateImage(cvSize(sz.width()/2, sz.height()/2), src.depth(), src.nChannels()); // down-scale and upscale the image to filter out the noise cvPyrDown(timg, pyr, CV_GAUSSIAN_5x5); cvPyrUp(pyr, timg, CV_GAUSSIAN_5x5); cvSaveImage("ha.jpg", timg); CvSeq contours = new CvContour(); // request closing of the application when the image window is closed // show image on window // find squares in every color plane of the image for( int c = 0; c  1){ cvSplit(timg, channels[0], channels[1], channels[2], null); }else{ tgray = cvCloneImage(timg); } tgray = channels[c]; // try several threshold levels for( int l = 0; l  0) { approx = cvApproxPoly(contours, Loader.sizeof(CvContour.class),storage, CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0); if( approx.total() == 4 && Math.abs(cvContourArea(approx, CV_WHOLE_SEQ, 0)) > 1000 && cvCheckContourConvexity(approx) != 0 ){ double maxCosine = 0; // for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = Math.abs(angle(new CvPoint(cvGetSeqElem(approx, j%4)), new CvPoint(cvGetSeqElem(approx, j-2)), new CvPoint(cvGetSeqElem(approx, j-1)))); maxCosine = Math.max(maxCosine, cosine); } if( maxCosine < 0.2 ){ CvRect x=cvBoundingRect(approx, l); if((x.width()*x.height())<5000 ){ System.out.println("Width : "+x.width()+" Height : "+x.height()); cvSeqPush(squares, approx); //System.out.println(x); } } } } contours = contours.h_next(); } contours = new CvContour(); } } return squares; } 

请帮助我修改此方法以从图像中识别T形状。 输入图像是这样的。

在此处输入图像描述

这是我必须识别的T形

在此处输入图像描述

我找到了解决问题的方法:

  • 将图像转换为灰度:

灰度图像

  • 做一个阈值(转换为1位图像):

2位图像

  • 查找轮廓并填充它们:

填充图像

提示:要在OpenCV中填充轮廓,请使用-1作为drawContours函数中的thickness参数。

  • 使用相同的内核进行扩张和侵蚀后:

结果图像

就是这样! 在此之后,您在图像上找到T形图形不是问题!

不幸的是我不知道JavaCV,但我可以与你分享c ++代码:

 Mat src = imread("in.jpg"), gray; cvtColor(src, gray, CV_BGR2GRAY); threshold(gray, gray, 230, 255, THRESH_BINARY_INV); vector hierarchy; vector > contours; findContours(gray, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); gray = Scalar::all(255); for (size_t i=0; i 

提示:如果需要,可以将此代码转换为JavaCV。 为此,请阅读本教程 。

您最好找到轮廓并使用CvApproxPoly() 。 您可以找到一个很好的示例,说明如何使用此函数在此处查找矩形并调整它以查找T形状。 此示例使用OpenCV创建并使用c ++编写。

要遍历序列中的所有点:

 for (int i = 0; i < cornerPoints->total; i++) { CvPoint *cornerPoints = (CvPoint*) cvGetSeqElem(cornerPoints, i); } 

听起来像家庭作业

预处理@Astor带来的肯定是有帮助的。 但我仍然认为这种形状识别与图像处理:形态学密切相关

你可以准备一个T形模板,然后“回旋?” 具有预处理结果的模板。 我不记得更多的细节,只是关于TAG形态学和卷积的调查