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;
相关推荐
keep intensify几秒前
Redis基础指令全解析:从入门到精通
linux·数据库·c++·redis
无风听海3 分钟前
神经网络之计算图
人工智能·深度学习·神经网络
摘星编程8 分钟前
RAG系统搭建指南:5种主流框架的易用性和效果对比
人工智能
爱吃生蚝的于勒8 分钟前
【Linux】零基础学会linux环境基础开发工具使用(yum,vim,makefile,gdb)
linux·服务器·数据结构·c++·蓝桥杯·编辑器·vim
R-G-B10 分钟前
【34】MFC入门到精通——MFC 控件 ComboBox 运行点击控件下拉框 “终止“、“重试“、“忽略“、“引发异常”
c++·mfc·combobox“引发异常”·“终止“·“重试“·“忽略“·“引发异常”
荔园微风15 分钟前
ML.NET机器学习框架基本流程介绍
人工智能·机器学习·.net
点云SLAM16 分钟前
矩阵奇异值分解算法(SVD)的导数 / 灵敏度分析
人工智能·线性代数·算法·机器学习·矩阵·数据压缩·svd算法
仁懋-MOT半导体19 分钟前
高效能源转换的关健|仁懋MOSFET在逆变器领域的突破应用
人工智能·硬件工程·能源·创业创新·制造
JAVA学习通21 分钟前
Spring AI 1.0 GA 深度解析:Java生态的AI革命已来
java·人工智能·spring·springai
二向箔reverse22 分钟前
神经网络中的批归一化(BatchNorm)
人工智能·深度学习·神经网络