版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengxianghui01/article/details/84891288
实现图像旋转,首先要对图像的存储,图像的读写比较清楚,在此基础上进行线性变换。以下代码为逆时针旋转90度,后续会给出旋转任意角度的代码:
核心还是掌握旋转时的前后变换。变换的过程可以归结为:首先将图像坐标变换为数学坐标,然后在数学坐标上进行变换,然后在进行逆变换,得到在图像坐标上的变换。同时需要求出各个变换的逆变换。
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *fp = fopen("./01.bmp", "rb");
if (fp == 0){
printf("文件打开失败\n");
return 0;
}
BITMAPFILEHEADER fileHead;
BITMAPINFOHEADER infoHead;
fread(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);
fread(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);
int width = infoHead.biWidth;
int height = infoHead.biHeight;
int biCount = infoHead.biBitCount;
int lineByte = (width*biCount / 8 + 3) / 4 * 4;
RGBQUAD *pColorTable;
pColorTable = new RGBQUAD[256];
fread(pColorTable, sizeof(RGBQUAD), 256, fp);
unsigned char *pBmpBuf;
pBmpBuf = new unsigned char[lineByte*height];
fread(pBmpBuf, lineByte*height, 1, fp);
fclose(fp);
// 右旋转90
unsigned char *pBmpBuf3;
int lineByte3 = (height*biCount / 8 + 3) / 4 * 4;
pBmpBuf3 = new unsigned char[lineByte3*width];
for (int i = 0; i < width; ++i){
for (int j = 0; j < height; ++j){
unsigned char *p;
p = (unsigned char *)(pBmpBuf3 + lineByte3*i + j);
(*p) = 255;
}
}
for (int i = 0; i < width; ++i){
for (int j = 0; j < height; ++j){
unsigned char *p,*p3;
p = (unsigned char *)(pBmpBuf + lineByte*j + i); // 原图像
p3 = (unsigned char *)(pBmpBuf3 + lineByte3*i + height-j-1);// 新图像
(*p3) = (*p);
}
}
FILE *fpo = fopen("./rotate90N.bmp", "wb");
if (fpo == 0)
return 0;
fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fpo);
BITMAPINFOHEADER infoHead3;
infoHead3.biBitCount = biCount;
infoHead3.biClrImportant = 0;
infoHead3.biClrUsed = 0;
infoHead3.biCompression = 0;
infoHead3.biHeight = width;
infoHead3.biPlanes = 1;
infoHead3.biSize = 40;
infoHead3.biSizeImage = lineByte3*width;
infoHead3.biWidth = height;
infoHead3.biXPelsPerMeter = 0;
infoHead3.biYPelsPerMeter = 0;
fwrite(&infoHead3, sizeof(BITMAPINFOHEADER), 1, fpo);
fwrite(pColorTable, sizeof(RGBQUAD), 256, fpo);
fwrite(pBmpBuf3, lineByte3*width, 1, fpo);
fclose(fpo);
system("pause");
return 1;
}
实验结果:
原图 逆时针旋转90度