2017-02-23 104 views
2

我想製作一個橢圓蒙版來裁剪圖像,以便只顯示橢圓內的內容。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

回答

1

您正在檢索imageOrig座標系中的橢圓座標,但是您在裁剪的out圖像上顯示它。

如果你想顯示對作物的橢圓,您需要翻譯的橢圓中心,以考慮通過作物(的rect左上角座標)推出的翻譯,是這樣的:

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

謝謝@Miki! –

0

你可以試試這個:

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

仍然沒有:( –

+0

它必須工作,你改變厚度,並再試一次 –

+0

我已經改變了厚度在2-20左右,我還沒有得到任何東西。:( –

0

您應該檢查使用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)'應該可以工作。否則,將座標改爲本地座標系 –