The fastest way to create a transparent image in Mathematica 8 or higher?

I am currently using:

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" ] 
  • Is there a way to play with the form of what ImageData returns to exclude ColorSeparate / ColorCombine in the above?
  • Are there any improvements or completely different methods that you could come up with so quickly or faster than the above?

Note: the function only makes perfectly white RGB pixels transparent and intended.

Update the first question:

ColorSeparate, ColorCombine can be eliminated 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} *) 
+4
source share
1 answer

What version of Mathematica are you using? In Mathematica 8, you can use SetAlphaChannel . for instance

 transparent2[img_] := SetAlphaChannel[img, Binarize[ColorNegate[img], 0.]] 

will 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 timers that I get

 transparent2[img]; // Timing (* ==> {0.10067, Null} *) 

compared to the source code

 transparent[img]; //Timing (* ==> {0.202112, Null} *) 
+10
source

Source: https://habr.com/ru/post/1385678/


All Articles