我有一个自定义函数来计算图像的两个像素(表示图形上的节点)之间的权重
function [weight] = getWeight(a,b,img, r, L)
ac = num2cell(a);
bc = num2cell(b);
imgint1 = img(sub2ind(size(img),ac{:}));
imgint2 = img(sub2ind(size(img),bc{:}));
weight = (sum((a - b) .^ 2) + (r^2/L) * abs(imgint2 - imgint1)) / (2*r^2);
其中a = [x1 y1]
和b = [x2 y2]
是表示图像像素的坐标,img
是灰度图像,r
和L
是常数。在函数imgint1
和是和imgint2
上像素的灰度强度。a
b
我需要计算图像的一组点之间的权重。
我想使用 pdist 函数而不是两个嵌套循环,因为它更快!
例如,让nodes
一组像素坐标
nodes =
1 1
1 2
2 1
2 2
和img = [ 128 254; 0 255]
, r = 3
,L = 255
为了获得这些权重,我使用了一个中间函数。
function [weight] = fxIntermediate(a,b, img, r, L)
weight = bsxfun(@(a,b) getWeight(a,b,img,r,L), a, b);
为了最终得到整套权重
distNodes = pdist(nodes,@(XI,XJ) fxIntermediate(XI,XJ,img,r,L));
但它总是给我一个错误
Error using pdist (line 373)
Error evaluating distance function '@(XI,XJ)fxIntermediate(XI,XJ,img,r,L)'.
Error in obtenerMatriz (line 27)
distNodes = pdist(nodes,@(XI,XJ) fxIntermediate(XI,XJ,img,r,L));
Caused by:
Error using bsxfun
Invalid output dimensions.
编辑 1
这是我的代码的一个简短示例,它应该可以工作,但我得到了上面提到的错误。如果您在 MATLAB 上复制/粘贴代码并运行代码,您将看到错误
function [adjacencyMatrix] = problem
img = [123, 229; 0, 45]; % 2x2 Image as example
nodes = [1 1; 1 2; 2 2]; % I want to calculate distance function getWeight()
% between pixels img(1,1), img(1,2), img(2,2)
r = 3; % r is a constant, doesn't matter its meaning
L = 255; % L is a constant, doesn't matter its meaning
distNodes = pdist(nodes,@(XI,XJ) fxIntermediate(XI,XJ,img,r,L));
adjacencyMatrix = squareform(distNodes );
end
function [weight] = fxIntermediate(a,b, img, r, L)
weight = bsxfun(@(a,b) getWeight(a,b,img,r,L), a, b);
end
function [weight] = getWeight(a,b,img, r, L)
ac = num2cell(a);
bc = num2cell(b);
imgint1 = img(sub2ind(size(img),ac{:}));
imgint2 = img(sub2ind(size(img),bc{:}));
weight = (sum((a - b) .^ 2) + (r^2/L) * abs(imgint2 - imgint1)) / (2*r^2);
end
我的目标是获得一个表示像素之间距离的邻接矩阵。对于上面的示例,所需的邻接矩阵是:
adjacencyMatrix =
0 0.2634 0.2641
0.2634 0 0.4163
0.2641 0.4163 0