How to convert a 4-channel image to 3-channel image in an elegant way?
The second example from RemoveAlphaChannel
:
- Remove opacity by blending with a white background:
img2 = RemoveAlphaChannel[img, White]
ImageChannels /@ {img, img2}
{4, 3}
ColorSeparate /@ {img, img2} // Grid
Row[{Labeled[Framed@AlphaChannel@img, "img", Top],
Labeled[Framed@AlphaChannel@img2, "img2", Top]}]
@kglr 's solution is very convenient and powerful. However RemoveAlphaChannel[#, colorname]&
does not work for all cases. So I spent some time searching in the web forimage channels andfound the principle of the alpha channel.
Based on that, I get the following solution which can be used for other cases(different images with different alpha channels).
reduceImageChannels[img_] :=
Map[Most,
Map[(#*#[[4]] + 1*(1 - #[[4]])) &,
(Flatten[ImageData@img, 1])]] // Partition[#, First@ImageDimensions[img]] & // Image
Let's check it,
img = Import @ "https://i.stack.imgur.com/XvzDc.png"
img2 = reduceImageChannels@img
ImageChannels@img2
3
It given me the image exactly what I want!