【问题标题】:Union two rectangles in Java OpenCV在Java OpenCV中合并两个矩形
【发布时间】:2016-05-01 04:51:16
【问题描述】:

This documentation page 状态:

除了类成员之外,还有以下操作 矩形实现: [...]

  • 矩形 = 矩形 1 | rect2(包含 rect2 和 rect3 的最小面积矩形)

但是,这段代码:

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

unionBox = box1 | box2;

导致此错误:

运算符“|”不能应用于'org.opencv.core.Rect'、'org.opencv.core.Rect'

如何正确合并两个(或更好:多个)Rects?

【问题讨论】:

    标签: java opencv operator-overloading


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 2016-06-27
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多