cv::Mat assignment or copy with guarantee that there is no reallocation
I have code in the form of
cv::Mat function(const cv::Mat&);
cv::Mat a = ..;
cv::Mat b = ..;
cv::Rect roi = ..;
function(b, roi).copyTo(a(roi)); // here
on the line marked with "here" the matrix "a" will be reallocated if dimensions or data type do not match. In my case I only want to change a subregion, so reallocation would be a programming error. As far as I see, a temporary matrix would be created and a would not change at all.
another example:
cv::Mat matrixHeader = someOtherMat(roi)
matrixHeader = a | b; // someOtherMat won't be changed if there is a type mismatch, which is unexpected and without warning
is there a copy method in opencv that throws if the matrices are not compatible?
use clone method.
what do you mean by "my case that would be a programming error"?
clone is reallocation and not copy, so it doesn't apply.
I actually had a bug in the example code. I fixed and edited to make my intent more clear.
An example can be reproduced. i cannot with your example. I understand your problem like this :
No exception. Of course if b and rect size are different there is an exception
Indeed.
Is the documentation wrong? It says (cv::Mat::copyTo):
and (cv::Mat::create):
or am I misunderstanding something?
From what i see in the source code, (copy.cpp function
Mat::copyTo
and mat.inl.hpp function_OutputArray::_OutputArray
), it indeed does not behave as documented.Output array is initialised with flags called
FIXED_TYPE + FIXED_SIZE
.copyTo
checks forfixedType
, but not forFIXED_SIZE
. The code path using the create function is still there, but it is not taken. instead there is said exception (plus "OpenCV Error: Assertion failed" warnings in 3.2, depending on what mismatches, but not always).you can test the code below ( see memory usage )
there is a reallocation when it is mat object and not ROI. In a roi there is no real data opencv plays with rows and column and stride.
In b.copyTo(a) a is reallocated.
I don't think so... If it were reallocated, you wouldn't see it change the original. But the copyTo still affects the original image. So b.copyTo(a) is still using the original memory.
a is not using original if a is smaller than b :
Ah, I think I see the confusion. Yes, that will reallocate. No there is not a built-in copy function that will throw, but you can build a simple check that will.
For example: