1

I need to change value for items in a numpy array on the basis of their neighbours values. More specifically, let's suppose that I have just 3 possible values for each item in a numpy representing an image. Let's suppose my numpy is the following one:

[[1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1],
 [1,1,1,2,1,1,1],
 [1,1,1,2,1,1,1],
 [1,1,1,1,1,1,1],
 [3,3,3,3,3,3,3],
 [3,3,3,3,3,3,3],
 [3,3,3,3,3,3,3]
]

What I want is: Since the size of group of contiguous items containing the value 2 in such example is less than (3 x 3) matrix, I need to assign them the value of neighbour items: in such case 1! Resulting numpy has to be

[[1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1],
 [1,1,1,**1**,1,1,1],
 [1,1,1,**1**,1,1,1],
 [1,1,1,1,1,1,1],
 [3,3,3,3,3,3,3],
 [3,3,3,3,3,3,3],
 [3,3,3,3,3,3,3]
]

What I would like to have is that the 'spurious' elements (only two cells containing the value 2 in an area with a predominance of 1 values) are eliminated and uniformed to the area in which they appear. I hope I have explained. Thanks for any information you can give me. Thanks a lot.

gazzella
  • 11
  • 1
  • What is your definition of "neighborhood" of the spurious items ? Especially in cases where the contiguous spurious items do not form a rectangle? Could you please edit your answer with such examples also, and clarify what the "neighborhood" should be? – fountainhead Nov 14 '20 at 22:32
  • Consider a 5x5 grid. Assume that its boundary cells contain `2` - that is, they form a nice closed "ring" of `2`s. Assume that the next inner ring has `1`s. This leaves the central cell. Let's assume that the central cell has a `2`. Should we now treat the central `2` as "spurious", since it is surrounded by the intermediate ring of `1`s, or should we treat the intermediate ring of `1`s as spurious since they are surrounded by the outer ring of `2`s (not to mention the central cell having another `2`) ? – fountainhead Nov 14 '20 at 22:44
  • yes, sure. You're right. My idea was that in case you reported me, the 'spurious' elements should be the ones containing the internal ring of 1, since sourrounded by a greater ring of containing 2. – gazzella Nov 14 '20 at 22:51

1 Answers1

1

In image processing this operations are called morphological filtering. In your case you can use an opening.

import numpy as np
from skimage.morphology.grey import opening
from skimage.morphology import square

a = np.array(
[[1,1,1,1,1,1,1],
 [1,1,1,1,1,1,1],
 [1,1,1,2,1,1,1],
 [1,1,1,2,1,1,1],
 [1,1,1,1,1,1,1],
 [3,3,3,3,3,3,3],
 [3,3,3,3,3,3,3],
 [3,3,3,3,3,3,3]
])

opening(a, square(3))

Out:

[[1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1]
 [3 3 3 3 3 3 3]
 [3 3 3 3 3 3 3]
 [3 3 3 3 3 3 3]]
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32