Accessing raw image data (ofPixel) does not effect output

Hi!

My name is Steve. I’m new to programming and of. My first impressions are overwhelming! Thanks to everyone, who has contributed to this wonderful programming framework!

Everything worked smoothly so far. No, however, I am facing my first problem:

I work on Win 10, with VS 2017. I want to access raw pixel data, via ofPixels. Changes on raw data, however, don’t seem to effect the corresponding ofImage object. See the code as an example. It should set the red channel on all pixels to maximum. In the draw() - Function the image is outputed beside the original. They are the same. What didn’t I consider.

in ofApp.h:

ofImage image;
ofImage imageOrg; 

in ofApp.cpp:

void ofApp::setup(){

	image.loadImage("sunflower2.png");
	imageOrg.loadImage("sunflower2.png");

	int components; // number of color components
	int type =  image.getImageType();

	if (type == OF_IMAGE_COLOR) {
		components = 3;
	}
	if (type == OF_IMAGE_COLOR_ALPHA) {
		components = 4;
	}

	ofPixels data = image.getPixels();

	for (int y = 0; y < image.getWidth(); y++) {
		for (int x = 0; x < image.getHeight(); x++) {

			int i = components * (y * image.getWidth() + x);
			data[i] = 255; // set red-value to maximum
		}
	}
	image.update();
}

//--------------------------------------------------------------
void ofApp::update(){

}

//--------------------------------------------------------------
void ofApp::draw(){

	//Set up white background
	ofBackground(255, 255, 255);
	ofSetColor(255);

	imageOrg.draw(0, 0);
	image.draw(400, 0);

}

Thanks for any help!

Steve

Hi Steve,
I think it’s because you’re making a copy of the pixel data, instead of modifying the actual pixel-data itself.

By declaring an ofPixels you’re making an individual ofPixels-object, which has no knowledge of the ofImage.
The pixels from the ofImage are only copied to the ofPixels-object.

By using a pointer/address (I’m not realy good at the terminology here) like in the example below, you’re referencing to the actual ofPixels of the ofImage.
(You could also use image.setFromPixels(pixels), but would take time and resources for the copying).
I’ve also changed the reading-direction, since the raw pixel data is stored per horizontal line. I’m not sure if this is the same with each loaded image however.

// Example
image.load("testImage.png");
image.setImageType(OF_IMAGE_COLOR);
ofPixels &data = image.getPixels();
for(int y=0; y<image.getHeight(); y++){
	for(int x = 0; x<image.getWidth(); x++){
		int i = 3 * (x * image.getHeight() + y);
		data[i] = 255;
	}
}
image.update();

Best

2 Likes

Yes, this was in fact the problem! It works now.
Thanks a lot, @Jildert !

All these type issues, pointer, references, normal types, …, it’s driving me nuts!