2
我使用蟒,与SciPy的,numpy的1D直方图等numpy的:基于二维像素欧几里得距离从中心
我想计算灰度图像的强度值的直方图,基于距离的像素到图像的质量中心。以下解决方案的工作,但速度很慢:
import matplotlib.pyplot as plt
from scipy import ndimage
import numpy as np
import math
# img is a 2-dimensionsl numpy array
img = np.random.rand(300, 300)
# center of mass of the pixels is easy to get
centerOfMass = np.array(list(ndimage.measurements.center_of_mass(img)))
# declare histogram buckets
histogram = np.zeros(100)
# declare histogram range, which is half the diagonal length of the image, enough in this case.
maxDist = len(img)/math.sqrt(2.0)
# size of the bucket might be less than the width of a pixel, which is fine.
bucketSize = maxDist/len(histogram)
# fill the histogram buckets
for i in range(len(img)):
for j in range(len(img[i])):
dist = np.linalg.norm(centerOfMass - np.array([i,j]))
if(dist/bucketSize < len(histogram)):
histogram[int(dist/bucketSize)] += img[i, j]
# plot the img array
plt.subplot(121)
imgplot = plt.imshow(img)
imgplot.set_cmap('hot')
plt.colorbar()
plt.draw()
# plot the histogram
plt.subplot(122)
plt.plot(histogram)
plt.draw()
plt.show()
正如我之前所说,这个工作,但速度很慢,因为你没有以这种方式在numpy的应该是双回路阵列。有没有更有效的方法来做同样的事情?我假设我需要在所有数组元素上应用一些函数,但我也需要索引坐标。我怎样才能做到这一点?目前,1kx1k图像需要几秒钟的时间,速度很慢。 。
更好的答案,然后我的。有趣的,但并不意外的回顾,np.histogram可以采取多维阵列。 – Daniel
@Ophion它需要你的一切行,但在处理之前它总是变平。 – Jaime
非常感谢你,我正在玩一系列的距离,因为它似乎是要走的路,但我无法让它工作。 –