访问数组Python中的元素

时间:2013-02-17 04:27:36

标签: python numpy

这是我第一次处理多维数组,而且访问元素时遇到问题。我试图得到图片的红色像素,但只是数组中的前8个元素。这是代码

import Image
import numpy as np

im = Image.open("C:\Users\Jones\Pictures\1.jpg")
pix = im.load() 

r, g, b = np.array(im).T
print r[0:8]

5 个答案:

答案 0 :(得分:3)

由于您正在处理图像,r是一个二维数组。要获得图像中的前8个像素,请尝试

r.flatten()[:8]

如果第一行的像素少于8个,则会自动回绕。

答案 1 :(得分:1)

你可以这样做:

r[0][:8]

但请注意,如果第一行的像素少于8个,则无法使用此功能。要解决这个问题,请执行以下操作:

from itertools import chain
r = list(chain.from_iterable(r))
r[:8]

或(如果您不想import整个模块):

r = [val for element in r for val in element]
r[:8]

答案 2 :(得分:1)

你想要所有的行吗?试试这个r[:,:8]

只想要第一排?试试这个r[0,:8]

答案 3 :(得分:1)

我认为这可能更简单。此示例使用随机矩阵(这将是您的r矩阵):

In [7]: from pylab import *                 # convention

In [8]: r = randint(0,10,(10,10))           # this is your image

In [9]: r
array([[7, 9, 5, 5, 6, 8, 1, 4, 3, 4],
       [5, 4, 4, 4, 2, 6, 2, 6, 4, 2],
       [1, 4, 9, 9, 2, 6, 1, 9, 0, 6],
       [5, 9, 0, 7, 9, 9, 5, 2, 0, 7],
       [8, 3, 3, 9, 0, 0, 5, 9, 2, 2],
       [5, 3, 7, 8, 8, 1, 6, 3, 2, 0],
       [0, 2, 5, 7, 0, 1, 0, 2, 1, 2],
       [4, 0, 4, 5, 9, 9, 3, 8, 3, 7],
       [4, 6, 9, 9, 5, 9, 3, 0, 5, 1],
       [6, 9, 9, 0, 3, 4, 9, 7, 9, 6]])

然后,提取前8列并做一些事情

In [17]: r_8 = r[:,:8]              # extract columns

In [18]: r_8
Out[18]: 
array([[7, 9, 5, 5, 6, 8, 1, 4],
       [5, 4, 4, 4, 2, 6, 2, 6],
       [1, 4, 9, 9, 2, 6, 1, 9],
       [5, 9, 0, 7, 9, 9, 5, 2],
       [8, 3, 3, 9, 0, 0, 5, 9],
       [5, 3, 7, 8, 8, 1, 6, 3],
       [0, 2, 5, 7, 0, 1, 0, 2],
       [4, 0, 4, 5, 9, 9, 3, 8],
       [4, 6, 9, 9, 5, 9, 3, 0],
       [6, 9, 9, 0, 3, 4, 9, 7]])

In [19]: r_8 = r_8 * 2              # do something

In [20]: r_8
Out[20]: 
array([[14, 18, 10, 10, 12, 16,  2,  8],
       [10,  8,  8,  8,  4, 12,  4, 12],
       [ 2,  8, 18, 18,  4, 12,  2, 18],
       [10, 18,  0, 14, 18, 18, 10,  4],
       [16,  6,  6, 18,  0,  0, 10, 18],
       [10,  6, 14, 16, 16,  2, 12,  6],
       [ 0,  4, 10, 14,  0,  2,  0,  4],
       [ 8,  0,  8, 10, 18, 18,  6, 16],
       [ 8, 12, 18, 18, 10, 18,  6,  0],
       [12, 18, 18,  0,  6,  8, 18, 14]])

现在,这就是诀窍。使用r替换hstack中的前8列:

In [21]: r = hstack((r_8, r[:,8:]))             # it replaces the FISRT 8 columns, note the indexing notation 

In [22]: r
Out[22]: 
array([[14, 18, 10, 10, 12, 16,  2,  8,  3,  4],    # it does not touch the last 2 columns
       [10,  8,  8,  8,  4, 12,  4, 12,  4,  2],
       [ 2,  8, 18, 18,  4, 12,  2, 18,  0,  6],
       [10, 18,  0, 14, 18, 18, 10,  4,  0,  7],
       [16,  6,  6, 18,  0,  0, 10, 18,  2,  2],
       [10,  6, 14, 16, 16,  2, 12,  6,  2,  0],
       [ 0,  4, 10, 14,  0,  2,  0,  4,  1,  2],
       [ 8,  0,  8, 10, 18, 18,  6, 16,  3,  7],
       [ 8, 12, 18, 18, 10, 18,  6,  0,  5,  1],
       [12, 18, 18,  0,  6,  8, 18, 14,  9,  6]])

答案 4 :(得分:0)

编辑:关于DSM指出的内容,OP实际上使用的是 numpy数组

我将我的答案收回为nonno的正确