how to draw webcam image with an opacity?

I’m trying to figure out how to draw a webcam image to the screen (ofVideoGrabber) with an opacity/alpha setting so it’s somewhat transparent. From reading in the forum I came upon the idea of copying the incoming pixels into a larger array that has room for the alpha channel. I tweaked the movieGrabber example with this in mind but it’s not making any different in the resulting image (it looks the same as the original):

  
//--------------------------------------------------------------  
void testApp::setup(){  
	  
	camWidth 		= 320;	// try to grab at this size.   
	camHeight 		= 240;  
	  
	vidGrabber.setVerbose(true);  
	vidGrabber.initGrabber(camWidth,camHeight);  
	  
	videoAlpha 	= new unsigned char[camWidth*camHeight*4];  
	videoTexture.allocate(camWidth,camHeight, GL_RGBA);	  
}  
  
  
//--------------------------------------------------------------  
void testApp::update(){  
	  
	ofBackground(100,100,100);  
	  
	vidGrabber.grabFrame();  
	  
	if (vidGrabber.isFrameNew()){  
		int totalPixels = camWidth*camHeight;  
		unsigned char * pixels = vidGrabber.getPixels();  
		for (int i = 0; i < totalPixels; i++){  
			videoAlpha[i*4] = pixels[i*3];  
            videoAlpha[i*4+1] = pixels[i*3+1];  
            videoAlpha[i*4+2] = pixels[i*3+2];  
            videoAlpha[i*4+3] = 128;  
		}  
		videoTexture.loadData(videoAlpha, camWidth,camHeight, GL_RGBA);  
	}  
  
}  
  
//--------------------------------------------------------------  
void testApp::draw(){  
	ofSetHexColor(0xffffff);  
	vidGrabber.draw(20,20);  
	videoTexture.draw(20+camWidth,20,camWidth,camHeight);  
}  

What am I missing? Is there a way to do this, and if so, is this the best way?

thx!

ah, figured it out. i need a call to ofEnableAlphaBlending(). apparently it’s turned off by default. still interested in whether there’s a better/more efficient way to do this if anyone has that knowledge.

You can do it with a GLSL shader, but that gets tricky if you’re not used to using them. Otherwise, no, there really isn’t a simpler way.

If all you want to do is make the entire texture the same opacity, which it looks like you’re doing by setting the new alpha byte to 128, then the easiest way is:

  
  
ofEnableAlphaBlending();  
ofSetColor(255,255,255,128);  
vidGrabber.draw(0,0);  
  

No need to add an alpha channel per-pixel if all you need is a global alpha value for whatever you’re drawing.

nice, even easier. thanks Tim!

Here is an example of how to mask one image with another using a shader:
https://github.com/Flightphase/ofxAlphaMask

It works with webcams as well!