利用OpenCV创建自己的Rect类

本文通过示例代码展示了如何在OpenCV中创建并使用自定义的Rect类,详细解释了相关实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码!

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值