Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an image with a big black disk bounded by a white boundary in its center. The image contains some other stuff outside of the spot and its boundary. This stuff has colors which include both black and white. I wonder whether Mathematica can do either of the following:

  1. Find the position of all the points in the central disk
  2. Change the color of the central disk to red while preserving all the other parts of the image.

enter image description here

share|improve this question
Also, can you post what you have tried so far? – Teake Nutma Aug 5 '13 at 5:47
Most probably the answer is "yes." You can find a number of useful questions if you browse this list. If you upload an image somewhere and provide a link I will be happy to embed it in your question. – Mr.Wizard Aug 5 '13 at 6:51

You can use SelectComponents to select a big object whose convex perimeter is almost equal to the object perimeter. This gives you your central element

img = Import[""];
disk = SelectComponents[Binarize[ColorNegate[img]], 
  {"PerimeterLength", "ConvexPerimeterLength"}, #1 > 1000 && Abs[#1 - #2] < 500 &]

With this mask you can count the white pixels and get directly the number of points inside your object. The colouring is done by

ImageAdd[RemoveAlphaChannel[img], ImageMultiply[disk, Red]]

Mathematica graphics

share|improve this answer

One way is to locate the central portion using a Closing operation (which removes all the small white flecks in the background) and to then build back the desired image. One oddity of the OPs image is that it is and RGB image with an alpha channel (even though it looks like a grayscale), so the first line converts it to grayscale. The second line builds a mask that contains only the central object by doing the Closing. The third line builds an image b that is the same size but is all zeros. The final line creates the superposition of the original and the colored version.

im = First[ColorSeparate[ColorConvert[
     Import[""], "GrayScale"]]];
mask = ColorNegate[Erosion[Closing[im, 18], 3]]
b = ImageMultiply[mask, 0];
ImageAdd[ColorCombine[{mask, b, b}], im]

enter image description here

enter image description here

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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