I was given some code where IplImage is created using memcpy and then converted to cv :: Mat:
IplImage* iplImage = cvCreateImage(cv::Size(imageWidth, imageHeight), IPL_DEPTH_8U, bytesPerPixel);
memcpy(iplImage->imageData, memory, imageWidth * imageHeight * bytesPerPixel);
cv::Mat image = cv::cvarrToMat(iplImage, true, true, 0);
cvReleaseImage(&iplImage);
memory is a pointer to a void pointer to the beginning of a memory block.
I want to port this code to use only OpenCV C ++ Api. This is what I tried first:
cv::Mat image(cv::Size(imageWidth, imageHeight), CV_MAKETYPE(CV_8U, bytesPerPixel), memory);
But the image is empty.
Then I tried this:
cv::Mat image(cv::Size(imageWidth, imageHeight), CV_MAKETYPE(CV_8U, bytesPerPixel));
memcpy(image.data, memory, imageWidth * imageHeight * bytesPerPixel);
This method works, but it uses a lot more RAM (about 100 MB), so I assume there is unnecessary copying.
What would be the right way to do this?
EDIT: The memory is indeed in a wrapper class. It is automatically released. I just changed it to "memory."
EDIT2: Here is the complete code, including the object from which the memory originates:
cv::Mat RecordingPlayer::next() {
if (currentContainer.getDataType() == odcore::data::image::SharedImage::ID()) {
odcore::data::image::SharedImage sharedImage = currentContainer.getData<odcore::data::image::SharedImage>();
std::shared_ptr<odcore::wrapper::SharedMemory> memory = odcore::wrapper::SharedMemoryFactory::attachToSharedMemory(sharedImage.getName());
IplImage* iplImage = cvCreateImage(imageSize(), IPL_DEPTH_8U, bytesPerPixel);
memcpy(iplImage->imageData, memory->getSharedMemory(), imageWidth * imageHeight * bytesPerPixel);
cv::Mat image = cv::cvarrToMat(iplImage, true, true, 0);
cvReleaseImage(&iplImage);
return image;
} else {
return cv::Mat();
}
}