My old post has been receiving lots of hits requesting for the source code of the background subtraction in this post. The code below is an improved implementation, much faster and less code. Please note that this method is excellent for the type of images where foreground and background object is contrasting. Additional image post-processing may be needed to remove small blobs.
var image= new Image<Bgr,byte>(filename);
// threshold values for each channel
var thresholds = new [] {new TRange<int>(70,255), new TRange<int>(0,255), new TRange<int>(0,255)};
Image<Gray, byte>[] grays = image.Convert<Lab, byte>().Split();
// threshold each channel
for (int i = 0; i < 3; i++)
{
grays[i]._ThresholdToZero(new Gray(thresholds [i].LowerValue));
grays[i]._ThresholdToZeroInv(new Gray(thresholds [i].UpperValue));
grays[i]._ThresholdBinary(new Gray(1), new Gray(255));
}
// merge the thresholded array of binary images above
var mask = grays[0].And(grays[1].And(grays[2]));
// result
var resultImage = image.Copy(mask);