我有一个圆柱形物体,上面贴有圆形标签。我提取图像的轮廓。
我知道圆柱形物体的半径以及标签。但并不是每次得到的椭圆都是完全对称的。如何将椭圆展开为圆形?
这是一个不对称的图像
已编辑 我尝试扩展 @Haris 的解决方案,如下所示
我想使用点数组来获得更准确的圆,而不是仅仅使用 4 个点。但
getPerspectiveTransform
不允许我获得超过4分。有更好的方法吗?
所以你想将你的对象变换为最小外接圆,
如下图所示,将簧片矩形变换为绿色圆圈。即将边界矩形变换为边界圆。
所以请执行以下操作,
对图像设置阈值
Mat src=imread("src.png");
Mat thr;
cvtColor(src,thr,CV_BGR2GRAY);
threshold( thr, thr, 20, 255,CV_THRESH_BINARY_INV );
bitwise_not(thr,thr);
vector< vector <Point> > contours; // Vector for storing contour
vector< Vec4i > hierarchy;
Mat dst(src.rows,src.cols,CV_8UC1,Scalar::all(0)); //create destination image
findContours( thr.clone(), contours, hierarchy,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE ); // Find the contours in the image
drawContours( dst,contours, 0, Scalar(255,255,255),CV_FILLED, 8, hierarchy );
Rect R=boundingRect(contours[0]);
Point2f center;
float radius;
minEnclosingCircle( (Mat)contours[0], center, radius);`
这里你需要从边界框和圆计算变换矩阵
std::vector<Point2f> src_pts;
std::vector<Point2f> dst_pts;
src_pts.push_back(Point(R.x,R.y));
src_pts.push_back(Point(R.x+R.width,R.y));
src_pts.push_back(Point(R.x,R.y+R.height));
src_pts.push_back(Point(R.x+R.width,R.y+R.height));
dst_pts.push_back(Point2f(center.x-radius,center.y-radius));
dst_pts.push_back(Point2f(center.x+radius,center.y-radius));
dst_pts.push_back(Point2f(center.x-radius,center.y+radius));
dst_pts.push_back(Point2f(center.x+radius,center.y+radius));
Mat transmtx = getPerspectiveTransform(src_pts,dst_pts);
然后应用透视变换,
Mat transformed = Mat::zeros(src.rows, src.cols, CV_8UC3);
warpPerspective(src, transformed, transmtx, src.size());
imshow("transformed", transformed);