Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to create a transparent image in Mathematica 8 or above?

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"
  ]
  1. Is there a way to play with the shape of what ImageData returns to eliminate ColorSeparate / ColorCombine in the above?
  2. Are there improvements or wholly other methods you could come up with that are as fast as or faster than the above?

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} *)
like image 216
Cetin Sert Avatar asked Dec 28 '22 09:12

Cetin Sert


1 Answers

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} *)
like image 89
Heike Avatar answered Jan 31 '23 00:01

Heike