【发布时间】:2015-04-22 15:47:28
【问题描述】:
我正在使用 open cv ,我在从视频中捕获图像时遇到了问题。 我的基本需求是,当视频在 open cv 中运行时,只要我单击鼠标程序的右键应该从视频中捕获图像,然后图像应该保存在任何位置。在保存的图像之后,我必须执行进一步的图像处理。 请任何人帮助我。
【问题讨论】:
-
OpenCV 支持鼠标回调。对于视频,它是逐帧读取的,因此,创建一个存储当前帧的全局变量,您就可以开始了。
我正在使用 open cv ,我在从视频中捕获图像时遇到了问题。 我的基本需求是,当视频在 open cv 中运行时,只要我单击鼠标程序的右键应该从视频中捕获图像,然后图像应该保存在任何位置。在保存的图像之后,我必须执行进一步的图像处理。 请任何人帮助我。
【问题讨论】:
这很简单。您需要鼠标回调、写入图像和运行剪辑,因此这是我为您提出问题的代码。
#include <iostream>
#include <string>
#include <sstream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
cv::Mat currentFrame;
static void onMouse( int event, int x, int y, int, void* )
{
static int count(0);
if ( event == cv::EVENT_RBUTTONDOWN ) {
std::stringstream ss;
ss << count;
std::string countStr = ss.str();
std::string imageName = "image_" + countStr;
std::string FullPath = "/home/xxxx/" + imageName + ".jpg";
cv::imwrite( FullPath, currentFrame );
std::cout << " image has been saved " << std::endl;
++count;
}
}
int main()
{
std::string clipFullPath = "/home/xxxx/drop.avi";
cv::VideoCapture clip(clipFullPath);
if ( !clip.isOpened() ){
std::cout << "Error: Could not open the video: " << std::endl;
return -1;
}
cv::namedWindow("Display", CV_WINDOW_AUTOSIZE);
cv::setMouseCallback("Display", onMouse, 0 );
for(;;){
clip >> currentFrame;
if ( currentFrame.empty() )
break;
cv::imshow("Display", currentFrame);
cv::waitKey(30);
}
return 0;
}
std::to_string() 需要 -std=c++11。如果您想通过 GUI 窗口保存图像,我认为您需要另一个库,例如支持此功能的 Qt。
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ $$$$$$$$$$$$$$$$$$$$$$$$
已编辑:OP 需要从网络摄像头而不是视频中捕获帧。
这是评论中您问题的代码。
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
cv::Mat frame;
static void onMouse( int event, int x, int y, int, void* )
{
static int count(0);
if ( event == cv::EVENT_RBUTTONDOWN ) {
std::stringstream ss;
ss << count;
std::string countStr = ss.str();
std::string imageName = "image_" + countStr;
std::string FullPath = imageName + ".jpg"; // save to the current directory
cv::imwrite( FullPath, frame );
std::cout << " image has been saved " << std::endl;
++count;
}
}
int main()
{
// access the default webcam
cv::VideoCapture cap(0);
// Double check the webcam before start reading.
if ( !cap.isOpened() ){
std::cerr << "Cannot open the webcam " << std::endl;
exit (EXIT_FAILURE);
}
cv::namedWindow("webcam",CV_WINDOW_AUTOSIZE);
cv::setMouseCallback("webcam", onMouse, 0 );
while ( true ){
// acquire frame
cap >> frame;
// Safety checking
if ( !frame.data ){
std::cerr << "Cannot acquire frame from the webcam " << std::endl;
break;
}
cv::imshow("webcam", frame);
if ( cv::waitKey(30) == 27){
std::cout << "esc key is pressed" << std::endl;
break;
}
}
return 0;
}
图像保存在可执行文件的目录中。在终端命令中(即我使用的是 Mac 和 OpenCV 2.4.11)
g++ main.cpp -o main -I/opt/local/include -L/opt/local/lib -lopencv_highgui.2.4.11 -lopencv_core.2.4.11
【讨论】:
g++ -std=c++11
cv::format("/some/path/%d.png", number);轻松避免字符串问题