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;
}
可以PLZ給我一個例子。 – Jordan
增加了一個示例 –
感謝的代碼工作得很好。 – Jordan