Python - NumPy - tuples as elements of an array

I am a senior CS specialist at a university working on a programming project for my Calc III course, including a decomposition with unique meanings. The idea is to convert an image of dimensions mxn into a matrix mxn, where each element is a tuple representing the color channels of the (r, g, b) pixels at the point (m, n). I use Python because it is the only language that I have really (well) taught so far.

From what I can say, Python usually doesn't like tuples as elements of an array. I did a little research myself and found a workaround, namely: pre-allocating the array as follows:

def image_to_array(): #converts an image to an array  
    aPic = loadPicture("zorak_color.gif")  
    ph = getHeight(aPic)  
    pw = getWidth(aPic)  
    anArray = zeros((ph,pw), dtype='O')  
    for h in range(ph):  
         for w in range(pw):             
            p = getPixel(aPic, w, h)  
            anArray[h][w] = (getRGB(p))  
    return anArray

This worked correctly for the first part of the assignment, which was just for converting the image into a matrix (without the involvement of linear algebra).

The SVD part, however, is where it gets harder. When I call the numpy svd built-in function using an array that I built from my image (where each element is a tuple), I get the following error:

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in -toplevel-
    svd(x)
  File "C:\Python24\Lib\site-packages\numpy\linalg\linalg.py", line 724, in svd
    a = _fastCopyAndTranspose(t, a)
  File "C:\Python24\Lib\site-packages\numpy\linalg\linalg.py", line 107, in _fastCopyAndTranspose
    cast_arrays = cast_arrays + (_fastCT(a.astype(type)),)
ValueError: setting an array element with a sequence.

This is the same error that I received initially, before I did some research, and found that I can pre-allocate my arrays so that the tuples are elements.

, , numPy, , ( , , ). , . ? , numPy ?

.

+5
2

, "O" (), . . SciPy.

-

a = zeros((ph,pw), dtype=(float,3))

, RGB 3 .

3d- ( ), a[n,m][k] z[n,m,k], k - .

, SVD 2d-, 3d-, linalg.svd(a). SVD, ( : R G B) .

, , , SVD "R" ( , ), - :

linalg.svd(a[:,:,1])
+7

, ph pw 3 numpy.

anArray = zeros((ph,pw,3))  
for h in range(ph):  
     for w in range(pw):             
        p = getPixel(aPic, w, h)  
        anArray[h][w] = getRGB(p)

, getRGB 3 .

+2

All Articles