栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在二维numpy数组中定位值的特定“区域”?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在二维numpy数组中定位值的特定“区域”?

您可以使用简单的布尔条件找到满足截止要求的像素,然后使用

scipy.ndimage.label
scipy.ndimage.center_of_mass
查找相连的区域并计算其质心:

import numpy as npfrom scipy import ndimagefrom matplotlib import pyplot as plt# generate some lowpass-filtered noise as a test imagegen = 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.75blobs = img > 0.75# label connected regions that satisfy this conditionlabels, 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 cornerd = np.sqrt(r*r + c*c)# plotfig, 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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611153.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号