FaC*_*fee 4 python arrays numpy image-processing scipy
我正在使用numpy由101x101=10201值组成的2D 数组.这样的值的float类型和范围从0.0到1.0.数组有一个X,Y坐标系,它起源于左上角:因此,位置(0,0)在左上角,而位置(101,101)在右下角.
这就是2D数组的样子(只是一个摘录):
X,Y,Value
0,0,0.482
0,1,0.49
0,2,0.496
0,3,0.495
0,4,0.49
0,5,0.489
0,6,0.5
0,7,0.504
0,8,0.494
0,9,0.485
Run Code Online (Sandbox Code Playgroud)
我希望能够:
1)计算超过给定阈值的单元区域数(见下图),比如说0.3;
2)确定这些区域的视觉中心与具有坐标的左上角之间的距离(0,0).
怎么能在Python 2.7中完成?
这是一个2D数组的直观表示,突出显示了2个区域(颜色越深,值越高):
您可以使用简单的布尔条件找到哪些像素满足您的截止值,然后使用scipy.ndimage.label和scipy.ndimage.center_of_mass查找连接区域并计算其质心:
import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt
# generate some lowpass-filtered noise as a test image
gen = np.random.RandomState(0)
img = gen.poisson(2, size=(512, 512))
img = ndimage.gaussian_filter(img.astype(np.double), (30, 30))
img -= img.min()
img /= img.max()
# use a boolean condition to find where pixel values are > 0.75
blobs = img > 0.75
# label connected regions that satisfy this condition
labels, nlabels = ndimage.label(blobs)
# find their centres of mass. in this case I'm weighting by the pixel values in
# `img`, but you could also pass the boolean values in `blobs` to compute the
# unweighted centroids.
r, c = np.vstack(ndimage.center_of_mass(img, labels, np.arange(nlabels) + 1)).T
# find their distances from the top-left corner
d = np.sqrt(r*r + c*c)
# plot
fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))
ax[0].imshow(img)
ax[1].hold(True)
ax[1].imshow(np.ma.masked_array(labels, ~blobs), cmap=plt.cm.rainbow)
for ri, ci, di in zip(r, c, d):
ax[1].annotate('', xy=(0, 0), xytext=(ci, ri),
arrowprops={'arrowstyle':'<-', 'shrinkA':0})
ax[1].annotate('d=%.1f' % di, xy=(ci, ri), xytext=(0, -5),
textcoords='offset points', ha='center', va='top',
fontsize='x-large')
for aa in ax.flat:
aa.set_axis_off()
fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3017 次 |
| 最近记录: |