Getting pixel value from image

Hey guys,
I’m trying the get pixel value from a grayscale image. I am also trying to count the number of white pixels in that image. I understand that i have to use a nested for loop to go through the image and also use the getPixels function. However, i do not understand how i have to structure this. Could someone help me out?
thanks

Here is the snipet of code for finding white pixels in an image

  
  
  
void testApp::draw(){  
	ofSetColor(255, 255, 255);  
	myPicture.draw(0,0);  
	unsigned char * pixels = myPicture.getPixels();	  
	int counter = 0;  
	for(int i = 0; i < myPicture.width*myPicture.height; i++){		  
		if (pixels[i] > 250){  
			counter ++;  
		}  
	}  
	printf("num white pixels= %i \n", counter);	  
}  
  
  

1 Like

Have a look at the ImageLoadedExample that comes with the OF package.

  
  
	unsigned char * pixels = bikeIcon.getPixels();  
	int w = bikeIcon.width;  
	int h = bikeIcon.height;  
	for (int i = 0; i < w; i++){  
		for (int j = 0; j < h; j++){  
			int value = pixels[j * w + i];  
			float pct = 1 - (value / 255.0f);  
			ofCircle(i*10,500 + j*10,1 + 5*pct);		  
		}  
	}  
  

For colour images, you will need to use a slightly different index on the array:

  
  
	int w = myImage.width;  
	int h = myImage.height;  
	int type = myImage.type;  
	int bpp = myImage.bpp / 8;  
	unsigned char * pixels = myImage.getPixels();  
	  
	for (int i = 0; i < w; i++){  
		for (int j = 0; j < h; j++){  
			if(bpp >= 3){  
				float cRed = pixels[(j*w+i)*bpp+0];  
				float cGreen = pixels[(j*w+i)*bpp+1];  
				float cBlue = pixels[(j*w+i)*bpp+2];  
				if(bpp >= 4)  
					float cAlpha = pixels[(j*w+i)*bpp+3];  
			}  
			else if(bpp == 1){  
				float cGray = pixels[(j*w+i)];  
			}  
		}  
	}  
  

HTH!
-plong0

and be aware that the getPixels() returns the R,G,B values separate. (one pixel will return 3 indexes).

http://www.openframeworks.cc/documentat-…–getPixels