Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 16:49   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 更快版本的dec2bin函数可转换许多元素?

我正在读取一个位图文件,并将范围从0到255的每个 RGB值转换为二进制。

因此240 x 320位图将具有230400 RGB值进行转换。原始的dec2bin函数太慢,因此我写了自己的函数,因为我知道我的值将始终在0到255之间。

但是,通过230400值仍将花费大约。在我的机器上需要6秒,而一张彩色位图大约需要2.3秒。

有什么方法可以将速度提高到1秒以下甚至更好的0.5秒,因为每毫秒都取决于我的应用程序?

这是我的代码:

function s = dec2bin_2(input) if input == 255 s = [1;1;1;1;1;1;1;1]; return; end s = [0;0;0;0;0;0;0;0]; if input == 0 return; end if input >= 128 input = input - 128; s(1) = 1; if input == 0 return; end end if input >= 64 input = input - 64; s(2) = 1; if input == 0 return; end end if input >= 32 input = input - 32; s(3) = 1; if input == 0 return; end end if input >= 16 input = input - 16; s(4) = 1; if input == 0 return; end end if input >= 8 input = input - 8; s(5) = 1; if input == 0 return; end end if input >= 4 input = input - 4; s(6) = 1; if input == 0 return; end end if input >= 2 input = input - 2; s(7) = 1; if input == 0 return; else s(8) = 1; end end end 我在想如果我不能在MATLAB中完成此操作,那么也许我将在C ++中进行转换。这是明智的吗?

谢谢。


回答:
甚至更快的方法是使用查找表。由于您知道所有值都是0到255之间的强度,因此可以构造每个值的二进制等效项以加快处理速度。

% build table (computed once) [using gnovice option#1] lookupTable = cell2mat(arrayfun(@(i)bitget([0:255]',9-i),1:8,'UniformOutput',0)); % random' image I = randi(256, [240 320])-1; % decimal to binary conversion binI = lookupTable(I(:)+1,:); 在我的机器上,平均花费0.0036329秒(仅转换)。请注意,查找表几乎没有空间开销:

>> whos lookupTable Name Size Bytes Class Attributes lookupTable 256x8 2048 uint8

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 01:13


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.