I'm using opencv2. I created 2 cv::Mat
with external user data ( matLoad
and matResize
. And resize matLoad
to matResize
. However, after the cv::resize
function is called, the user data is still empty (all 0xCD
). But matResize.data
is changed and no longer equal to the pointer to the user data. It seems that cv::resize
resets the destination Mat's data
property, with a new piece of memory space allocated inside opencv. See below:
cv::Mat matLoad(cutw, cuth, cvfmt, mDataLoad);
... // Read image data into `mDataLoad`
cv::Mat matResize(rcutw, rcuth, cvfmt, mDataProc);
printf("%s\n", (matResize.data == mDataProc) ? "equal" : "notequal"); // "equal" is called
cv::resize(matLoad, matResize, cv::Size(rcutw, rcuth));
printf("%s\n", (matResize.data == mDataProc) ? "equal" : "notequal"); // "notequal" is printed
for (int i = 0; i < matResize.elemSize() * matResize.cols * matResize.rows; i++) {
if (matResize.data[i] != 205) {
printf("hehe %d\n", matResize.data[i]); // many lines printed, with different values
}
}
for (int i = 0; i < matResize.elemSize() * matResize.cols * matResize.rows; i++) {
if (mDataProc[i] != 205) {
printf("hehe %d\n", mDataProc[i]); // none is printed
}
}
But if I create matResize
without passing the user data (ie, let opencv allocate and maintain the memory space by itself), the resize works well.
cv::Mat matLoad(cutw, cuth, cvfmt, mDataLoad);
... // Read image data into `mDataLoad`
cv::Mat matResize(rcutw, rcuth, cvfmt);
cv::resize(matLoad, matResize, cv::Size(rcutw, rcuth));
for (int i = 0; i < matResize.elemSize() * matResize.cols * matResize.rows; i++) {
if (matResize.data[i] != 205) {
printf("hehe %d\n", matResize.data[i]); // many lines printed, with different values
}
}
What's wrong with the cv::Mat
created with external user data?
If the dimension of the resized matrix is different from the destination matrix, then the destination matrix will be re-allocated. So to avoid re-allocations you need to be sure that the dimensions agree.
In your code you're setting the destination size as:
cv::Mat matResize(rcutw, rcuth, cvfmt, mDataProc);
but you're asking for a resized image of size:
cv::Size(rcutw, rcuth)
You inverted rows (height) and columns (width).
So simply create the matrix with the correct size with:
cv::Mat matResize(rcuth, rcutw, cvfmt, mDataProc);
^^^^^^^^^^^^^
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.