opencv从txt文本读取像素点并显示
文本储存格式为每行一个像素点,排列为RGB。每帧图像的帧头为65535. 如下图所示
废话不多说,代码如下:
//
#include <iostream>
#include <opencv2\opencv.hpp>
#include <fstream>
#include <string>
#include <WINSOCK2.H>
#include <STDIO.H> #define MAX 32
using namespace cv;
using namespace std; Vec3b GetPoint( void )
{
Vec3b pixels; //声明像素点储存变量//static int64 count = 0;cout<<count++<<endl;
char Buf[MAX];//声明一个buf,用来储存一行
//声明三个空格,用于分割像素点
int firstspace = ; int secondspace = ; int thirdspace = ;
//读取一行数据
cin.getline(Buf,MAX);
//如果读到的是个回车或者换行,则继续读
while(Buf[] == '\0'||Buf[] == ' ' ) cin.getline(Buf,MAX);
//遍历整个buf,找到三个空格的位置
for(int i = ;i < MAX ;i ++ )
{
if(Buf[i] == ' ')
{
if(firstspace != && secondspace != && thirdspace ==) thirdspace =i;
if(firstspace != && secondspace == ) secondspace = i;
if(firstspace == ) firstspace = i; } }
//将三个空格之间的像素点解码储存
for(int i = ; i < firstspace; i++) { pixels[] += (Buf[i] - )*pow(,firstspace--i); }
for(int i = firstspace+; i < secondspace; i++) { pixels[] += (Buf[i] - )*pow(,secondspace--i); }
for(int i = secondspace+; i < thirdspace; i++) { pixels[] += (Buf[i] - )*pow(,thirdspace--i); }
//抛出这个像素点
return pixels;
} int main(int argc, char* argv[])
{
//首先定义一个图像buf,并初始化为0 ,此处一定要初始化图像大小和通道数,否则迭代器无法使用
Mat ReceiveImage = Mat::zeros(,,CV_8UC3);
//声名一个窗口用于显示
namedWindow("picture");
//声明buf,用于缓冲入的储存单个字符
char ReadBuf;
//声明帧头判断标志位
int flag = ;
//输入流重定向,将输入流定向到相应文件,定向错误则退出
if(freopen("rgb.txt","r", stdin) == NULL ) { fprintf(stderr,"open error"); return -;}
//进入循环读图模式
while()
{ //帧头判断
if(flag != )
{
cin>>ReadBuf;
if(ReadBuf == '' && flag == ) flag = ;
else if(ReadBuf == '' && flag == ) flag = ;
else if(ReadBuf == '' && flag == ) flag = ;
else if(ReadBuf == '' && flag == ) flag = ;
else if(ReadBuf == '' && flag == ) flag = ;
else flag = ;
}else{ flag = ;
//迭代器读图储存
Mat_<Vec3b>::iterator itbeg = ReceiveImage.begin<Vec3b>() ;
Mat_<Vec3b>::iterator itend = ReceiveImage.end<Vec3b>() ;
for( ;itbeg != itend ;itbeg++ )
{ *itbeg = GetPoint(); }
imshow("picture",ReceiveImage);
waitKey();
}
}
return ;
}