我正在读取位图文件并进行转换each范围从 0 到 255 的 RGB 值的二进制。
因此,240 x 320 位图将有 230400 个 RGB 值需要转换。原来的 dec2bin 函数太慢了,所以我编写了自己的函数,因为我知道我的值始终在 0 到 255 之间。
但遍历 230400 个值仍需要大约 10 分钟。在我的机器上需要 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++ 中进行转换。这是可取的吗?
Thanks.
更快的方法是使用查找表。由于您知道所有值的强度都在 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)