Saving masked parts of an image using transparency


I’m trying to save only a part of an image (from a video grabber), to a
transparent png file. It would be nice if I could create a alpha transparent
png which I can ‘cut’ from a picture.

Maybe this picture will explain what I mean:

  • So at (1) I created a transparent png under which I show
    the webcam stream.
  • Than I want to use this mask I created (also a png with
    feathered corners) (2)
  • and save it in a transparent png (3).

Would it be best to create a new ofImage and set fill it
with pixeldata and using the alpha values of the mask (2) ?


maybe there is a faster way with opencv but this should work:

    // assumes the mask is a transparetn png image (4 channels)  
    ofImage mask;  
    ofImage imgOut;  
    imgOut.allocate(mask.width, mask.height, OF_IMAGE_COLOR_ALPHA);  
    unsigned char * pixelsSrc   = videoIn.getPixels();  
    unsigned char * pixelsMask  = mask.getPixels();  
    unsigned char * pixelsFinal = new unsigned char[mask.width*mask.height*4];  
    for( int i = 0; i < mask.width*mask.height; i++)  
        if( pixelsMask[i*4] == 0 )  
            pixelsFinal[i*4]    = pixelsSrc[ i*3 ];  
            pixelsFinal[i*4+1]  = pixelsSrc[ i*3+1 ];  
            pixelsFinal[i*4+2]  = pixelsSrc[ i*3+2 ];  
            pixelsFinal[i*4+3]  = 255;