Most efficient way to clear an image with C++ interface?
I'm currently porting my old OpenCV C code to the C++ interface of OpenCV 2/3 and I'm not quite sure about some equivalents for old functions. Pretty early I ran into an issue with cvZero. The only possibility I found was to set the matrix content via Mat::setTo. Now, having to be able to manage multi-channel scalars and different data types, setTo iterates through all elements of the matrix and sets them one after another while cvZero basically did a memset. Also, I read that using setTo is a lot slower compared to simply doing this:
myMat = cv::Mat::zeros( myMat.size(), myMat.type() );
Still, I'm not sure if this allocates a new matrix and frees the old one, which I also wouldn't want. Of course I could always write
memset( myMat.data, 0, myMat.size().width * myMat.size().height * myMat.depth() );
but isn't there a proper convenience function for this?
So, I am wondering what would be the recommended way for using the C++ interface, in case I just want to clear my image black.
Thanks!
the equivalent for cvZero you can find it here (that you probably saw). Why do you think that it is slower than the cvZero function? How do you use cvZero and what do you think it does (is there any doc about it?)?
please take another look at setTo(), it does not iterate over pixels, but over planes and consecutive blocks, and then does a memset.
also, a simple memset might be inappropriate for non-continuous data (i.e. a ROI)
thanks, I misread. not sure what blocks are for, though. As a matter of fact, setTo is a lot slower, compared to cvZero. Here is the output of a very basic benchmark I did (image size is Full HD, 8 bit single channel):
Mat::zeros is, however, faster than cvZero. Mat::setTo on the other hand is a lot faster than the old C API's cvSet:
IMHO
cv::Mat::zeros
is the equivalent tocvZero
and cv::Mat::setTo is the equivalent tocvSet
. But could you be more explicit about thecvZero( im )
? How do you use it? Why would it be a problem if it allocates a new Mat and deallocates the old one? Normally, if you still have some other Mat that use the initial one, you will not arrive in the case of lost pointer, because the Mat is a smart pointer, it will be deallocated only if no-one is using that memory.Frankly, I don't understand what you're asking - I use cvZero exactly as I wrote above, how else would I use it? cvZero( im ); The reason I am worried about unnecessary memory allocation and deallocation is of course performance, which is traditionally a consideration in most computer vision applications. I don't want to allocate and deallocate hundreds of matrixes each frame. When I use a computer vision library, I really try to use it in the most efficient way and to avoid unnecessary operations.