【问题标题】:Matlab allRGB image generatingMatlab allRGB图像生成
【发布时间】:2018-06-05 17:02:19
【问题描述】:

我正在为学校项目编写脚本/函数,它将在 matlab 中生成所有 24 位 RGB 颜色图像。

我写了这样的东西,但它很慢(而且 matlab 不喜欢我并且经常崩溃)。上次崩溃前它工作了 5 天。 代码如下:

a = 1;
for r = 0:255
    for g = 0:255
        for b = 0:255
            colors(a,:) = [r g b];
            a = a + 1;
        end
    end
end

colors = reshape(colors, [4096, 4096, 3]);

colors = uint8(colors);
imshow(colors);
imwrite(colors, 'generated.png');

有没有更快的方法来做到这一点?

【问题讨论】:

    标签: image matlab image-processing rgb


    【解决方案1】:

    使用repmat/repelem分别构建三列,然后将它们连接起来。

    colors = [repelem((0:255).',256^2),...
              repmat([repelem((0:255).',256) repmat((0:255).',256,1)],256,1)];
    

    【讨论】:

    • 结果是二维的。如问题中所述,结果应该是 3D。
    • @OmG 这是 OP 循环的矢量化。 OP 正在做的其他事情保持不变。
    • 我知道,但 OP 怎么知道?!
    • 这似乎很明显。不是吗?
    【解决方案2】:

    预分配大型矩阵以加快代码速度通常是个好主意。在您当前的实现中,colors 的大小每次迭代都会增长一行,这需要大量的内存分配资源。尝试用

    定义你的矩阵
    colors = zeros(2^24, 3);
    

    在代码的开头。为了节省内存和时间,您甚至可以从一开始就将矩阵定义为uint8,而不是之后再进行转换

    colors = zeros(2^24, 3, 'uint8');
    

    【讨论】:

      猜你喜欢
      • 2014-04-07
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      相关资源
      最近更新 更多