How can I change the intensities of a certain pixel in an image along with 3*3 surrounding neighbor pixels?

1 view (last 30 days)
Lets say I have a image(matrix) as following:
a =
1 1 1 1 1
1 1 1 1 1
1 2 2 2 1
1 2 0 2 1
1 2 2 2 1
1 1 1 1 1
1 1 1 1 1
Finding that 0 in the middle and changing it is easy. I can do this :
a(a==0)=4;
and the result will be this:
a =
1 1 1 1 1
1 1 1 1 1
1 2 2 2 1
1 2 4 2 1
1 2 2 2 1
1 1 1 1 1
1 1 1 1 1
Now I want a code that can find the zero, convert that zero to 4, and also convert the 3*3 neighbors of zero to 4 as well. So after the code that you're suggesting, my output should look something like this:
b =
1 1 1 1 1
1 1 1 1 1
1 4 4 4 1
1 4 4 4 1
1 4 4 4 1
1 1 1 1 1
1 1 1 1 1
thanks in advance, Sina

Accepted Answer

Matt J
Matt J on 21 Sep 2016
a( imdilate(a==0, true(3)) ) = 4;
  3 Comments

Sign in to comment.

More Answers (1)

Adam
Adam on 21 Sep 2016
[x, y] = find( a == 0 );
a( x-1:x+1, y-1:y+1 ) = 4;
Obviously you would need to deal with when you are on the border and there is no x-1 or y+1 or whatever, but that is easy enough for you to adapt.
  1 Comment
Matt J
Matt J on 21 Sep 2016
Changoleon commented:
Adam,
Fast and accurate answer. Thanks you. I just realized that I need to change my values circularly which is impossible to make a perfect circle inside a matrix ( since you can not cover half of an element). How to change it so it look like a hexagon or octagon?

Sign in to comment.

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!