At the moment I use:
transparent // ClearAll
transparent[i_] :=
Module[{r, g, b, a},
{r, g, b} = ImageData /@ ColorSeparate[i, "RGB"];
a = Unitize[3. - (r + g + b)];
(Image /@ {r, g, b, a})~ColorCombine~"RGB"
]
Note: the function makes only perfectly white RGB pixels transparent and that is intended.
Update about first question:
ColorSeparate, ColorCombine can be eliminated by using Interleaving->False
transparent0 // ClearAll
transparent0[i_] :=
Module[{r, g, b, a},
{r, g, b} = ImageData[i, Interleaving -> False];
a = Unitize[3. - (r + g + b)];
Image[{r, g, b, a}, Interleaving -> False, ColorSpace -> "RGB"]
]
but performance is worse:
transparent0[img]; //Timing
(* ==> {0.6490372, Null} *)
What version of Mathematica are you using? In Mathematica 8 you could use SetAlphaChannel
. For example
transparent2[img_] := SetAlphaChannel[img, Binarize[ColorNegate[img], 0.]]
would set the alpha channel of all white pixels to 0 and all other pixels to 1. I tested this on
img = Image[Graphics3D[Sphere[], Background -> White], ImageSize -> 1000]
and the timings I get are
transparent2[img]; // Timing
(* ==> {0.10067, Null} *)
compared to the original code
transparent[img]; //Timing
(* ==> {0.202112, Null} *)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With