ofImage avoid memory copy when setting pixels

Hi,

I have a RGB image in memory, I would like to use setFromPixels using a memory address. But avoid the memcpy when setting the pixels.

Here’s what I’m trying:

// let m_image be my ofImage
// let m_data_ptr be the pointer to the RGB in memory
ofPixels_<unsigned char> m_pixels_ref = m_image.getPixelsRef();
m_pixels_ref.setFromExternalPixels( m_data_ptr, m_width, m_height, OF_IMAGE_COLOR );

m_image.update(); //thought this might be necessary

From the source I thought the pixels of the ofImage would now point to the correct data and thence update the texture. But it’s not working.

In ofxCv there is a similar code, which I used to bind an ofImage to a cv::Mat. I don’t know what could be going wrong in my case.

Hi,
the problem with your code is that you are creating a new instance of ofPixels_ instead of a reference.
You either can do

ofPixels_<unsigned char> & m_pixels_ref = m_image.getPixelsRef();
m_pixels_ref.setFromExternalPixels( m_data_ptr, m_width, m_height, 3 );
m_image.update();

or

m_image.getPixelsRef().setFromExternalPixels( m_data_ptr, m_width, m_height, 3 );
m_image.update();

hope it helps

1 Like

Thanks a lot Roy! Also, for people wanting to use the setFromExternalPixels, notice that the last parameter should not be OF_IMAGE_COLOR, but the number of channels!! e.g.

m_image.getPixelsRef().setFromExternalPixels( m_data_ptr, m_width, m_height, 3 /*RGB*/ );
m_image.update();
1 Like