我创建了一个类,向其中传递图像(2D 数组,1280x720)。它应该迭代,寻找最高值:
import bumpy as np
class myCv:
def maxIntLoc(self,image):
intensity = image[0,0] #columns, rows
coordinates = (0,0)
for y in xrange(0,len(image)):
for x in xrange(0,len(image[0])):
if np.all(image[x,y] > intensity):
intensity = image[x,y]
coordinates = (x,y)
return (intensity,coordinates)
但是当我运行它时,我收到错误:
if np.all(image[x,y] > intensity):
IndexError: index 720 is out of bounds for axis 0 with size 720
任何帮助都会很棒,因为我是 Python 新手。
谢谢, 肖恩
最佳答案
无论您遇到的索引错误如何(其他人已解决该错误),迭代像素/体素都不是操作图像的有效方法。这个问题在多维图像中变得尤其明显,您面临 curse of dimensionality 。
正确的方法是在支持向量化的编程语言(例如 Python、Julia、MATLAB)中使用向量化。通过这种方法,您将更有效地(并且速度快数千倍)获得您正在寻找的结果。 Click here了解有关矢量化(又名数组编程)的更多信息。在Python中,这可以使用生成器来实现,生成器不适合图像,因为它们在调用之前不会真正产生结果;或使用 NumPy 数组。
这是一个例子:
通过矢量化屏蔽图像矩阵
from numpy.random import randint
from matplotlib.pyplot import figure, imshow, title, grid, show
def mask_img(img, thresh, replacement):
# Copy of the image for masking. Use of |.copy()| is essential to
# prevent memory mapping.
masked = initial_image.copy()
# Replacement is the value to replace anything that
# (in this case) is bellow the threshold.
masked[initial_image<thresh] = replacement # Mask using vectorisation methods.
return masked
# Initial image to be masked (arbitrary example here).
# In this example, we assign a 100 x 100 matrix of random integers
# between 1 and 256 as our sample image.
initial_image = randint(0, 256, [100, 100])
threshold = 150 # Threshold
# Masking process.
masked_image = mask_img(initial_image, threshold, 0)
# Plots.
fig = figure(figsize=[16,9])
fig.add_subplot(121)
imshow(initial_image, interpolation='None', cmap='gray')
title('Initial image')
grid('off')
fig.add_subplot(122)
imshow(masked_image, interpolation='None', cmap='gray')
title('Masked image')
grid('off')
show()
返回结果:
当然,您可以将 mask 过程(函数)放入循环中以对一批图像执行此操作。您也可以修改索引并在 3D、4D(例如 MRI)或 5D(例如 CAT 扫描)图像上执行此操作,而无需迭代每个单独的像素或体素。
希望这有帮助。
关于Python索引错误: Out of bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980446/