写一个图像旋转的c++代码
时间: 2024-03-15 21:19:05 浏览: 13
以下是一个简单的图像旋转C代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265
int main() {
FILE *input_file, *output_file;
int width, height, maxval, x, y, new_x, new_y;
int angle = 45; // 旋转角度
double radians = angle * PI / 180.0;
unsigned char *image_data, *rotated_data;
input_file = fopen("input.pgm", "rb");
output_file = fopen("output.pgm", "wb");
// 读取PGM文件头信息
fscanf(input_file, "P5\n%d %d\n%d\n", &width, &height, &maxval);
// 分配图像数据内存
image_data = (unsigned char *) malloc(width * height * sizeof(unsigned char));
rotated_data = (unsigned char *) malloc(width * height * sizeof(unsigned char));
// 读取图像数据
fread(image_data, sizeof(unsigned char), width * height, input_file);
// 计算旋转后的图像尺寸
int new_width = abs(width * cos(radians)) + abs(height * sin(radians));
int new_height = abs(width * sin(radians)) + abs(height * cos(radians));
// 计算旋转后的中心点
int center_x = width / 2;
int center_y = height / 2;
// 逐像素旋转
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
// 计算旋转后的像素位置
new_x = (x - center_x) * cos(radians) - (y - center_y) * sin(radians) + center_x;
new_y = (x - center_x) * sin(radians) + (y - center_y) * cos(radians) + center_y;
// 将旋转后的像素写入新图像
rotated_data[new_y * new_width + new_x] = image_data[y * width + x];
}
}
// 写入PGM文件头信息
fprintf(output_file, "P5\n%d %d\n%d\n", new_width, new_height, maxval);
// 写入旋转后的图像数据
fwrite(rotated_data, sizeof(unsigned char), new_width * new_height, output_file);
// 释放内存和关闭文件
free(image_data);
free(rotated_data);
fclose(input_file);
fclose(output_file);
return 0;
}
```
上述代码是一个简单的图像旋转示例,使用了简单的几何计算来计算每个像素的旋转后位置。要使用此代码,请将输入图像命名为“input.pgm”,并将输出图像命名为“output.pgm”,然后在执行代码时运行它。