直接上代码!
#pragma once
#include <opencv2/opencv.hpp>
class MyRect
{
public:
MyRect(cv::Point pt, cv::Size size);
MyRect(int x, int y, int width, int height);
cv::Rect get();
int area();
int width();
int height();
bool contains(cv::Point pt);
cv::Size size();
cv::Point tl();
cv::Point br();
bool isInside(cv::Rect rect1, cv::Rect rect2);
cv::Point getCenterPoint(cv::Rect rect);
cv::Rect rectCenterScale(cv::Rect rect, cv::Size size);
int distance(cv::Rect rect2);
private:
cv::Rect rect;
};
#include "MyRect.h"
MyRect::MyRect(cv::Point pt, cv::Size size)
: rect(pt, size)
{
}
MyRect::MyRect(int x, int y, int width, int height)
: rect(x, y, width, height)
{
}
cv::Rect MyRect::get()
{
return rect;
}
int MyRect::area()
{
return rect.area();
}
int MyRect::width()
{
return rect.width;
}
int MyRect::height()
{
return rect.height;
}
bool MyRect::contains(cv::Point pt)
{
return rect.contains(pt);
}
cv::Size MyRect::size()
{
return rect.size();
}
cv::Point MyRect::tl()
{
return rect.tl();
}
cv::Point MyRect::br()
{
return rect.br();
}
bool MyRect::isInside(cv::Rect rect1, cv::Rect rect2)
{
return (rect1 == (rect1&rect2));
}
cv::Point MyRect::getCenterPoint(cv::Rect rect)
{
cv::Point cpt;
cpt.x = rect.x + cvRound(rect.width/2.0);
cpt.y = rect.y + cvRound(rect.height/2.0);
return cpt;
}
cv::Rect MyRect::rectCenterScale(cv::Rect rect, cv::Size size)
{
rect = rect + size;
cv::Point pt;
pt.x = cvRound(size.width/2.0);
pt.y = cvRound(size.height/2.0);
return (rect-pt);
}
int MyRect::distance(cv::Rect rect2)
{
cv::Point cpt1 = getCenterPoint(rect);
cv::Point cpt2 = getCenterPoint(rect2);
int wd = abs(cpt1.x-cpt2.x);
int hd = abs(cpt1.y-cpt2.y);
return cvRound(static_cast<int>(sqrtl(powl(wd,2.0)+powl(hd,2.0))));
}
#include <opencv2/opencv.hpp>
#include "MyRect.h"
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("img1.jpg");
MyRect rect1(200, 200, 100, 100);
rectangle(img, rect1.get(), Scalar(0, 0, 255), 2);
MyRect rect2(300, 300, 100, 100);
rectangle(img, rect2.get(), Scalar(0, 255, 0), 2);
cout << rect1.distance(rect2.get()) << endl;
cout << rect2.distance(rect1.get()) << endl;
imshow("Img", img);
waitKey(0);
return 0;
}