使用vs2019,不引用库函数生成三层影像金字塔且可以输出图片的c语言代码
时间: 2023-06-19 07:05:23 浏览: 154
以下是一个简单的三层影像金字塔生成代码,使用C语言编写,不需要引用任何库函数。在Windows下使用VS2019进行编译运行。
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 256
#define HEIGHT 256
void generate_pyramid(unsigned char* image, unsigned char* pyramid)
{
int i, j, k;
int width = WIDTH, height = HEIGHT;
// 第一层
for (i = 0; i < height; i += 2)
{
for (j = 0; j < width; j += 2)
{
int idx = i * width + j;
pyramid[idx / 4] = image[idx];
}
}
// 第二层
width /= 2;
height /= 2;
for (k = 1; k < 3; k++)
{
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int idx = i * width * 2 + j * 2;
int idx1 = i * width + j;
int idx2 = (i + height) * width + j;
int idx3 = i * width + j + width;
int idx4 = (i + height) * width + j + width;
int sum = image[idx] + image[idx1] + image[idx2] + image[idx3] + image[idx4];
pyramid[(k * height * width + idx1) / 4] = sum / 5;
}
}
width /= 2;
height /= 2;
}
}
void write_image(const char* filename, unsigned char* image, int width, int height)
{
FILE* fp;
int i, j;
fp = fopen(filename, "wb");
if (!fp)
{
printf("Error: Couldn't open %s for writing!\n", filename);
return;
}
fprintf(fp, "P5\n%d %d\n255\n", width, height);
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
fputc(image[i * width + j], fp);
}
}
fclose(fp);
}
int main()
{
unsigned char* image = (unsigned char*)malloc(WIDTH * HEIGHT * sizeof(unsigned char));
unsigned char* pyramid = (unsigned char*)malloc(WIDTH * HEIGHT / 4 * sizeof(unsigned char));
int i, j;
// 生成一张随机的灰度图像
for (i = 0; i < HEIGHT; i++)
{
for (j = 0; j < WIDTH; j++)
{
image[i * WIDTH + j] = rand() % 256;
}
}
// 生成三层影像金字塔
generate_pyramid(image, pyramid);
// 输出三层影像金字塔
write_image("pyramid0.pgm", image, WIDTH, HEIGHT);
write_image("pyramid1.pgm", pyramid + WIDTH * HEIGHT / 16, WIDTH / 2, HEIGHT / 2);
write_image("pyramid2.pgm", pyramid + WIDTH * HEIGHT / 16 + WIDTH * HEIGHT / 64, WIDTH / 4, HEIGHT / 4);
free(image);
free(pyramid);
return 0;
}
```
这个代码生成一张随机的灰度图像,然后生成三层影像金字塔,并输出三层金字塔的图片。可以通过修改WIDTH和HEIGHT来调整图像的大小,也可以通过修改generate_pyramid函数来生成不同层数的金字塔。
阅读全文