OpenCV - 根本不显示椭圆

问题描述:

我想制作一个椭圆蒙版来裁剪图像,以便只显示椭圆内的内容。OpenCV - 根本不显示椭圆

你可以检查我的代码吗?

public static Mat cropImage(Mat imageOrig, MatOfPoint contour){ 
    Rect rect = Imgproc.boundingRect(contour); 

    MatOfPoint2f contour2f = new MatOfPoint2f(contour.toArray()); 
    RotatedRect boundElps = Imgproc.fitEllipse(contour2f); 

    Mat out = imageOrig.submat(rect); 

    // the line function is working 
    Imgproc.line(out, new Point(0,0), new Point(out.width(), out.height()), new Scalar(0,0,255), 5); 

    // but not this one 
    Imgproc.ellipse(out, boundElps, new Scalar(255, 0, 0), 99); 

    return out; 
}//cropImage 

看起来好像根本不起作用。虽然你可以看到我所做的线函数来测试它是否在正确的图像上工作,我可以看到一条线但没有椭圆。

下面是我的cropImage函数的示例输出。

cropImage's Output

TIA

+1

唐不要裁剪图像。您正在'imageOrig'坐标系中检索椭圆坐标。如果你想在裁剪上显示椭圆,你需要翻译椭圆中心,例如:'boundElps.center()。x - = rect.x; boundElps.center()。y - = rect.y;' – Miki

+0

嘿@Miki你应该让这个答案!这解决了我的问题!谢谢! –

+0

很高兴帮助。作为回答发布 – Miki

您正在检索imageOrig坐标系中的椭圆坐标,但是您在裁剪的out图像上显示它。

如果你想显示对作物的椭圆,您需要翻译的椭圆中心,以考虑通过作物(的rect左上角坐标)推出的翻译,是这样的:

boundElps.center().x -= rect.x; boundElps.center().y -= rect.y; 
+0

谢谢@Miki! –

你可以试试这个:

RotatedRect rRect = Imgproc.minAreaRect(contour2f); 
Imgproc.ellipse(out, rRect , new Scalar(255, 0, 0), 3); 
+0

仍然没有:( –

+0

它必须工作,你改变厚度,并再试一次 –

+0

我已经改变了厚度在2-20左右,我还没有得到任何东西。:( –

您应该检查使用fitEllipse如图this post的最低要求。 功能fitEllipse需要至少5分。 注意:虽然我提到的参考文献是针对Python的,但我希望您可以对Java做同样的工作。

for cnt in contours: 
    area = cv2.contourArea(cnt) 
    # Probably this can help but not required 
    if area < 2000 or area > 4000: 
     continue 
    # This is the check I'm referring to 
    if len(cnt) < 5: 
     continue 
    ellipse = cv2.fitEllipse(cnt) 
    cv2.ellipse(roi, ellipse, (0, 255, 0), 2) 

希望它有帮助!

+0

我认为如果积分不大于5我会有一个错误的权利?我之前遇到过这种情况,我想我已经过滤了所有小于5的轮廓。谢谢! –

+1

而且我会说你应该在原始图像中绘制椭圆,否t在裁剪的图像上。我想你是这么做的。 'Imgproc.ellipse(imgOrig,boundElps,new Scalar(0,255,0),2)'应该可以工作。否则,将坐标改为本地坐标系 –