Thursday, November 17, 2016

Background Subtraction

Since OpenCV 3, background subtraction by Java becomes possible.  After searching for one example without success, I decided to put out one myself.

The class I'd like use is BackgroundSubtractorMOG2.  The confusing part is that you cannot use its constructor to create an instance.  Video.createBackgroundSubtractorMOG2() is needed for this task.

1. Create an instance of BackgroundSubtractorMOG2.

  • BackgroundSubtractorMOG2 fgbg =Video.createBackgroundSubtractorMOG2();


2. Apply it to the incoming image.

  • fgbg.apply(mat, mask);

where mat is RGB image from a webcam, and mask is the output gray scale foreground mask

I also updated my ImageConvertor, so it can convert both three channel and one channel OpenCV Mat to BufferedImage for displaying.  Here is a screenshot of example: after waiting for a while so my office scene disappears from the mask, I put my hand in the view.

Top is mat, bottom is mask


The complete code listings is at https://github.com/huiyingShen/Java-Background-Subtraction