天天看點

Opencv 使用Rect選取與設定視窗ROI

首先看一下Rect對象的定義:

typedef Rect_<int> Rect;
           

再看Rect_的定義:

/*!
  The 2D up-right rectangle class

  The class represents a 2D rectangle with coordinates of the specified data type.
  Normally, cv::Rect ~ cv::Rect_<int> is used.
*/
template<typename _Tp> class Rect_
{
public:
    typedef _Tp value_type;

    //! various constructors
    Rect_();
    Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
    Rect_(const Rect_& r);
    Rect_(const CvRect& r);
    Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
    Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);

    Rect_& operator = ( const Rect_& r );
    //! the top-left corner
    Point_<_Tp> tl() const;
    //! the bottom-right corner
    Point_<_Tp> br() const;

    //! size (width, height) of the rectangle
    Size_<_Tp> size() const;
    //! area (width*height) of the rectangle
    _Tp area() const;

    //! conversion to another data type
    template<typename _Tp2> operator Rect_<_Tp2>() const;
    //! conversion to the old-style CvRect
    operator CvRect() const;

    //! checks whether the rectangle contains the point
    bool contains(const Point_<_Tp>& pt) const;

    _Tp x, y, width, height; //< the top-left corner, as well as width and height of the rectangle
};
           

從上面的定義至少可以發現兩點:

  • 類Rect_的類模闆中的資料類型Tp在Rect中被指定為整型
  • 從Rect_的構造函數可以看出,其形參清單一共有6種形式
    1. Rect_(),形參清單為空,即定義一個空視窗(預設值為:x=y=width=height=0)
    2. Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height),定義一個左上角點坐标為(_x, _y)的_width*_height矩形視窗
    3. Rect_(const Rect_& r),使用其他的Rect_對象初始化
    4. Rect_(const CvRect& r),使用CvRect對象初始化
    5. Rect_(const Point_<Tp>& org, const Size<Tp>& sz),分别将位置坐标(_x, _y)和視窗大小(_width, _height)用Point和Size_對象初始化
    6. Rect_(const Point_<Tp>& pt1, const Point<Tp>& pt2),分别将坐标位置(_x, _y)和視窗大小(_width, _height)用Point和Point_對象初始化
    7. 在OpenCV庫中,圖像像素坐标與所在行列數的對應關系為:x -> col, y -> row, width -> cols, height -> rows

下面給出一段代碼,基本可以把Rect的常見用法涵蓋

Mat image = imread("C:\\Users\\Leo\\Desktop\\lena.jpg");
Rect rect1(, , , );
Rect rect2(, , , );

Mat roi1;
image(rect1).copyTo(roi1); // copy the region rect1 from the image to roi1
imshow("1", roi1);
waitKey();

Mat roi2;
image(rect2).copyTo(roi2); // copy the region rect2 from the image to roi2
imshow("2", roi2);
waitKey();

cv::Rect rect3 = rect1&rect2; // intersection of the two sets
Mat roi3;
image(rect3).copyTo(roi3);
imshow("3", roi3);
waitKey();

Rect rect4 = rect1|rect2; // union of the two sets (the minimum bounding rectangle)
Mat roi4;
image(rect4).copyTo(roi4);
imshow("4", roi4);
waitKey();

Rect rect5(, , , );
roi1.copyTo(image(rect5)); // copy the region rect1 to the designated region in the image
imshow("5", image);
waitKey();
           

結果為

Opencv 使用Rect選取與設定視窗ROI

注:本文轉自yhl_leo的CSDN部落格