改写别人项目,但是结果图片不尽人意,结果如下:

这是一个原图的一个分量,明显看到歪了,正确的应该是正的黑白图,原图:

以下是相关代码,我就贴一些相关的,不然代码太多太繁琐,最后cv.imshow(m)结果就是我的歪图:
def computeKernel(mat, nRowSamples, nColSamples, hx, hy):
if nRowSamples > mat.shape[0] or nColSamples > mat.shape[1]:
raise ValueError("Number of samples per row and col must be <= that of image.")
nPixels = mat.size
selected, rest = samplePixels(mat.shape[0], mat.shape[1], nRowSamples, nColSamples)
nSamples = len(selected)
Ka = np.zeros((nSamples, nSamples))
Kab = np.zeros((nSamples, nPixels - nSamples))
photometricWeight = 1.0 / (hy * hy)
spatialWeight = 1.0 / (hx * hx)
for i in range(nSamples):
# Ka
p1 = selected[i]
for j in range(i, nSamples):
val = negativeWeightedDistance(mat, p1, selected[j], spatialWeight, photometricWeight)
Ka[i, j] = val
Ka[j, i] = val
# Kab
for j in range(len(rest)):
Kab[i, j] = negativeWeightedDistance(mat, p1, rest[j], spatialWeight, photometricWeight)
Ka = np.exp(Ka)
Kab = np.exp(Kab)
if (Ka.transpose() == Ka).all():
print("Ka is symmetric")
else:
print("Ka is NOT symmetric")
P = np.zeros((nPixels,), dtype=np.int32)
for i in range(nSamples):
p = selected[i]
P[i] = to1DIndex(p[0], p[1], mat.shape[1])
for j in range(len(rest)):
p = rest[j]
P[j + nSamples] = to1DIndex(p[0], p[1], mat.shape[1])
return P, Ka, Kab
pass
def eigen2opencv(v, nrows, ncols):
mat = np.array(v).reshape((nrows, ncols))
return mat.copy()
pass
def rescaleForVisualization(mat):
mat = np.float32(mat)
minVal, maxVal, _, _ = cv2.minMaxLoc(mat)
rescaledMat = (mat - minVal) / (maxVal - minVal) * 255
return rescaledMat.astype(np.uint8)
pass
def trainFilter(self, channel, nRowSamples, nColSamples, hx, hy, nSinkhornIter, nEigenVectors):
# implementation of the filter training algorithm
# ...
print("Computing kernel")
P, Ka, Kab = computeKernel(channel, nRowSamples, nColSamples, hx, hy)
print("Nystrom approximation")
eigvals, phi = nystromApproximation(Ka, Kab)
print("Sinkhorn")
Wa, Wab = sinkhorn(phi, eigvals, nSinkhornIter)
print("Orthogonalize")
eigvecs, eigvals = orthogonalize(Wa, Wab, nEigenVectors,EPS)
# Permute values back into correct position
#eigvecs = np.dot(P, eigvecs)
#eigvecs2 = np.empty((0, eigvecs.shape[1]))
#for i in range(P.size):
#row_to_add = eigvecs[P[i], :]
#eigvecs2 = np.vstack((eigvecs2, row_to_add))
eigvecs2=np.take(eigvecs,P,axis=0)
#eigvecs2=eigvecs
for i in range(min(nEigenVectors, 5)):
v = eigvecs2[:,i]
print("Eigvec ", i, " eigval: ", eigvals[i], " minCoeff: ", np.min(v), " maxCoeff: ", np.max(v))
m = eigen2opencv(v, channel.shape[0], channel.shape[1])
m = rescaleForVisualization(m)
m = cv2.convertScaleAbs(m)
cv2.imshow("image" + str(i), m)
return eigvecs2,eigvals
pass