使用vs2019,不引用库函数生成三层影像金字塔且可以输出图片的c语言代码
时间: 2023-06-19 16:05:30 浏览: 168
以下是使用C语言生成三层影像金字塔的简单示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image.h"
#include "stb_image_write.h"
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: %s <input_image>\n", argv[0]);
return 1;
}
int width, height, channels;
unsigned char *image_data = stbi_load(argv[1], &width, &height, &channels, 0);
if (!image_data)
{
printf("Failed to load image %s\n", argv[1]);
return 1;
}
// Allocate memory for pyramid levels
unsigned char *level1_data = malloc(width / 2 * height / 2 * channels);
unsigned char *level2_data = malloc(width / 4 * height / 4 * channels);
// Downsample first level
int level1_width = width / 2;
int level1_height = height / 2;
for (int y = 0; y < level1_height; y++)
{
for (int x = 0; x < level1_width; x++)
{
for (int c = 0; c < channels; c++)
{
int index = (y * 2 * width + x * 2) * channels + c;
int sum = image_data[index] + image_data[index + 1] + image_data[index + width * 2] + image_data[index + width * 2 + 1];
level1_data[(y * level1_width + x) * channels + c] = sum / 4;
}
}
}
// Downsample second level
int level2_width = width / 4;
int level2_height = height / 4;
for (int y = 0; y < level2_height; y++)
{
for (int x = 0; x < level2_width; x++)
{
for (int c = 0; c < channels; c++)
{
int index = (y * 2 * level1_width + x * 2) * channels + c;
int sum = level1_data[index] + level1_data[index + 1] + level1_data[index + level1_width * 2] + level1_data[index + level1_width * 2 + 1];
level2_data[(y * level2_width + x) * channels + c] = sum / 4;
}
}
}
// Save pyramid levels to files
char *filename = malloc(strlen(argv[1]) + 10);
strcpy(filename, argv[1]);
char *dot = strrchr(filename, '.');
if (dot)
{
*dot = '\0';
}
stbi_write_png(strcat(filename, "_level0.png"), width, height, channels, image_data, width * channels);
stbi_write_png(strcat(filename, "_level1.png"), level1_width, level1_height, channels, level1_data, level1_width * channels);
stbi_write_png(strcat(filename, "_level2.png"), level2_width, level2_height, channels, level2_data, level2_width * channels);
// Free memory
stbi_image_free(image_data);
free(level1_data);
free(level2_data);
free(filename);
return 0;
}
```
这个示例代码使用了STB库来加载和保存PNG图像。要使用这个库,只需要在代码中包含 `"stb_image.h"` 和 `"stb_image_write.h"` 文件,并定义 `STB_IMAGE_IMPLEMENTATION` 和 `STB_IMAGE_WRITE_IMPLEMENTATION` 宏。这些宏告诉编译器在编译时包含库的实现代码。
请注意,这个示例代码中的金字塔级别是硬编码的。如果您想生成不同数量或不同大小的级别,请相应地修改代码。
阅读全文