本文介绍了获取高于特定值的二维数组中局部最大值的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
from PIL 导入图片将 numpy 导入为 np从 scipy.ndimage.filters 导入maximum_filter导入pylab# 图片(256 * 256 像素)包含我想要获取位置的亮点# 问题:数据在值 900 - 1000 附近有高背景im = Image.open('slice0000.png')数据 = np.array(im)# 据我所知,data == maximum_filter 给出了像素的真值# 是他们附近最亮的(这里是 10 * 10 像素)maxima = (data == maximum_filter(data,10))# 我怎样才能得到最大值,突出背景一定的值,比如说 500 ?
恐怕我不太了解 scipy.ndimage.filters.maximum_filter()
函数.有没有办法只在斑点内而不是在背景内获得像素坐标?
from PIL import Image
import numpy as np
from scipy.ndimage.filters import maximum_filter
import pylab
# the picture (256 * 256 pixels) contains bright spots of which I wanna get positions
# problem: data has high background around value 900 - 1000
im = Image.open('slice0000.png')
data = np.array(im)
# as far as I understand, data == maximum_filter gives True-value for pixels
# being the brightest in their neighborhood (here 10 * 10 pixels)
maxima = (data == maximum_filter(data,10))
# How can I get only maxima, outstanding the background a certain value, let's say 500 ?
I'm afraid I don't really understand the scipy.ndimage.filters.maximum_filter()
function. Is there a way to obtain pixel-coordinates only within the spots and not within the background?
http://i.stack.imgur.com/RImHW.png (16-bit grayscale picture, 256*256 pixels)
解决方案
import numpy as np
import scipy
import scipy.ndimage as ndimage
import scipy.ndimage.filters as filters
import matplotlib.pyplot as plt
fname = '/tmp/slice0000.png'
neighborhood_size = 5
threshold = 1500
data = scipy.misc.imread(fname)
data_max = filters.maximum_filter(data, neighborhood_size)
maxima = (data == data_max)
data_min = filters.minimum_filter(data, neighborhood_size)
diff = ((data_max - data_min) > threshold)
maxima[diff == 0] = 0
labeled, num_objects = ndimage.label(maxima)
slices = ndimage.find_objects(labeled)
x, y = [], []
for dy,dx in slices:
x_center = (dx.start + dx.stop - 1)/2
x.append(x_center)
y_center = (dy.start + dy.stop - 1)/2
y.append(y_center)
plt.imshow(data)
plt.savefig('/tmp/data.png', bbox_inches = 'tight')
plt.autoscale(False)
plt.plot(x,y, 'ro')
plt.savefig('/tmp/result.png', bbox_inches = 'tight')
Given data.png:
the above program yields result.png with threshold = 1500
. Lower the threshold
to pick up more local maxima:
References:
这篇关于获取高于特定值的二维数组中局部最大值的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!