6
$\begingroup$

I want to extract a part of an image. For example, let's start with something like the following image:

enter image description here

I would like to apply some image processing to get this result:

enter image description here

I have tried to manipulate Graphics[Disk] and the image using ImageAdd but it looks like the Graphics[Disk] is a box that contains a disk, so adding the Mathematica logo image to the Disk outputs a white box.

$\endgroup$
0

1 Answer 1

10
$\begingroup$

Here is one way:

extractAnnulus[image_, {r1_, r2_}] := Module[{mask},
  mask = Rasterize[Graphics[
     {White, Disk[{0, 0}, r2], Black, Disk[{0, 0}, r1]},
     PlotRange -> 1,
     Background -> Black,
     ImageSize -> ImageDimensions[image]
     ],
    ImageResolution -> 72 (* Necessary as of Mathematica 12.1 *)
    ];
  ImageAdd[ImageMultiply[image, mask], ColorNegate[mask]]
  ]

img = Import["https://i.sstatic.net/paxJ9.png"];
extractAnnulus[img, {0.4, 0.6}]

Mathematica graphics

$\endgroup$
8
  • $\begingroup$ excellent!! Thank you so much. $\endgroup$
    – JMarc
    Commented Sep 30, 2015 at 3:34
  • $\begingroup$ BTW, I was initially confused, but looks like your r1 and r2 are a %age of the image size..right? $\endgroup$
    – JMarc
    Commented Sep 30, 2015 at 3:49
  • $\begingroup$ @JMarc Yes, I set PlotRange to one which means that zero is the top/left edges of the mask (a graphics object), and 1 is the bottom/right edges of the mask. i.e. I create a coordinate system where all coordinates are between 0 and 1. Then I specify, using ImageSize, that the corresponding image of this graphics object should have the same size as the image we are putting the mask over. This is actually useful to understand, because this approach breaks if the aspect ratio of the image is not square, then the aspect ratio has to be taken into account when creating the mask. $\endgroup$
    – C. E.
    Commented Sep 30, 2015 at 10:29
  • $\begingroup$ Does not work for me in 12.1. There is an additional black ring. $\endgroup$
    – Natas
    Commented Aug 12, 2020 at 12:36
  • $\begingroup$ @Natas Thank you for notifying me about this. I don't know yet why the example in my original answer cannot be reproduced but I have now provided a work-around. $\endgroup$
    – C. E.
    Commented Aug 14, 2020 at 0:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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