﻿ python-如何在numpy 2d数组中选择唯一元素的所有位置,并用包围框包围它们？ - 代码日志

python-如何在numpy 2d数组中选择唯一元素的所有位置,并用包围框包围它们？

``````array([[1, 1, 2, 2],\
[1, 1, 2, 2],\
[3, 3, 4, 4],\
[3, 3, 4, 4]])
``````

``````1, (0,0),(1,1)
2, (0,2),(1,2)
3, (2,0),(3,1)
4, (2,2),(3,3)
``````

`````` array([[1, 0, 1, 2, 2],\
[1, 0, 1, 2, 2],\
[3, 0, 3, 4, 4],\
[3, 0, 3, 4, 4]])
``````

``````1, (0,0),(1,2)
2, (0,3),(1,4)
3, (2,0),(3,2)
4, (2,3),(3,4)
``````

``````import numpy as np

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

for val in np.unique(x):
rows, cols = np.where(x == val)
rowstart, rowstop = np.min(rows), np.max(rows)
colstart, colstop = np.min(cols), np.max(cols)
print val, (rowstart, colstart), (rowstop, colstop)
``````

find_objects重新调整切片对象的元组列表.老实说,如果您需要绑定框,这些可能正是您想要的.但是,打印出起始和终止指标看起来会有些混乱.

``````import numpy as np
import scipy.ndimage as ndimage

x = np.array([[1, 0, 1, 2, 2],
[1, 0, 1, 2, 2],
[3, 0, 3, 4, 4],
[3, 0, 3, 4, 4]])

for i, item in enumerate(ndimage.find_objects(x), start=1):
print i, item
``````

``````for i, item in enumerate(ndimage.find_objects(x), start=1):
print i, ':'
print x[item], '\n'
``````

``````    for i, (rowslice, colslice) in enumerate(ndimage.find_objects(x), start=1):
print i,
print (rowslice.start, rowslice.stop - 1),
print (colslice.start, colslice.stop - 1)
``````

``````import numpy as np
import scipy.ndimage as ndimage

x = np.array([[1.1, 0.0, 1.1, 0.9, 0.9],
[1.1, 0.0, 1.1, 0.9, 0.9],
[3.3, 0.0, 3.3, 4.4, 4.4],
[3.3, 0.0, 3.3, 4.4, 4.4]])
ignored_val = 0.0
labels = np.zeros(data.shape, dtype=np.int)

i = 1
for val in np.unique(x):
if val != ignored_val:
labels[x == val] = i
i += 1

# Now we can use the "labels" array as input to find_objects
for i, item in enumerate(ndimage.find_objects(labels), start=1):
print i, ':'
print x[item], '\n'
``````