So you already got the mask for foreground,
then,
- Create alpha channel with above mask.
- Split the original image in to three single channel.
- Create the final result by merging three single channel and alpha(BGRA order).
See similar thread with example code here.