2

这是我第一次处理多维数组,我在访问元素时遇到了问题。我正在尝试获取图片的红色像素,但只是数组中的前 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]
4

5 回答 5

3

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

r.flatten()[:8]

如果第一行少于 8 个像素,这将自动环绕。

于 2013-02-17T04:30:33.140 回答
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]
于 2013-02-17T04:35:01.500 回答
1

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

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

于 2013-02-17T04:39:59.800 回答
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替换using中的前 8 列hstack

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]])
于 2013-02-17T05:28:37.510 回答
0

编辑:至于 DSM 所指出的,OP 实际上是使用numpy array

我收回我的答案,因为 nneonneo 是正确的

于 2013-02-17T05:04:56.973 回答