要将OpenCV中的Mat转换为数组,并将其保存为bmp文件,您可以使用以下代码:
// 导入头文件
#include <opencv2/opencv.hpp>
using namespace cv;
int main() {
// 加载图片
Mat image = imread("image.jpg");
// 转换为数组
int height = image.rows;
int width = image.cols;
int channels = image.channels();
uchar* data = image.data;
// 保存为bmp
FILE* fp;
int filesize = 54 + height * width * channels;
unsigned char bmpfileheader[14] = {'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0};
unsigned char bmpinfoheader[40] = {40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int bmpfilesize = filesize - 54;
bmpinfoheader[4] = (unsigned char)(bmpfilesize);
bmpinfoheader[5] = (unsigned char)(bmpfilesize >> 8);
bmpinfoheader[6] = (unsigned char)(bmpfilesize >> 16);
bmpinfoheader[7] = (unsigned char)(bmpfilesize >> 24);
bmpinfoheader[8] = (unsigned char)(width);
bmpinfoheader[9] = (unsigned char)(width >> 8);
bmpinfoheader[10] = (unsigned char)(width >> 16);
bmpinfoheader[11] = (unsigned char)(width >> 24);
bmpinfoheader[12] = (unsigned char)(height);
bmpinfoheader[13] = (unsigned char)(height >> 8);
bmpinfoheader[14] = (unsigned char)(height >> 16);
bmpinfoheader[15] = (unsigned char)(height >> 24);
fp = fopen("image.bmp", "wb");
fwrite(bmpfileheader, 1, 14, fp);
fwrite(bmpinfoheader, 1, 40, fp);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
unsigned char color[3] = {0, 0, 0};
color[0] = data[(i * width + j) * channels + 2];
color[1] = data[(i * width + j) * channels + 1];
color[2] = data[(i * width + j) * channels];
fwrite(color, 1, 3, fp);
fclose(fp);
return 0;
上述代码中,首先使用imread
函数加载要保存为bmp的图像。然后,使用rows
和cols
函数获取图像的高度和宽度,使用channels
函数获取图像的通道数。接下来,将图像数据转换为数组形式,将其保存在指针data
中。
然后,计算bmp文件