Updated answer: use the CV_LOAD_IMAGE_UNCHANGED flag to load all four channels (including Alpha) from the image. Then use mixChannels() and / or split() to separate the alpha channel from the others and set a threshold for it, as described below.
Very old answer:
OpenCV does not support alpha channel, only masking. If you want to read in PNG format with an alpha channel, first use imagemagick to extract the alpha channel:
convert input.png -channel Alpha -negate -separate input-mask.png
Then in OpenCV you can do the following:
Mat_<float> mask = imread("input-mask.png", 0); threshold(mask, mask, 254., 1., THRESH_BINARY);
... to get a real mask (which can be used as a mask matrix in OpenCV operations). Or you can use it in your own operations without a threshold. To apply the mask, it would be nice to expand it to three channels:
std::vector<Mat> marr(3, mask); Mat_<Vec<float, 3> > maskRGB; merge(marr, maskRGB);
After that you can check it like this:
imshow("Target", target); imshow("Mask", mask*255); imshow("Applied", target.mul(maskRGB)); waitKey();
Note. This is OpenCV 2.0 code.
ypnos
source share