c++ 彩色图转灰度图
时间: 2023-12-22 08:27:55 浏览: 144
以下是C++将彩色图转换为灰度图的代码示例:
```c++
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
using namespace std;
#pragma pack(push, 1)
typedef struct {
unsigned short bfType;
unsigned int bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned int bfOffBits;
} BITMAPFILEHEADER;
typedef struct {
unsigned int biSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned int biCompression;
unsigned int biSizeImage;
int biXPelsPerMeter;
int biYPelsPerMeter;
unsigned int biClrUsed;
unsigned int biClrImportant;
} BITMAPINFOHEADER;
typedef struct {
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
unsigned char rgbReserved;
} RGBQUAD;
typedef struct {
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
RGBQUAD *palette;
unsigned char *data;
} BMP;
#pragma pack(pop)
BMP* readBmp(char* filename) {
BMP* bmp = new BMP;
ifstream file(filename, ios::binary);
if (!file) {
cout << "Error: could not open file " << filename << endl;
exit(1);
}
file.read((char*)&bmp->fileHeader, sizeof(BITMAPFILEHEADER));
file.read((char*)&bmp->infoHeader, sizeof(BITMAPINFOHEADER));
if (bmp->infoHeader.biBitCount <= 8) {
bmp->palette = new RGBQUAD[1 << bmp->infoHeader.biBitCount];
file.read((char*)bmp->palette, sizeof(RGBQUAD) * (1 << bmp->infoHeader.biBitCount));
}
bmp->data = new unsigned char[bmp->infoHeader.biSizeImage];
file.seekg(bmp->fileHeader.bfOffBits, ios::beg);
file.read((char*)bmp->data, bmp->infoHeader.biSizeImage);
file.close();
return bmp;
}
void writeBmp(char* filename, BMP* bmp) {
ofstream file(filename, ios::binary);
if (!file) {
cout << "Error: could not open file " << filename << endl;
exit(1);
}
file.write((char*)&bmp->fileHeader, sizeof(BITMAPFILEHEADER));
file.write((char*)&bmp->infoHeader, sizeof(BITMAPINFOHEADER));
if (bmp->infoHeader.biBitCount <= 8) {
file.write((char*)bmp->palette, sizeof(RGBQUAD) * (1 << bmp->infoHeader.biBitCount));
}
file.write((char*)bmp->data, bmp->infoHeader.biSizeImage);
file.close();
}
void rgb2gray(BMP* bmp) {
if (bmp->infoHeader.biBitCount != 24) {
cout << "Error: only support 24-bit color depth" << endl;
exit(1);
}
int width = bmp->infoHeader.biWidth;
int height = bmp->infoHeader.biHeight;
int lineByte = (width * 24 + 31) / 32 * 4;
unsigned char* data = bmp->data;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int b = data[i * lineByte + j * 3];
int g = data[i * lineByte + j * 3 + 1];
int r = data[i * lineByte + j * 3 + 2];
int gray = (r * 19595 + g * 38469 + b * 7472) >> 16;
data[i * lineByte + j * 3] = gray;
data[i * lineByte + j * 3 + 1] = gray;
data[i * lineByte + j * 3 + 2] = gray;
}
}
}
int main() {
BMP* bmp = readBmp("color.bmp");
rgb2gray(bmp);
writeBmp("gray.bmp", bmp);
delete[] bmp->palette;
delete[] bmp->data;
delete bmp;
return 0;
}
```
阅读全文