2016-05-01 53 views
2

This documentation page狀態:聯盟兩個矩形Java中的OpenCV

In addition to the class members, the following operations on rectangles are implemented: [...]

  • rect = rect1 | rect2 (minimum area rectangle containing rect2 and rect3)

然而,這段代碼:

Rect box1 = new Rect(); 
Rect box2 = new Rect(); 
Rect unionBox = new Rect(); 

unionBox = box1 | box2; 

導致這個錯誤:

Operator '|' cannot be applied to 'org.opencv.core.Rect', 'org.opencv.core.Rect'

我如何正確工會兩(或更好:很多)Rect s?

回答

2

JAVA不支持AFAIK使用運算符。

我建議使用boundingRect,但你應該知道下面還有所看到C++代碼的一個像素差

#include "opencv2/imgproc/imgproc.hpp" 
#include "opencv2/highgui/highgui.hpp" 

#include <iostream> 

using namespace cv; 
using namespace std; 

int main(int argc, char** argv) 
{ 
    Rect a(10,10,20,20); 
    Rect b(11,11,20,20); 

    vector<Point> pts; 

    pts.push_back(a.tl()); 
    pts.push_back(a.br()); 

    pts.push_back(b.tl()); 
    pts.push_back(b.br()); 

    Rect boundingRect_result = boundingRect(pts); 
    Rect operator_result = a | b; 

    cout << "Rect a: " << a << endl; 
    cout << "Rect b: " << b << endl; 

    cout << "\nRect Points a b:\n" << pts << endl; 

    cout << "\nboundingRect result : " << boundingRect_result << endl; 
    cout << "result a | b  : " << operator_result << endl; 

    return 0; 
} 

輸出:

Rect a: [20 x 20 from (10, 10)] 
Rect b: [20 x 20 from (11, 11)] 

Rect Points a b: 
[10, 10; 
30, 30; 
11, 11; 
31, 31] 

boundingRect result : [22 x 22 from (10, 10)] 
result a | b  : [21 x 21 from (10, 10)] 

(我不熟悉Java,但試着寫下面的代碼來測試)

Rect r1 = new Rect(10,10,20,20); 
Rect r2 = new Rect(11,11,20,20); 

Point[] rects_pts = new Point[4]; 
rects_pts[0] = r1.tl(); 
rects_pts[1] = r1.br(); 
rects_pts[2] = r2.tl(); 
rects_pts[3] = r2.br(); 

MatOfPoint mof = new MatOfPoint(); 
mof.fromArray(rects_pts); 

Rect union = Imgproc.boundingRect(mof); 
System.out.print(union); 

結果就像{10, 10, 22x22}

另一種選擇是在JAVA中編寫自己的函數。 here is OpenCV source可以轉換成JAVA