# How can I detect and modify one area of an image while preserving the rest

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.

• Also, can you post what you have tried so far? Aug 5, 2013 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. Aug 5, 2013 at 6:51

## 2 Answers

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["http://i.stack.imgur.com/8uowA.png"], "GrayScale"]]];
mask = ColorNegate[Erosion[Closing[im, 18], 3]]
b = ImageMultiply[mask, 0];
ImageAdd[ColorCombine[{mask, b, b}], im]


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["http://i.stack.imgur.com/kJVmP.png"];
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]]