Python索引器:超出范围

Python索引器:超出范围,python,python-2.7,numpy,Python,Python 2.7,Numpy,我创建了一个类,我传递了它的一个图像(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 xrang

我创建了一个类,我传递了它的一个图像(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新手

谢谢,
Shaun

在python中,与大多数编程语言一样,索引从
0
开始

因此,您只能访问从
0
719
的像素


使用调试打印检查
len(image)
len(image[0])
是否确实返回1280和720。

不管您遇到的索引错误(其他人已经解决了这个问题),通过像素/体素进行迭代都不是处理图像的有效方法。这一问题在多维图像中变得尤为明显,因为在多维图像中,你面对的是现实

正确的方法是在支持向量化的编程语言(例如Python、Julia、MATLAB)中使用向量化。通过这种方法,您将更高效地(而且速度快数千倍)实现所需的结果。了解更多有关矢量化(也称为数组编程)的信息。在Python中,这可以通过使用生成器来实现,生成器不适用于图像,因为它们在调用之前不会真正生成结果;或者使用
NumPy
数组

以下是一个例子:

矢量化掩模图像矩阵
来自numpy.random import randint
从matplotlib.pyplot导入图形、imshow、标题、网格、显示
def面罩img(img、脱粒、更换):
#用于遮罩的图像副本。使用|.copy()|对于
#防止内存映射。
蒙版=初始图像。复制()
#替换是指替换任何
#(在这种情况下)低于阈值。

蒙版[初始图像应该是
图像[x,y]
图像[y,x]
?你为什么要遍历整个图像?你考虑过改用矢量化吗?@PouriaHadjibagheri谢谢你的评论,我现在正在研究矢量化。我正在为你写一个例子。请稍等几分钟。:)非常欢迎。它让生活更轻松(更快)用于分析图像。顺便说一下,如果要将现有变量转换为向量,可以使用
numpy.array
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()