【发布时间】:2016-11-15 22:55:39
【问题描述】:
我正在尝试使用 C/C++ 旋转 BMP 图像,但它不起作用。
我已经制作了一些用于读取、写入和旋转的函数。读取和写入功能工作正常,但由于某种原因无法旋转。
编辑(正弦、余弦和旋转函数)
BMP 结构:
struct BMP {
int width;
int height;
unsigned char header[54];
unsigned char *pixels;
int size;
};
写:
void writeBMP(string filename, BMP image) {
string fileName = "Output Files/" + filename;
FILE *out = fopen(fileName.c_str(), "wb");
fwrite(image.header, sizeof(unsigned char), 54, out);
int i;
unsigned char tmp;
for (i = 0; i < image.size; i += 3) {
tmp = image.pixels[i];
image.pixels[i] = image.pixels[i + 2];
image.pixels[i + 2] = tmp;
}
fwrite(image.pixels, sizeof(unsigned char), image.size, out); // read the rest of the data at once
fclose(out);
}
阅读:
BMP readBMP(string filename) {
BMP image;
int i;
string fileName = "Input Files/" + filename;
FILE *f = fopen(fileName.c_str(), "rb");
fread(image.header, sizeof(unsigned char), 54, f); // read the 54-byte header
// extract image height and width from header
image.width = *(int *) &image.header[18];
image.height = *(int *) &image.header[22];
image.size = 3 * image.width * image.height;
image.pixels = new unsigned char[image.size]; // allocate 3 bytes per pixel
fread(image.pixels, sizeof(unsigned char), image.size, f); // read the rest of the data at once
fclose(f);
for (i = 0; i < image.size; i += 3) {
unsigned char tmp = image.pixels[i];
image.pixels[i] = image.pixels[i + 2];
image.pixels[i + 2] = tmp;
}
return image;
}
旋转:
BMP rotate(BMP image, double degree) {
BMP newImage = image;
unsigned char *pixels = new unsigned char[image.size];
double radians = (degree * M_PI) / 180;
int sinf = (int) sin(radians);
int cosf = (int) cos(radians);
double x0 = 0.5 * (image.width - 1); // point to rotate about
double y0 = 0.5 * (image.height - 1); // center of image
// rotation
for (int x = 0; x < image.width; x++) {
for (int y = 0; y < image.height; y++) {
long double a = x - x0;
long double b = y - y0;
int xx = (int) (+a * cosf - b * sinf + x0);
int yy = (int) (+a * sinf + b * cosf + y0);
if (xx >= 0 && xx < image.width && yy >= 0 && yy < image.height) {
pixels[(y * image.height + x) * 3 + 0] = image.pixels[(yy * image.height + xx) * 3 + 0];
pixels[(y * image.height + x) * 3 + 1] = image.pixels[(yy * image.height + xx) * 3 + 1];
pixels[(y * image.height + x) * 3 + 2] = image.pixels[(yy * image.height + xx) * 3 + 2];
}
}
}
newImage.pixels = pixels;
return newImage;
}
主要:
int main() {
BMP image = readBMP("InImage_2.bmp");
image = rotate(image,180);
writeBMP("Output-11.bmp", image);
return 0;
}
sin=0.8939966636(弧度)和cos=-0.44807361612(弧度)表示这张图片应该旋转90度。
这是我的原图:
现在是我的结果:
有人可以帮我理解我在这里做错了什么吗?我真的需要这个功能。
我不能为此代码使用任何第三方库。
【问题讨论】:
-
在旋转中,newImage = image。因此,您在旋转时会覆盖图像像素。
-
PIxel 寻址应该是
[y * image.width + x],假设是光栅顺序 -
@samgak 我认为应该对旋转方向产生一些影响。但无论如何它都不起作用...我已经编辑了我的 旋转函数 添加了新结果以及您所说的内容。而在这一刻……我有一个比以前更奇怪的结果。
-
我会说问题是因为你截断了 sin 和 cos: int sinf = (int) sin(radians); int cosf = (int) cos(弧度);通常的做法是将浮点数保留到最后一刻。
标签: c++ c bitmap rotation bitmapimage