导航

opencv从txt文本读取像素点并显示

Posted on 2016-11-25 16:12  Joekk  阅读(714)  评论(0编辑  收藏  举报

                                                                     opencv从txt文本读取像素点并显示

文本储存格式为每行一个像素点,排列为RGB。每帧图像的帧头为65535.  如下图所示

 65535 
24 28 16 
24 28 16 
32 32 24 
32 32 32 
32 32 32 
40 40 40 
56 60 56 
88 88 88 
112 112 112 
112 120 112 
112 124 120 

废话不多说,代码如下:

//
#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 = 0; int secondspace = 0; int thirdspace = 0;
    //读取一行数据
    cin.getline(Buf,MAX);
    //如果读到的是个回车或者换行,则继续读
    while(Buf[0] == '\0'||Buf[0] == ' ' ) cin.getline(Buf,MAX);
    //遍历整个buf,找到三个空格的位置
    for(int i = 0 ;i < MAX ;i ++ )
    {
        if(Buf[i] == ' ') 
        {
            if(firstspace  != 0 && secondspace != 0 && thirdspace ==0) thirdspace =i;
            if(firstspace  != 0 && secondspace == 0)  secondspace = i;
            if(firstspace  == 0) firstspace  = i;
            
        }

    }
    //将三个空格之间的像素点解码储存
    for(int i = 0; i < firstspace; i++)              {  pixels[2] += (Buf[i] - 48)*pow(10,firstspace-1-i);   }
    for(int i = firstspace+1; i < secondspace; i++)  {  pixels[1] += (Buf[i] - 48)*pow(10,secondspace-1-i);   }
    for(int i = secondspace+1; i < thirdspace; i++)  {  pixels[0] += (Buf[i] - 48)*pow(10,thirdspace-1-i);   }
    //抛出这个像素点
    return pixels;
}

int main(int argc, char* argv[])
{
    //首先定义一个图像buf,并初始化为0 ,此处一定要初始化图像大小和通道数,否则迭代器无法使用
    Mat ReceiveImage = Mat::zeros(200,200,CV_8UC3);
    //声名一个窗口用于显示
    namedWindow("picture");
    //声明buf,用于缓冲入的储存单个字符
    char  ReadBuf; 
    //声明帧头判断标志位
    int flag = 0;
    //输入流重定向,将输入流定向到相应文件,定向错误则退出
    if(freopen("rgb.txt","r", stdin) == NULL )   {  fprintf(stderr,"open error"); return -1;}
    //进入循环读图模式
        while(1) 
        {    //帧头判断
            if(flag != 5)
            {  
                cin>>ReadBuf; 
                if(ReadBuf == '6' && flag == 0)  flag = 1;
                else if(ReadBuf == '5' && flag == 1)  flag = 2;
                else if(ReadBuf == '5' && flag == 2)  flag = 3;
                else if(ReadBuf == '3' && flag == 3)  flag = 4;
                else if(ReadBuf == '5' && flag == 4)  flag = 5; 
                else  flag = 0;
            }else{                                    flag = 0;
                  //迭代器读图储存
                 Mat_<Vec3b>::iterator itbeg = ReceiveImage.begin<Vec3b>() ; 
                 Mat_<Vec3b>::iterator itend = ReceiveImage.end<Vec3b>()   ;
                 for( ;itbeg != itend ;itbeg++ )
                 {         *itbeg = GetPoint();   }
                 imshow("picture",ReceiveImage);
                  waitKey(0);
            }
        }
    return 0;
}