给我用C++生成影像金字塔的代码
时间: 2023-06-11 14:09:26 浏览: 94
以下是使用C语言生成影像金字塔的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define MAX_LEVELS 10
typedef struct {
unsigned char *data;
int width, height, channels;
} Image;
Image load_image(char *filename) {
Image img;
img.data = stbi_load(filename, &img.width, &img.height, &img.channels, 0);
return img;
}
void free_image(Image *img) {
if (img->data) {
stbi_image_free(img->data);
img->data = NULL;
}
img->width = img->height = img->channels = 0;
}
void save_image(char *filename, Image img) {
stbi_write_png(filename, img.width, img.height, img.channels, img.data, img.width * img.channels);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s input_image\n", argv[0]);
return 1;
}
Image src = load_image(argv[1]);
if (!src.data) {
fprintf(stderr, "Error: cannot load image '%s'\n", argv[1]);
return 1;
}
Image pyr[MAX_LEVELS];
pyr[0] = src;
int levels = 1;
while (levels < MAX_LEVELS) {
Image prev = pyr[levels - 1];
Image next;
next.width = prev.width / 2;
next.height = prev.height / 2;
next.channels = prev.channels;
next.data = malloc(next.width * next.height * next.channels);
for (int i = 0; i < next.height; i++) {
for (int j = 0; j < next.width; j++) {
for (int k = 0; k < next.channels; k++) {
int idx = (i * 2) * prev.width * prev.channels + (j * 2) * prev.channels + k;
next.data[i * next.width * next.channels + j * next.channels + k] = prev.data[idx];
}
}
}
pyr[levels] = next;
levels++;
if (next.width < 2 || next.height < 2) {
break;
}
}
for (int i = 0; i < levels; i++) {
char filename[256];
sprintf(filename, "level_%d.png", i);
save_image(filename, pyr[i]);
}
for (int i = 0; i < levels; i++) {
free_image(&pyr[i]);
}
free_image(&src);
return 0;
}
```
这个程序可以读取一个图像文件,然后生成一组影像金字塔图像,每一层的分辨率是上一层的一半。在程序中,我们使用了stb_image和stb_image_write库来读取和写入图像文件。请注意,这个程序只支持处理RGB图像,如果需要处理其他类型的图像,需要进行一些修改。
阅读全文