Python AttributeError: 'numpy.ndarray' 对象没有属性 'append':图像处理示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25012948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AttributeError: 'numpy.ndarray' object has no attribute 'append':Image processing example
提问by DimKoim
I will first explain what I want to do. I have an image and I want to store the pixel values for a specific ROI. For that reason I implement the following loop(found in another topic of the site):
我将首先说明我想做什么。我有一个图像,我想存储特定 ROI 的像素值。出于这个原因,我实现了以下循环(在站点的另一个主题中找到):
pixels = im.load()
all_pixels = []
for x in range(SpecificWidth):
for y in range(SpecificHeight):
cpixel = pixels[x, y]
all_pixels.append(cpixel)
However, it does not return a SpecificwidthXSpecificHeight matrix but one of length as much as the values. Because I want to keep the size of the matrix of the ROI I implement the following loop(much the same with the previous):
但是,它不会返回一个 SpecificwidthXSpecificHeight 矩阵,而是一个长度与值一样多的矩阵。因为我想保持 ROI 矩阵的大小,所以我实现了以下循环(与之前的大致相同):
array=np.array(all_pixels)
roi_pixels = np.zeros((SpecificWidth,SpecificHeight))
for i in range(0,array.shape[0],width):
c_roi_pixels=all_pixels[i]
roi_pixels.append(c_roi_pixels)
And I have the error as it mentioned in the title.
我有标题中提到的错误。
采纳答案by ali_m
@RolandSmith is absolutely right about the cause of the error message you're seeing. A much more efficient way to achieve what you're trying to do is to convert the whole image to a numpy array, then use slice indexing to get the pixels corresponding to your ROI:
@RolandSmith 关于您看到的错误消息的原因是完全正确的。实现您想要做的事情的一种更有效的方法是将整个图像转换为一个 numpy 数组,然后使用切片索引来获取与您的 ROI 对应的像素:
# convert the image to a numpy array
allpix = np.array(im)
# array of zeros to hold the ROI pixels
roipix = np.zeros_like(allpix)
# copy the ROI region using slice indexing
roipix[:SpecificHeight, :SpecificWidth] = allpix[:SpecificHeight, :SpecificWidth]
回答by Roland Smith
In numpy, appendis a function, not a method.
在 numpy 中,append是一个函数,而不是一个方法。
So you should use e.g:
所以你应该使用例如:
roi_pixels = np.append(roi_pixels, c_roi_pixels)
Note that the appendfunction creates and returns a copy! It does not modify the original.
请注意,该append函数会创建并返回一个副本!它不会修改原始文件。

