在vs2019中用C语言对灰度图像进行1/4下采样
时间: 2024-01-26 19:03:56 浏览: 95
下采样是将图像的分辨率降低,可以通过对像素点进行平均或者隔行/列采样的方式实现。下面是在vs2019中用C语言对灰度图像进行1/4下采样的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WIDTH 640 // 图像宽度
#define HEIGHT 480 // 图像高度
#define FACTOR 4 // 采样因子
int main()
{
// 读入灰度图像
FILE* fp = fopen("lena_gray.raw", "rb");
unsigned char* img = (unsigned char*)malloc(WIDTH * HEIGHT * sizeof(unsigned char));
fread(img, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
// 1/4下采样
int new_w = WIDTH / FACTOR;
int new_h = HEIGHT / FACTOR;
unsigned char* new_img = (unsigned char*)malloc(new_w * new_h * sizeof(unsigned char));
for (int i = 0; i < new_h; i++) {
for (int j = 0; j < new_w; j++) {
int sum = 0;
for (int k = 0; k < FACTOR; k++) {
for (int l = 0; l < FACTOR; l++) {
sum += img[(i * FACTOR + k) * WIDTH + (j * FACTOR + l)];
}
}
new_img[i * new_w + j] = sum / (FACTOR * FACTOR);
}
}
// 保存下采样后的图像
fp = fopen("lena_gray_downsampled.raw", "wb");
fwrite(new_img, sizeof(unsigned char), new_w * new_h, fp);
fclose(fp);
// 释放内存
free(img);
free(new_img);
return 0;
}
```
在上述代码中,我们先读入灰度图像,然后对图像进行1/4下采样,最后保存下采样后的图像。具体来说,我们遍历新图像的每个像素,计算其在原图像中对应的像素的平均值,作为新图像中该像素的值。最后,我们释放内存,程序结束。
阅读全文