Now to do all the channels.
Split the bayer pattern into four half-size images (red, green, green, blue)
Stack and sort these images so you have one image containing the brightest pixels of all the channels, one with the minimum and two in the middle.
Reconstruct the clipped values for the image of minimum values. This is your reference image.
However, it is possible that you are missing some details that are contained in the other channels, so we need to make a better reference image.
We are going to use the minimum image as a reference to reconstruct the clipped values in the next brightest image.
Find the difference between the reference image and the reconstruction candidate. Inpaint the pixels that were clipped in the candidate image on the difference image based on the closest unclipped values.
Add the difference image back to the reference image. We have now reconstructed the highlights on another image in the stack. Average the reference image and the new reconstructed image together to create a new reference image
Repeat this process for the remaining images in the stack. The last image will be the brightest one with the most clipped values.
You now have one grey scale reference image with the most details possible.
… will we ever reconstruct the highlights on the colour channels, what will become of the reference image, find out next time…