我想使用C/C++旋轉BMP圖像,但它不工作。C/C++旋轉BMP圖像
我已經做了一些讀,寫和旋轉的功能,讀寫工作完美,但沒有,並且由於某種原因旋轉。
EDIT(正弦,餘弦和旋轉功能)
BMP的結構:
struct BMP {
int width;
int height;
unsigned char header[54];
unsigned char *pixels;
int size;
};
WRITE:
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);
}
READ:
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;
}
ROTATE:
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;
}
MAIN:
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度旋轉。
這是我的original image,在這裏它的那一刻my result in
請你能球員之一,讓我已瞭解我在做什麼錯在這裏?我真的需要這個功能讓它工作。並且請不要向我建議一些可以幫助我這樣做的庫,因爲我需要使用代碼來完成這項工作特有的任何庫。
而在同一時間,請不要讓類似「去閱讀BMP頭」,因爲我alread這樣做幾
我希望你能幫助我這個...評論我真的需要它。
在旋轉中,newImage = image。因此,您在旋轉時覆蓋圖像像素。 – stark
假設光柵順序 – samgak
@samgak應該對旋轉方向產生一些影響,我認爲PIxel尋址應該是'[y * image.width + x]'。但無論如何它不能正常工作......我編輯了我的**旋轉功能**添加了新的結果以及您說了些什麼。而在這一刻......我之前有一個更奇怪的結果。 – Mircea