Let's take a sample image

enter image description here

Now I want to make transparent all the white areas of the image, so as to be able to copy/paste it above text

enter image description here

After the copy/paste only the color parts (non-white) of the figure should be covering the text.

I use version 9.0 of Mathematica.

Any suggestions?

  • $\begingroup$ img = Import["https://i.stack.imgur.com/JLncI.png"], Export["transparent.png", SetAlphaChannel[img, 1 - ColorSeparate[img][[1]]]] seems to work. But it's not going to be generalizable to more complex images... Although, having just seen @C.E.'s answer, RemoveBackground seems like the right way to go in this case. $\endgroup$ – aardvark2012 Nov 26 '17 at 11:11
  • $\begingroup$ @aardvark2012 When I run your code I get the following error message SetAlphaChannel::invalpha: Expecting an image or a number between 0 and 1 for the alpha channel specification instead of 1 $\endgroup$ – Vaggelis_Z Nov 26 '17 at 11:22
  • $\begingroup$ What does 1 - ColorSeparate[img][[1]] give you? It gives me an image that I use as a mask... albeit a pretty hacky one. $\endgroup$ – aardvark2012 Nov 26 '17 at 11:37
  • $\begingroup$ @aardvark2012 When I run 1 - ColorSeparate[img][[1]] I get 1 - the image in black and white. $\endgroup$ – Vaggelis_Z Nov 26 '17 at 11:41
  • $\begingroup$ So SetAlphaChannel should be using that image as the mask... no idea what's going on there and why the error is appearing (it doesn't for me). But RemoveBackground seems to be working for you now, so I'd stick with that. $\endgroup$ – aardvark2012 Nov 26 '17 at 11:45

There are two ways:

  1. Use RemoveBackground[img, {"Background", White}]
  2. Use SetAlphaChannel together with a mask

How to generate the mask would depend on the image. Binarize works in this case.

  • $\begingroup$ Could you be a little bit more specific, providing an example? $\endgroup$ – Vaggelis_Z Nov 26 '17 at 11:02
  • 1
    $\begingroup$ @Vaggelis_Z Yes, if you are more specific about what you don't understand. A general question will get a general answer, whereas a very specific question will get a very specific answer. $\endgroup$ – C. E. Nov 26 '17 at 11:03
  • $\begingroup$ When I use RemoveBackground[img, {"Background", White}] the exported JPEG image is not transparent, $\endgroup$ – Vaggelis_Z Nov 26 '17 at 11:21
  • 2
    $\begingroup$ Afaik, JPEGs don't support transparency. Try as PNG? $\endgroup$ – aardvark2012 Nov 26 '17 at 11:35
  • $\begingroup$ @aardvark2012 Yes, you are absolutely right! The PNG is indeed transparent. $\endgroup$ – Vaggelis_Z Nov 26 '17 at 11:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.