C++对ascii文件的读取和显示
步骤:
1.在已知文件头部行数情况下,读取文件头部获取文件信息
2.根据文件头部读取信息创建相关数组存储文件下方数据
3.cv创建矩阵,转换数据并显示
#include<iostream>
#include<sstream>
#include<fstream>
#include<cstdlib>
#include<cstdio>
#include<iomanip>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
const int maxsize = 1000;
typedef struct Band
{
int data[maxsize][maxsize];
}Band;
typedef struct Ascii_image
{
double imageWidth;//图像的宽
double imageHeight;//图像的高
double nbands;//图像的波段数
double cellsize;//图像像素大小
Band bands[4];
}Ascii_image;
int main()
{
ifstream inf;
inf.open("F://ascii_image.txt");
string sline;//每一行
string out;
char* s1 = new char[10];
double s2 = 0;
int i = 0, j = 0, n = 0;
struct Ascii_image* image = NULL;
image = (Ascii_image*)malloc(sizeof(Ascii_image) * 2);
while (getline(inf, sline) && image != NULL)
{
if (sline.empty())
{
n++;
j = 0;
}
else if (i < 6)
{
istringstream sin(sline);
sin >> s1 >> s2;
if (strcmp(s1, "ncols") == 0)
image->imageWidth = s2;
if (strcmp(s1, "nrows") == 0)
image->imageHeight = s2;
if (strcmp(s1, "nbands") == 0)
image->nbands = s2;
if (strcmp(s1, "cellsize") == 0)
image->cellsize = s2;
i++;
}
else
{
istringstream sin(sline);
for (int k = 0; k < image->imageWidth; k++)
{
sin >> image->bands[n].data[j][k];
}
j++;
}
}
if (image != NULL)
{
Mat myimg(image->imageHeight, image->imageWidth, CV_8UC3);
//取像素数据首地址
for (int row = 0; row < myimg.rows; row++)
{
for (int col = 0; col < myimg.cols; col++)
{
myimg.at<Vec3b>(row, col) = Vec3b(image->bands[0].data[row][col], image->bands[1].data[row][col], image->bands[2].data[row][col]);
}
}
imshow("new", myimg * 10);
cv::waitKey(0);
}
return 0;
}
结果截图展示: