This code snippet:
import numpy as np
from skimage.measure import label, regionprops
image = np.array([[1, 1, 0], [1, 0, 0], [0, 0, 2]])
labels = label(image, background=0, connectivity=2)
props = regionprops(labels, image, cache=True)
print(image)
print(np.argmax([p.area for p in props]))
will print:
[[1 1 0]
[1 0 0]
[0 0 2]]
0
0
is an index of props
element with maximum value of area
property. Is there a more direct way of computing it without the need for creating a temporary array in np.argmax([p.area for p in props])
? It doesn't have to use NumPy.
CodePudding user response:
What about using regionprops_table
?
from skimage.measure import label, regionprops_table
labels = label(image, background=0, connectivity=2)
out = np.argmax(regionprops_table(labels, image, cache=True, properties=['area'])['area'])
Output: 0
CodePudding user response:
Mozway has given you a great solution. I answer here on how to find index of list element with maximum value of specific property
without creating a temporary array.
A straightforward method is use a for
loop:
maxid = -1
maxarea = -1
for i, p in enumerate(props):
if p.area > maxarea:
maxid, maxarea = i, p.area
This can be written in one line using functools.reduce
.
import functools
maxid, maxarea = functools.reduce(lambda res, i_p: (i_p[0], i_p[1].area) if i_p[1].area > res[1] else res, enumerate(props), (-1, -1))