The most efficient way to modify pixel data in ofImage?

I can’t figure out how to use ofImage::getPixels().

According to the reference, ofImage::getPixels() returns a raw pointer to the pixel data. So this code is supposed to draw a black image, but it draws the original image.

ofImage myImage;
myImage.load("apple.jpg");
ofPixels pix = myImage.getPixels();
for (int pi = 0; pi < pix.size(); pi++) {
	pix[pi] = 0;
}
myImage.update();
myImage.draw(0, 0);

When I check this in a debugger, I see the code is copying the data into a new instance of ofPixels instead of referring to the original data block.

I have to use setFromPixels() instead of update() to make this code work.

myImage.setFromPixels(pix);
myImage.draw(0, 0);

But this is a bit inefficient because it makes a copy of the whole data.

What is the correct way to

  • get pointer to the data in ofImage
  • modify some pixel data
  • and update?

Not sure about the data acces on your rams in this example. But you have to call update to send the updated pixels to the GPU for rendering. You will have to make a copy at this point unless you are working with shaders.

the problem is that when you do this:

ofPixels pix = myImage.getPixels();

you are making a copy of the pixels in ofImage so what you are modifying is that copy not the original pixels. you need to get a reference to the pixels in order to modify the original like:

ofPixels & pix = myImage.getPixels();

note the & after ofPixels

Aha, this is what I need.
I never used “reference variables” for years, and this might be why it did not come to my mind.

Thanks a lot.

(And thank you @underdoeg for your reply.)