C++对ascii文件按行和分隔符读取并显示


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;
}

结果截图展示:在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.癮.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值