2015-11-03 41 views
2

我正在尝试将RGB值和坐标值从RGB图像写入文本文件,在下面提到的代码中,我正在使用鼠标光标获取值并尝试将这些RGB和坐标值保存到文本文件中。但是文本文件只保存终端输出的最后一个值。如何在文本文件中获取RGB值和坐标值?

这里是我的代码

#include <iostream> 
#include <stdio.h> 
#include <opencv2/opencv.hpp> 
#include <fstream> 

using namespace cv; 
using namespace std; 
Mat rgb; 
char window_name[20]="Pixel Value Demo"; 

static void onMouse(int event, int i, int j, int f, void*) 
{ 
    ofstream fout("output.txt"); 
    Vec3b pix=rgb.at<Vec3b>(j,i); 
    int Red=rgb.at<cv::Vec3b>(j,i)[2]; 
    int Green= rgb.at<cv::Vec3b>(j,i)[1]; 
    int Blue = rgb.at<cv::Vec3b>(j,i)[0]; 
    int y= rgb.at<cv::Vec3b>(j,i)[3]; 
    int x = rgb.at<cv::Vec3b>(j,i)[4]; 
    cout<<" x= "<<x<<" y= "<<y<<" Red="<<Red<<" Green="<<Green<<" Blue="<<Blue<<" \t\n"; 
    fout<<" x= "<<x<<" y= "<<y<<" Red="<<Red<<" Green="<<Green<<" Blue="<<Blue<<" \t\n"; 
    fout<<endl; 
    fout.close(); 
} 

int main(int argc, char** argv) 
{ 
    namedWindow(window_name, CV_WINDOW_AUTOSIZE); 
    rgb = imread("lena.jpg"); 
    imshow(window_name, rgb); 
    setMouseCallback(window_name, onMouse, 0); 
    waitKey(0); 
    return 0; 
} 

回答

3

您创建每个鼠标事件创建新的文件。使用在运行时保持打开状态的流,或者至少在打开流时设置附加模式。

例如: - 你可以在你的主写:

ofstream fout("output.txt"); 
setMouseCallback(window_name, onMouse, &fout); 
waitKey(0); 
fout.close(); 

而且事件处理中:

static void onMouse(int event, int i, int j, int f, void* p){ 
    ofstream *pfout = (ofstream*) p; 
    (*pfout) << "text"; 
    // do not close file here 
+0

可以PLZ给我一个例子。 – Jordan

+0

增加了一个示例 –

+0

感谢的代码工作得很好。 – Jordan