I need to label an already classified img. The problem being, the image is non binary and I need to count separately neighbouring patch of different value.
Considering the following dataset :
import numpy as np
data = np.zeros((6,6), dtype=np.uint16)
data[2:4, 2:4] = 10
data[4, 4] = 10
data[:2, :3] = 22
data[0, 5] = 22
data
>>>
array([[22, 22, 22, 0, 0, 22],
[22, 22, 22, 0, 0, 0],
[0, 0, 10, 10, 0, 0],
[0, 0, 10, 10, 0, 0],
[0, 0, 0, 0, 10, 0],
[0, 0, 0, 0, 0, 0]], dtype=uint16)
I would like to obtain (with an 8 neigbours structuring element) the following :
array([[1, 1, 1, 0, 0, 3],
[1, 1, 1, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 0, 0, 2, 0],
[0, 0, 0, 0, 0, 0]], dtype=uint16)
but using the scipy.label function I obtain a complete different result :
from scipy import ndimage as ndi
s = ndi.generate_binary_structure(2,2)
labeled_array, num_features = ndi.label(data, structure=s)
labeled_array
>>>
array([[1, 1, 1, 0, 0, 2],
[1, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0]], dtype=int16)
So is there a trick to separate patch of different value ?
Get a list of unique values
uvand then replace each unique value with its order number (first value with 0, second with 1 etc.)Example:
Result:
UPDATE I've seen you changed your data in the question. In this case it's no longer an already classified image because
data[0,5]can't be22if it's not linked with all the other22s.So in this case I guess you need to do the labelling for each unique entrie in data separately like so:
Data:
Result: