OpenCV 3.1 UMat assignment

1.9k Views Asked by At

I am trying to implement a performance upgrade to the project of my company. The project depends on OpenCV and recently I have successfully upgraded to OpenCV 3.1 to use UMat. Though I cant find a complete tutorial on it except basic operations. So I am stuck at the following:

Mat m (width, height, type, someData, step);
cv::UMat * ptr = new cv::UMat (width, height, type);
//dont ask me why the hell we are using a pointer to the smart mat object (my project leader insists)

This doesnt work

ptr->setTo (m);

Neither does this:

m.copyTo(*ptr);

These cause an exception.

ptr=&m.getUMat(cv::ACCESS_RW);

And this one results with a two dimensional mat with 0 rows and 0 cols... Need help. Thanks in advance!!!!

2

There are 2 best solutions below

0
On

cv::setTo() is used to set a Mat object to a scalar, not for copying data from a Mat to a UMat, which is what I believe you are trying to do.

m.copyTo(*ptr) works fine to me:

int width=2;
int height=width;
int someData [4] {1,2,3,4};
int type=CV_32S;

cv::Mat m (width, height, type, someData, width*sizeof(int));
cv::UMat * ptr = new cv::UMat (width, height, type);
cv::UMat out;

m.copyTo(*ptr);

cv::multiply(*ptr,*ptr, out);

out.copyTo(m);

std::cout<<m<<std::endl; // [1, 4; 9, 16]

with ptr=&m.getUMat(cv::ACCESS_RW); you are trying to get the addess of a temporary UMat object generated by getUMat() and assign it to ptr. This object would no longer exist after this call. In addition, you would lose the reference to the UMat object generated by new().

Consider the following instead:

*ptr=m.getUMat(cv::ACCESS_RW);
0
On

I think you would be better of initializing your cv::UMat like this:

cv::UMat* ptr = new cv::UMat(m.getUMat(cv::ACCESS_READ));
std::cout << "ptr = " << std::endl << ptr->getMat(cv::ACCESS_RW) << std::endl;

This way you don't have to set the sizes and the types manually. Also, if you must use pointers, consider using some of the sweet C++11 features like std::unique_ptr or std::shared_ptr.