Render layers separately and then combine in post-processing

Is there a way to render different layers and then combine them in post processing? What I’d like to do is have three layers. Two of the layers are essentially duplicates of each-other, but with different materials assigned to the objects. Then the third layer will simply be used as a mask to determine whether the first or second layer is shown in the final image. I can do this by rendering the 3 layers separately and compositing them in GIMP, but It’d be really nice if I could just do it all in Blender.

Is there a way to render different layers and then combine them in post processing?
That’s what the render layers and compositor are for.

Supply an example blend file clearly showing what you want to do

example.zip (84.5 KB)

In the final image I would like to see the layer with the blue cube only where the final image renders the sphere and everywhere else on the final image the layer with the red cube is rendered.

Here you are: example.blend (102 KB)

I created three render layers, one for each object. As the cubes were z-fighting for the shadows, I had to duplicate the lamp for it to affect only its own layer (so the the blue and red cubes have their own, independent lighting). Just for teh lulz, I also threw in the nodes needed to composite the three layers according to your instructions.

Have fun!

Awesome, thank you.