DEC2BIN函数的快速版本转换许多元素? [英] Faster version of dec2bin function for converting many elements?

查看:92
本文介绍了DEC2BIN函数的快速版本转换许多元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读一个位图文件和RGB值范围从0到255之间的二进制转换的每个

I am reading a bitmap file and converting each of the RGB values ranging from 0 to 255 to binary.

因此​​,一个240×320的位图将有230400 RGB值转换。原来DEC2BIN函数是太慢了,所以我写了我自己,因为我知道我的价值永远是255 0之间。

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.3sec。

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?

下面是我的code:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆