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;
相关推荐
非凡ghost1 分钟前
ChatOn:智能AI聊天助手,开启高效互动新时代
android·人工智能·智能手机·生活·软件需求
一颗小树x16 分钟前
【机器人】具身导航 VLN 最新论文汇总 | Vision-and-Language Navigation
人工智能·论文·综述·具身导航·对象导航
红衣小蛇妖23 分钟前
神经网络-Day42
人工智能·深度学习·神经网络
Joern-Lee24 分钟前
机器学习算法:逻辑回归
人工智能·算法·机器学习·逻辑回归
亚马逊云开发者25 分钟前
基于 Amazon Q Developer CLI 和 Amazon Bedrock Knowledge Bases 实现智能问答系统
人工智能
Starry丶26 分钟前
一天搞懂深度学习--李宏毅教程笔记
人工智能·笔记·深度学习
love530love40 分钟前
【笔记】Windows系统部署suna基于 MSYS2的Poetry 虚拟环境backedn后端包编译失败处理
开发语言·人工智能·windows·笔记·python·numpy
逆风飞翔i1 小时前
简单工厂模式
c++·简单工厂模式
zyq~1 小时前
【课堂笔记】标签传播算法Label Propagation Algorithm(LPA)
人工智能·笔记·算法·机器学习·概率论·lpa·半监督学习
Xyz_Overlord1 小时前
机器学习——集成学习
人工智能·机器学习·集成学习