gpt4 book ai didi

c++ - 难以编写多级 for 循环

转载 作者:行者123 更新时间:2023-11-28 01:41:05 24 4
gpt4 key购买 nike

我有一个暗淡的数组,其中存储了图像的像素。我正在尝试将其作为二维数组打印到文件中。

每张图片为28*28像素,数组包含60000张。

我对输出单个图像的数学没有问题:

void makeImage(const std::string& filename,const char * insertion, const unsigned int& width, const unsigned int & height)
{
int i = 0;
FILE *fp = fopen(filename.c_str(), "wb"); /* b - binary mode */
(void)fprintf(fp, "P6\n%d %d\n255\n", width, height);
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
static unsigned char color[3];
color[0] = *(insertion + i); /* red */
color[1] = *(insertion + i); /* green */
color[2] = *(insertion + i); /* blue */
(void)fwrite(color, 1, 3, fp);
i++;
}
}
(void)fclose(fp);
}

所以如果我去哪里:

makeimage("myfile.ppm",&myarray[0],28,28); //First image.
makeimage("myfile2.ppm",&myarray[785],28,28); //Second image. ext.

但是我想得到一张包含所有 60000 个图像的图像。作为 6860x6860 像素的图像。

但是做这件事的数学让我很头疼。

最佳答案

您无法将这些图像完全放入一个 60000 图像正方形中,但您可以做,例如,具有 600 行和 100 列的网格。 (生成的图像将为 16800 x 2800。)

我相信您可以处理 C++ 实现,所以这里是数学:

你有一组图像:

|----im1----||----im2----|....|----im60000----|

你想得到一张合成图片:

|----im1----||----im2----|....|----im600----|

|---im601---||---im602---|....|---im1200----|

...

|--im59401--||--im59402--|....|--im60000--|

这里有一些伪代码可以做到这一点。

for a in 600
for b in 28
for c in 100
for d in 28
result[100*28*(28*a + b) + 28*c + d] = arr[28*28*(100*a + c) + 28*b + d]

这里,result 是你的大输出图像,arr 是你的大输入数组。

基本上,第一个和第三个循环处理图像的位置,第二个和第四个循环处理当前图像中当前像素的位置。

它不是很漂亮,但它确实有效。我想您必须考虑颜色,但我假设您正在解析 MNIST 数据(60000 个 28x28 手写数字图像),我认为它是灰度的。

祝你的项目好运。

关于c++ - 难以编写多级 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47116510/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com