Mar*_*bek 7 java opencv image-recognition shapes contour
我有一个简单的图像,其中包含一些形状:一些矩形和一些椭圆形,总共 4 或 5 个。形状可以旋转、缩放和重叠。有一个示例输入:
我的任务是检测所有这些图形并准备一些有关它们的信息:大小、位置、旋转等。在我看来,核心问题是形状可以相互重叠。我尝试搜索一些有关此类问题的信息,发现 OpenCV 库非常有用。
OpenCV 能够检测轮廓,然后尝试将椭圆或矩形拟合到这些轮廓。问题是当形状重叠时,轮廓会混淆。
我考虑以下算法:检测所有特征点:并在它们上面放置白点。我得到了类似的东西,其中每个数字都分为不同的部分:
然后我可以尝试使用一些信息链接这些部分,例如复杂度值(我将曲线 approxPolyDP 拟合到轮廓并读取它有多少个部分)。但这开始变得非常困难。另一个想法是尝试连接轮廓的所有排列并尝试使图形适合它们。将输出最好的编译。
有什么想法如何创建简单但优雅的解决方案吗?
模糊图像有助于找到代码中所示的交叉点
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
int main( int argc, char** argv )
{
Mat src = imread( argv[1] );
Mat gray, blurred;
cvtColor( src, gray, COLOR_BGR2GRAY );
threshold( gray, gray, 127, 255, THRESH_BINARY );
GaussianBlur( gray, blurred, Size(), 9 );
threshold( blurred, blurred, 200, 255, THRESH_BINARY_INV );
gray.setTo( 255, blurred );
imshow("result",gray);
waitKey();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第2步
简单来说,借用了generalContours_demo2.cpp的代码
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
Mat src = imread( argv[1] );
Mat gray, blurred;
cvtColor( src, gray, COLOR_BGR2GRAY );
threshold( gray, gray, 127, 255, THRESH_BINARY );
GaussianBlur( gray, blurred, Size(), 5 );
threshold( blurred, blurred, 180, 255, THRESH_BINARY_INV );
gray.setTo( 255, blurred );
imshow("result of step 1",gray);
vector<vector<Point> > contours;
/// Find contours
findContours( gray.clone(), contours, RETR_TREE, CHAIN_APPROX_SIMPLE );
/// Find the rotated rectangles and ellipses for each contour
vector<RotatedRect> minRect( contours.size() );
vector<RotatedRect> minEllipse( contours.size() );
for( size_t i = 0; i < contours.size(); i++ )
{
minRect[i] = minAreaRect( Mat(contours[i]) );
if( contours[i].size() > 5 )
{
minEllipse[i] = fitEllipse( Mat(contours[i]) );
}
}
/// Draw contours + rotated rects + ellipses
for( size_t i = 0; i< contours.size(); i++ )
{
Mat drawing = src.clone();
// contour
//drawContours( drawing, contours, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
// ellipse
ellipse( drawing, minEllipse[i], Scalar( 0, 0, 255 ), 2 );
// rotated rectangle
Point2f rect_points[4];
minRect[i].points( rect_points );
for( int j = 0; j < 4; j++ )
line( drawing, rect_points[j], rect_points[(j+1)%4], Scalar( 0, 255, 0 ), 2 );
/// Show in a window
imshow( "results of step 2", drawing );
waitKey();
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3446 次 |
| 最近记录: |