获取摄像头中的图像,通过鼠标选中点坐标并保存在txt中
#include <QCoreApplication>
#include <iostream>
#include <fstream>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
//设置一个全局变量保存onMouse函数获取的坐标点
cv::Point2f point;
//获取坐标点并保存在txt中
void onMouse(int event, int x, int y, int flags, void*)
{
if (event == cv::EVENT_LBUTTONDOWN)
{
//获取坐标
point = cv::Point2f(static_cast<float>(x), static_cast<float>(y));
std::cout << "click point is: " << point << std::endl;
//保存坐标
ofstream point_out;
point_out.open("point.txt", std::ios::out | std::ios::app); //以写入和在文件末尾添加的方式打开.txt文件,没有的话就创建该文件。
//如果没有文件那么就结束程序
if(!point_out.is_open()){
cout << "file open fail" << endl;
exit(0);
}
point_out << point << endl;
point_out.close();
}
}
int main(int argc, char *argv[])
{
std::string url = "url";
cv::VideoCapture cap(url);
cv::Mat mat;
//判断相机是否打开
if (!cap.isOpened()){
cout << "could not open camera" << endl;
return -1;
}
//从摄像头中获取一张图片并显示
cap.read(mat);
cv::namedWindow("source_image", cv::WINDOW_AUTOSIZE);
std::cout << "Please click points" << std::endl;
//点击图片获得坐标
cv::setMouseCallback("source_image", onMouse);
cv::imshow("source_image", mat);
cv::waitKey(0);
cap.release();
cv::destroyAllWindows();
}