创建binary类:
包括读取头文件,读取文件数据,显示等函数;
需要配置opencv。
#pragma once
#include<windows.h>
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
class binary
{
float* pbinaryBuf;//读入图像数据的指针
int binaryWidth;//图像的宽
int binaryHeight;//图像的高
int bands;//波段
int year;//年月日
int month;
int day;
typedef struct tagBINARYINFO
{
WORD Width;//图像的宽
WORD Height;//图像的高
WORD Bands;//图像波段
WORD Year;//年
WORD Month;//月
WORD Day;//日
}tagBINARYINFO;
typedef struct tagBINARYHEAD
{
char sensor[6];
}tagBINARYHEAD;
bool readbinaryhead(char* binaryname);//读取binary文件,获取相关参数
float* readBand(float* imgBuf, int k);//读取指定波段数据;
bool show(char* binaryname, float* imgBuf, int width, int height);//对所读取数据进行合成rgb图像
float** reshape(float** data, int m, int n);
public:
void doIt();
};
bool binary::readbinaryhead(char* binaryname)
{
FILE* fp = fopen(binaryname, "rb");//二进制读方式打开指定的图像文件
if (fp == 0)
return 0;
fseek(fp, sizeof(tagBINARYHEAD), 0);
tagBINARYINFO head;
fread(&head, sizeof(tagBINARYINFO), 1, fp); //获取图像宽、高、波段等信息
binaryWidth = head.Width;
binaryHeight = head.Height;
bands = head.Bands;
year = head.Year;
month = head.Month;
day = head.Day;
double widthstep = (double(binaryWidth) * 3 * sizeof(float) + 3) / 4 * 4;
pbinaryBuf = new float[widthstep * binaryHeight * bands];
fseek(fp, 22, 0);
fread(pbinaryBuf, sizeof(float), widthstep * binaryHeight * bands, fp);
fclose(fp);//关闭文件
return 1;//读取文件成功
}
float* binary::readBand(float* imgBuf, int k)
{
double widthstep = (double(binaryWidth) * 3 * sizeof(float) + 3) / 4 * 4;
float* image = new float[widthstep * binaryHeight];
for (int i = 0; i < binaryHeight; i++)
{
for (int j = 0; j < binaryWidth; j++)
{
image[i * binaryWidth + j] = imgBuf[binaryWidth * bands * i + binaryWidth * (k - 1) + j];
}
}
return image;
}
bool binary::show(char* binaryname, float* imgBuf, int width, int height)
{
if (!imgBuf)
return 0;
float** band = new float* [bands];
for (int i = 0; i < bands; i++)
{
band[i] = new float[double(width) * height];
}
for (int i = 0; i < bands; i++)
{
band[i] = readBand(imgBuf, i + 1);
}
delete[]pbinaryBuf;
Mat myimg(height, width, CV_32FC3);
for (int row = 0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
myimg.at<Vec3f>(row, col) = Vec3f(band[0][row * width + col], band[1][row * width + col], band[2][row * width + col]);
}
}
for (int i = 0; i < bands; i++)
{
delete[]band[i];
}
delete[]band;
imshow("读取影像", myimg / 2047);
cv::waitKey(0);
return 1;
}
void binary::doIt()
{
char readPath[] = "./binary_image";
readbinaryhead(readPath);
show(readPath, pbinaryBuf, binaryWidth, binaryHeight);
}
运行结果截图: