Full width home advertisement

OpenCV

HTML

Post Page Advertisement [Top]

 In this post I am showing how the background of an image replaced with transparent background. Here the background is black color. The procedure includes the following.

Load and Convert color image to gray scale


    Mat src=imread("source.jpg",1);
    Mat dst,tmp,alpha;
    cvtColor(src,tmp,COLOR_BGR2GRAY);
OpenCV  Transparent  Background

Threshold the image to create alpha mask.


    threshold(tmp,alpha,50,255,THRESH_BINARY);

Split source image to separate RGB channel


    Mat rgb[3];
    split(src,rgb);

Now merge RGB channel and alpha to create new image


    Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
    merge(rgba,4,dst);
    imwrite("dst.png",dst);


Full Code


    Mat src=imread("img/1.jpg",1);
    Mat dst,tmp,alpha;

    cvtColor(src,tmp,COLOR_BGR2GRAY);
    threshold(tmp,alpha,50,255,THRESH_BINARY);
    imwrite("alpha.jpg",alpha);

    Mat rgb[3];
    split(src,rgb);

    Mat rgba[4]={rgb[0],rgb[1],rgb[2],alpha};
    merge(rgba,4,dst);
    imwrite("dst.png",dst);

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib