I'm pretty new to openCV and would like to ask what seems like a easy question.
I have an image in the form of a cv::Mat
and I would like to change only a small part of the matrix. I've read that using a cv::Rect
is the correct way but I can't seem to find a way to only modify that little ROI.
Here's the code:
cv::Mat img = cv::Mat::zeros(msg->height, msg->width, CV_64FC1);
cv::Rect rect(100, 100, 20, 50);
All I want to do is do linear tranformation to the rect
and add asign it to the same part of the img.
Something like:
int a=0.1, b=20;
rect = rect*a b;
Thanks in advance.
CodePudding user response:
OpenCV's cv::Mat
has a constructor that creates an ROI image referncing another image:
cv::Mat::Mat(const Mat & m, const Rect & roi)
Using this constructor will cause the new cv::Mat
to share the data with the original one:
No data is copied by these constructors. Instead, the header pointing to m data or its sub-array is constructed and associated with it.
The reference counter, if any, is incremented. So, when you modify the matrix formed using such a constructor, you also modify the corresponding elements of m.
You can also use the operator()
for that:
Mat cv::Mat::operator() (const Rect & roi) const
In your case you can do something like the following:
#include <opencv2/core/core.hpp>
int main()
{
int h = 320;
int w = 640;
cv::Mat img = cv::Mat::ones(h, w, CV_64FC1);
cv::Rect rect(100, 100, 20, 50);
cv::Mat roi(img, rect); // alternatively you can use: cv::Mat roi = img(rect);
double a = 0.1;
double b = 20;
roi = roi * a b; // this will modify the relevant area in img
return 0;
}