我试图将下面的Matlab代码转换成C++,使用码元。但是,它在构建时失败了,我得到了错误:
“?除非指定‘行’,否则第一个输入必须是向量。如果向量是可变大小的,则第一维或第二维的长度必须固定为1。不支持输入[]。使用1乘0或0乘1的输入(例如零(1,0)或零(0,1))来表示空集。”
然后它指出id,m,n=唯一(Id);是罪魁祸首。为什么它不构建,什么是最好的方法来修复它?
function [L,num,sz] = label(I,n) %#codegen
% Check input arguments
error(nargchk(1,2,nargin));
if nargin==1, n=8; end
assert(ndims(I)==2,'The input I must be a 2-D array')
sizI = size(I);
id = reshape(1:prod(sizI),sizI);
sz = ones(sizI);
% Indexes of the adjacent pixels
vec = @(x) x(:);
if n==4 % 4-connected neighborhood
idx1 = [vec(id(:,1:end-1)); vec(id(1:end-1,:))];
idx2 = [vec(id(:,2:end)); vec(id(2:end,:))];
elseif n==8 % 8-connected neighborhood
idx1 = [vec(id(:,1:end-1)); vec(id(1:end-1,:))];
idx2 = [vec(id(:,2:end)); vec(id(2:end,:))];
idx1 = [idx1; vec(id(1:end-1,1:end-1)); vec(id(2:end,1:end-1))];
idx2 = [idx2; vec(id(2:end,2:end)); vec(id(1:end-1,2:end))];
else
error('The second input argument must be either 4 or 8.')
end
% Create the groups and merge them (Union/Find Algorithm)
for k = 1:length(idx1)
root1 = idx1(k);
root2 = idx2(k);
while root1~=id(root1)
id(root1) = id(id(root1));
root1 = id(root1);
end
while root2~=id(root2)
id(root2) = id(id(root2));
root2 = id(root2);
end
if root1==root2, continue, end
% (The two pixels belong to the same group)
N1 = sz(root1); % size of the group belonging to root1
N2 = sz(root2); % size of the group belonging to root2
if I(root1)==I(root2) % then merge the two groups
if N1 < N2
id(root1) = root2;
sz(root2) = N1+N2;
else
id(root2) = root1;
sz(root1) = N1+N2;
end
end
end
while 1
id0 = id;
id = id(id);
if isequal(id0,id), break, end
end
sz = sz(id);
% Label matrix
isNaNI = isnan(I);
id(isNaNI) = NaN;
[id,m,n] = unique(id);
I = 1:length(id);
L = reshape(I(n),sizI);
L(isNaNI) = 0;
if nargout>1, num = nnz(~isnan(id)); end 发布于 2014-09-16 20:48:44
只是一个FYI,如果您正在使用MATLAB R2013b或更新,您可以用narginchk(1,2)代替error(nargchk(1,2,nargin))。
正如错误消息所指出的,对于codegen unique,除非“行”被传递,否则输入必须是一个向量。
如果您查看报告(单击所显示的"Open“链接)并将其悬停在id上,您可能会发现它的大小既不是1-by-N也不是N-by-1。如果在这里搜索unique,可以看到对unique的需求:
http://www.mathworks.com/help/coder/ug/functions-supported-for-code-generation--alphabetical-list.html
你可以做几件事之一:
使id成为向量,并将其视为计算的向量。而不是声明:
id = reshape(1:prod(sizI),sizI);你可以用:
id = 1:numel(I)那么id将是一个行向量。
您还可以保持代码原样,并执行如下操作:
[idtemp,m,n] = unique(id(:));
id = reshape(idtemp,size(id));显然,这将导致复制,idtemp,但它可能涉及较少的更改您的代码。
发布于 2014-09-16 23:03:39
vec中的匿名函数,并使vec成为子函数:
函数y= vec(x) coder.inline(‘vec’);y= x(:);'rows'选项,unique函数的输入总是被解释为向量,而输出始终是向量。例如,如果矩阵id = unique(id)的所有元素都是唯一的,那么像id = id(:)这样的东西就会产生id = id(:)的效果。将输入作为向量输入是无害的。所以换行吧
id,m,n=唯一(Id);至
[id,m,n] = unique(id(:));https://stackoverflow.com/questions/25839277
复制相似问题