ValueError:矩阵未对齐

时间:2012-11-13 02:16:48

标签: python numpy linear-algebra slice matrix-multiplication

我应该写一个执行以下操作的for循环: 使用对应于最大n奇异值的奇异向量(Ur等列和VrT等行)创建与原始图像大小相同的新R,G和B矩阵(500 x 375)

这是我到目前为止所拥有的

from PIL import Image
from Image import new
from numpy import *
import numpy as np
from scipy.linalg import svd

r, g, b = im.split()
R = np.array(r.getdata())
R = np.asmatrix(R)
R = np.reshape(R, (375, 500), order = 'F')
G = np.array(g.getdata())
G = np.asmatrix(G)
G = np.reshape(G, (375, 500), order = 'F')
B = np.array(b.getdata())
B = np.asmatrix(B)
B = np.reshape(B, (375, 500), order = 'F')
Ur, Sr, VrT = svd(R.T, full_matrices=False)
Ug, Sg, VgT = svd(G.T, full_matrices=False)
Ub, Sb, VbT = svd(R.T, full_matrices=False)
R1 = np.dot(Ur, diag(Sr))
R1 = np.dot(R1, VrT)
G1 = np.dot(Ug, diag(Sg))
G1 = np.dot(G1, VgT)
B1 = np.dot(Ub, diag(Sb))
B1 = np.dot(B1, VbT)
R1 = np.around([R1])
G1 = np.around([G1])
B1 = np.around([B1])
R1 = np.uint8(R1)
G1 = np.uint8(G1)
B1 = np.uint8(B1)
R1 = R1.T
G1 = G1.T
B1 = B1.T
R1 = R1.flatten('F')
G1 = G1.flatten('F')
B1 = B1.flatten('F')
R1 = tuple(R1)
G1 = tuple(G1)
B1 = tuple(B1)
zipped = zip(R1,G1,B1)
newim = im.putdata(zipped,1,0)
im.show(newim)

for i in xrange(5):
N = array([200,100,50,10,1])
newUr = Ur[0:N[i], : ]
newSr = newSr[0:N[i]]
newVrT = VrT[ 0:N[i], :]
newUg = Ug[0:N[i], : ]
newSg = Sg[0:N[i]]
newVgT = VgT[ 0:N[i], :]
newUb = Ub[0:N[i], : ]
newSb = Sb[0:N[i]]
newVbT = VbT[ 0:N[i],:]
newR = dot(dot(newUr, diag(newSr), newVrT))
newG = dot(dot(newUg, diag(newSg), newVgT))
newB = dot(dot(newUb, diag(newSb), newVbT))
zipped = zip(newR,newG,newB)
newim = im.putdata(zipped,1,0)
im.show()
i = i+1

1 个答案:

答案 0 :(得分:0)

您可以使用Snp.argsort中找到n个最大值。例如,

In [31]: S = np.array([1,3,5,2,4,7])

In [32]: np.argsort(S)[-3:]
Out[32]: array([4, 2, 5])

In [33]: idx = np.argsort(S)[-3:]

In [34]: S[idx]
Out[34]: array([4, 5, 7])

import Image
import numpy as np
linalg = np.linalg
N = 10

def ngreatest(arr, n):
    idx = np.argsort(arr)[-n:]
    return idx

img = Image.open(filename).convert('RGB')
arr = np.asarray(img)
r, g, b = np.rollaxis(arr, axis = -1)

Ur, Sr, VrT = linalg.svd(r, full_matrices=False)
idx = ngreatest(Sr, N)
Sr = np.diag(Sr[idx])
VrT = VrT[idx]
Ur = Ur[:,idx]

print(Ur.shape, Sr.shape, VrT.shape)