问题
I am getting a bit confused with the flags that cv::imread
takes.
My goal is to load images that have an alpha channel with this alpha channel (i.e. as CV_8UC4
). At the same time I want to load them always with a depth of 8bit.
First of all I tried using the following:
cv::imread(/*path*/, cv::IMREAD_COLOR);
This strips the alpha channel and returns an 8bit image. For transparent TIFs everything looks kind of right, just the transparent parts are black. For transparent PNGs, hovever, it looks completely wrong.
Next thing I tried was:
cv::imread(/*path*/, cv::IMREAD_ANYCOLOR);
The result was exactly the same as with cv::IMREAD_COLOR
. Next try:
cv::imread(/*path*/, cv::IMREAD_ANYCOLOR | cv::IMREAD_ANYDEPTH);
The alpha channels are still not there, but now the image's original depth is kept.
Then I tried:
cv::imread(/*path*/, cv::IMREAD_UNCHANGED);
This then worked also for the PNG images. However, now the bit depth of the image is kept and not converted to 8bit. This means I'll have to convert it in an additional step. I suspect that this might not be super efficient.
I also had a look at the descriptions of the flags in the OpenCV documentation. There it says:
IMREAD_UNCHANGED
If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
IMREAD_GRAYSCALE
If set, always convert image to the single channel grayscale image.
IMREAD_COLOR
If set, always convert image to the 3 channel BGR color image.
IMREAD_ANYDEPTH
If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
IMREAD_ANYCOLOR
If set, the image is read in any possible color format.
So apparently only IMREAD_UNCHANGED
supports alpha channels at all. But what is IMREAD_ANYCOLOR
there for if I can't read a four-channel image with it?
Is there any way of loading an image with an alpha channel converted to 8bit depth?
Another thing seems rather strange to me: When I use the option IMREAD_UNCHANGED
and read an rgb image with alpha channel, the result seems to be RGBA. If I read an rgb image without alpha channel, the format seems to be BGR. Why is the ordering of the channels different? I thought OpenCV always uses a BGR ordering.
Here is an example of what a PNG with alpha channel looks like when it's coorecty loaded and when it's incorrectly loaded:
来源:https://stackoverflow.com/questions/39268301/opencv-load-image-with-alpha-channel-but-8bit-depth