Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我正在读取一个位图文件,并将范围从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 更多&回答... |
![]() |
![]() |