如何使用Matlab制作0和1的对角线分频器?

San*_*ong 1 matlab image-processing matrix diagonal

这是我想要的结果.位分辨率是256 x 256.

// assign default background to white.
img = ones(256, 256);
Run Code Online (Sandbox Code Playgroud)

结果示例:

0 1 1 1
0 0 1 1
0 0 0 1
0 0 0 0
Run Code Online (Sandbox Code Playgroud)

印在图中

有没有办法可以在MATLAB中使用zeros()ones()函数来实现这个结果?我该怎么做循环?

结果是eye()函数可以做的事情,但它只做一条对角线.我想要一条分开0和1的对角线.

Sha*_*hai 11

您正在寻找这个triu功能

img = triu( ones( 256 ), 1 );
Run Code Online (Sandbox Code Playgroud)


Div*_*kar 8

如果您关心性能,可以尝试bsxfun基于方法 -

n = 256; %// resolution of img would be nxn
img = bsxfun(@le,[1:n]',0:n-1);
Run Code Online (Sandbox Code Playgroud)

比较BSXFUN和TRIU的基准 -

num_runs = 50000; %// Number of iterations to run benchmarks
n =  256; %// nxn would be the resolution of image

%// Warm up tic/toc.
for k = 1:50000
    tic(); elapsed = toc();
end

disp(['For n = ' num2str(n) ' :'])
disp('---------------------- With bsxfun')
tic
for iter = 1:num_runs
    out1 = bsxfun(@le,[1:n]',0:n-1); %//'
end
time1 = toc;
disp(['Avg. elapsed time = ' num2str(time1/num_runs) ' sec(s)']),clear out1

disp('---------------------- With triu')
tic
for iter = 1:num_runs
    out2 = triu( true( n ), 1 );
end
time2 = toc;
disp(['Avg. elapsed time = ' num2str(time2/num_runs) ' sec(s)']),clear out2
Run Code Online (Sandbox Code Playgroud)

结果

For n = 256 :
---------------------- With bsxfun
Avg. elapsed time = 0.0001506 sec(s)
---------------------- With triu
Avg. elapsed time = 4.3082e-05 sec(s)

For n = 512 :
---------------------- With bsxfun
Avg. elapsed time = 0.00035545 sec(s)
---------------------- With triu
Avg. elapsed time = 0.00015582 sec(s)

For n = 1000 :
---------------------- With bsxfun
Avg. elapsed time = 0.0015711 sec(s)
---------------------- With triu
Avg. elapsed time = 0.0019307 sec(s)

For n = 2000 :
---------------------- With bsxfun
Avg. elapsed time = 0.0058759 sec(s)
---------------------- With triu
Avg. elapsed time = 0.0083544 sec(s)

For n = 3000 :
---------------------- With bsxfun
Avg. elapsed time = 0.01321 sec(s)
---------------------- With triu
Avg. elapsed time = 0.018275 sec(s)
Run Code Online (Sandbox Code Playgroud)

基准测试的结论

对于您的256x256大小问题,triu可能是首选方法,但对于足够大的数据量,可以考虑bsxfun提高50%的性能.

  • `bsxfun`一直令人印象深刻!总是找到一种巧妙的方式来使用它的信用......当我想到它时它会更快.通常,`bsxfun`会更快(与大多数其他函数相比),因为没有创建中间数组. (2认同)