2015-11-03 43 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