用于转换许多元素的更快版本的 dec2bin 函数? [英] Faster version of dec2bin function for converting many elements?
问题描述
我正在读取一个位图文件并将 每个从 0 到 255 的 RGB 值转换为二进制.
I am reading a bitmap file and converting each of the RGB values ranging from 0 to 255 to binary.
因此,一个 240 x 320 的位图将有 230400 个 RGB 值进行转换.原来的 dec2bin 函数太慢了,所以我自己写了,因为我知道我的值总是在 0 到 255 之间.
So a 240 by 320 bitmap will have 230400 RGB values to convert. The original dec2bin function was too slow, so I wrote my own as I know my value will always be between 0 to 255.
但是通过 230400 个值仍然需要大约.在我的机器上是 6 秒,单色位图大约需要 2.3 秒.
But going through 230400 values will still take approx. 6sec on my machine, and a single colour bitmap will take about 2.3sec.
是否有任何方法可以将速度提高到 1 秒以下甚至更好的 0.5 秒,因为我的应用程序每毫秒都很重要?
Is there anyway to speed things up to be under 1sec or even better 0.5sec, as every msec counts for my application?
这是我的代码:
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++ 中进行转换.这是可取的吗?
I was thinking if I'm not able to do it in MATLAB then maybe I'll do the conversion in C++. Is this advisable?
谢谢.
推荐答案
更快的方法是使用查找表.由于您知道所有值都是 0 到 255 之间的强度,因此您可以构造每个值的二进制等效项以加快处理速度.
An even faster way is to use lookup tables. Since you know all the values are intensities between 0 and 255, you construct the binary equivalent of each to speed up the process.
% 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 秒(仅转换).注意查找表几乎没有空间开销:
On my machine, it took on average 0.0036329 seconds (only the conversion). Note the lookup table has almost no space overhead:
>> whos lookupTable
Name Size Bytes Class Attributes
lookupTable 256x8 2048 uint8
这篇关于用于转换许多元素的更快版本的 dec2bin 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!