RBG data from ofImage

I am trying to pull RGB data from a picture I loaded. It will pull data from random pixels. I have done this in processing just not sure how to do it in OF.

try this…

  
  
ofImage myImage;  
myImage.loadImage("somePicture.jpg");  
unsigned char* pixels = myImage.getPixels();  
int width = myImage.width;  
int height = myImage.height;  
int bpp = myImage.bpp / 8; // bits per pixel / 8 = bytes per pixel (if RGB, 3; if RGBA, 4; if GrayScale, 1)  
  
for(int y = 0; y < height; y++){  
  for(int x = 0; x < width; x++){  
    // loop the components...   
    // colour (bpp >= 3): 0 = red, 1 = green, 2 = blue, 4 = alpha  
    // grayscale (bpp == 1): 0 = value  
    for(int b = 0; b < bpp; b++){  
      myColour[b] = pixels[(y*width+x)*bpp+b];  
    }  
  
    // or do something like...  
    if(bpp > 1){  
      // RGB  
      myColour.r = pixels[(y*width+x)*bpp+0];  
      myColour.g = pixels[(y*width+x)*bpp+1];  
      myColour.b = pixels[(y*width+x)*bpp+2];  
      if(bpp > 3){  
        // RGBA  
        myColour.a = pixels[(y*width+x)*bpp+3];  
      }  
    }  
    else{  
      // grayscale  
      myColour.r = myColour.g = myColour.b = pixels[(y*width+x)];  
    }  
  }  
}  
  

HTH

What is myColour delcared as?

myColour would be defined as whatever you want to store your RGB values in… I mostly just used it to illustrate how you can obtain the RGB values for pixels in your image.

I put in two different approaches… one that loops on an arbitrary number of bytes/pixel (ie. could be RGB, RGBA, or Grayscale)… and one that accesses the pixel bytes directly.

You’ll want to choose one of those approaches (based on what image type you are working with) and then replace myColour with whatever variable you are storing your data from.

The main thing to get here is this is how you access RGB values for arbitrary x, y in an image:

  
  
      myColour.r = pixels[(y*width+x)*bpp+0];   
      myColour.g = pixels[(y*width+x)*bpp+1];   
      myColour.b = pixels[(y*width+x)*bpp+2];  
  

Doesn’t matter what myColour is… just replace it with your own variable.

I wound up doing this and it worked

  
  
void testApp::setup(){	   
	ofBackground(0, 0, 0);   
	ofSetBackgroundAuto(false);  
	ofEnableAlphaBlending();  
	AtomPrimative.loadImage("images/IronMetal.png");  
	myPixels = AtomPrimative.getPixels();  
}  
  
void testApp::draw(){  
	int width = AtomPrimative.width;  
	int height = AtomPrimative.height;  
	x=ofRandom(0,width);  
	y=ofRandom(0,height);  
	int colorIndex = y*(AtomPrimative.width*4)+x*4;	  
ofSetColor(myPixels[colorIndex],myPixels[colorIndex+1],myPixels[colorIndex+2],myPixels[colorIndex+3]);   
	ofRect(x,y,8,8);  
}