OpenCv (C++) 使用矩形 Rect 覆盖图像中某个区域

文章目录

    • [1. 使用矩形将图像中某个区域置为黑色](#1. 使用矩形将图像中某个区域置为黑色)
    • [2. cv::Rect 类介绍](#2. cv::Rect 类介绍)

1. 使用矩形将图像中某个区域置为黑色

推荐参考博客:OpenCV实现将任意形状ROI区域置黑(多边形区域置黑)

比较常用的是使用 Rect 矩形实现该功能,代码如下:

cpp 复制代码
#include <opencv2\opencv.hpp>

int main() {
	std::string filePath = "img.png";
	cv::Mat img = cv::imread(filePath);

	//创建矩形
	int x = img.cols / 2;    // x 对应列坐标
	int y = img.rows / 2;    // y 对应行坐标
	int width = 150;
	int height = 80;
	cv::Rect rect(x, y, width, height);

	//将矩形贴到img中,并将矩形区域置为黑色
	cv::Mat subImg = img(rect);
	subImg.setTo(0);

	cv::imwrite("img_rect.png", img);
	return 0;
}

效果如下:

2. cv::Rect 类介绍

推荐参考博客:OpenCV 中 cv::Rect 矩形类用法

cv::Rect 用于创建矩形,API 参数如下:

bash 复制代码
int x;    // 左上角 x 坐标,对应列坐标
int y;    // 左上角 y 坐标,对应列坐标
int width;     // 宽
int height;    // 高

源码如下:

cpp 复制代码
template<typename _Tp> class Rect_
{
public:
    typedef _Tp value_type;

    //! default constructor
    Rect_();
    Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
    Rect_(const Rect_& r);
    Rect_(Rect_&& r) CV_NOEXCEPT;
    Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
    Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);

    Rect_& operator = ( const Rect_& r );
    Rect_& operator = ( Rect_&& r ) CV_NOEXCEPT;
    //! 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;
    //! true if empty
    bool empty() const;

    //! conversion to another data type
    template<typename _Tp2> operator Rect_<_Tp2>() const;

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

    _Tp x; //!< x coordinate of the top-left corner
    _Tp y; //!< y coordinate of the top-left corner
    _Tp width; //!< width of the rectangle
    _Tp height; //!< height of the rectangle
};

typedef Rect_<int> Rect2i;
typedef Rect_<float> Rect2f;
typedef Rect_<double> Rect2d;
typedef Rect2i Rect;
相关推荐
自不量力的A同学6 分钟前
字节 AI 原生 IDE Trae 发布 v1.3.0,新增 MCP 支持
人工智能
涛涛讲AI11 分钟前
当AI浏览器和AI搜索替代掉传统搜索份额时,老牌的搜索引擎市场何去何从。
人工智能·搜索引擎
engchina20 分钟前
来自B站AIGC科技官的“vLLM简介“视频截图
人工智能·vllm
说私域36 分钟前
基于开源技术体系的品牌赛道力重构:AI智能名片与S2B2C商城小程序源码驱动的品类创新机制研究
人工智能·小程序·重构·开源·零售
智驱力人工智能42 分钟前
无感通行与精准管控:AI单元楼安全方案的技术融合实践
人工智能·安全·智慧城市·智慧园区
Chrome深度玩家1 小时前
谷歌翻译安卓版拍照翻译精准度与语音识别评测【轻松交流】
android·人工智能·语音识别
Ethon_王1 小时前
走进Qt--工程文件解析与构建系统
c++·qt
机器之心1 小时前
ICLR 2025 Oral|差分注意力机制引领变革,DIFF Transformer攻克长序列建模难题
人工智能
机器之心1 小时前
字节Seed团队PHD-Transformer突破预训练长度扩展!破解KV缓存膨胀难题
人工智能
正宗咸豆花1 小时前
开源提示词管理平台PromptMinder使用体验
人工智能·开源·prompt