Matlab allRGB图像生成

Matlab allRGB image generating

我正在为学校项目 script/function 工作,该项目将在 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');

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

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

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

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

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

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

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